blob: d94bf07f9e8c649911023bdc1ef878f88df6d3d3 [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 Enderbyac9e1552016-05-17 17:10:12 +00001214 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
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 Enderbyac9e1552016-05-17 17:10:12 +00001247 if (SymbolTable) {
1248 StringRef ArchiveName = ArchiveMemberName == StringRef() ? "" : Filename;
1249 PrintSymbolTable(MachOOF, ArchiveName);
1250 }
Kevin Enderby98da6132015-01-20 21:47:46 +00001251 if (UnwindInfo)
1252 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001253 if (PrivateHeaders) {
1254 printMachOFileHeader(MachOOF);
1255 printMachOLoadCommands(MachOOF);
1256 }
1257 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001258 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001259 if (ObjcMetaData)
1260 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001261 if (ExportsTrie)
1262 printExportsTrie(MachOOF);
1263 if (Rebase)
1264 printRebaseTable(MachOOF);
1265 if (Bind)
1266 printBindTable(MachOOF);
1267 if (LazyBind)
1268 printLazyBindTable(MachOOF);
1269 if (WeakBind)
1270 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001271
1272 if (DwarfDumpType != DIDT_Null) {
1273 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1274 // Dump the complete DWARF structure.
1275 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1276 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001277}
1278
Kevin Enderby131d1772015-01-09 19:22:37 +00001279// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1280static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1281 outs() << " cputype (" << cputype << ")\n";
1282 outs() << " cpusubtype (" << cpusubtype << ")\n";
1283}
1284
1285// printCPUType() helps print_fat_headers by printing the cputype and
1286// pusubtype (symbolically for the one's it knows about).
1287static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1288 switch (cputype) {
1289 case MachO::CPU_TYPE_I386:
1290 switch (cpusubtype) {
1291 case MachO::CPU_SUBTYPE_I386_ALL:
1292 outs() << " cputype CPU_TYPE_I386\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1294 break;
1295 default:
1296 printUnknownCPUType(cputype, cpusubtype);
1297 break;
1298 }
1299 break;
1300 case MachO::CPU_TYPE_X86_64:
1301 switch (cpusubtype) {
1302 case MachO::CPU_SUBTYPE_X86_64_ALL:
1303 outs() << " cputype CPU_TYPE_X86_64\n";
1304 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1305 break;
1306 case MachO::CPU_SUBTYPE_X86_64_H:
1307 outs() << " cputype CPU_TYPE_X86_64\n";
1308 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1309 break;
1310 default:
1311 printUnknownCPUType(cputype, cpusubtype);
1312 break;
1313 }
1314 break;
1315 case MachO::CPU_TYPE_ARM:
1316 switch (cpusubtype) {
1317 case MachO::CPU_SUBTYPE_ARM_ALL:
1318 outs() << " cputype CPU_TYPE_ARM\n";
1319 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1320 break;
1321 case MachO::CPU_SUBTYPE_ARM_V4T:
1322 outs() << " cputype CPU_TYPE_ARM\n";
1323 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1324 break;
1325 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1326 outs() << " cputype CPU_TYPE_ARM\n";
1327 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1328 break;
1329 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1330 outs() << " cputype CPU_TYPE_ARM\n";
1331 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1332 break;
1333 case MachO::CPU_SUBTYPE_ARM_V6:
1334 outs() << " cputype CPU_TYPE_ARM\n";
1335 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1336 break;
1337 case MachO::CPU_SUBTYPE_ARM_V6M:
1338 outs() << " cputype CPU_TYPE_ARM\n";
1339 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1340 break;
1341 case MachO::CPU_SUBTYPE_ARM_V7:
1342 outs() << " cputype CPU_TYPE_ARM\n";
1343 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1344 break;
1345 case MachO::CPU_SUBTYPE_ARM_V7EM:
1346 outs() << " cputype CPU_TYPE_ARM\n";
1347 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1348 break;
1349 case MachO::CPU_SUBTYPE_ARM_V7K:
1350 outs() << " cputype CPU_TYPE_ARM\n";
1351 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1352 break;
1353 case MachO::CPU_SUBTYPE_ARM_V7M:
1354 outs() << " cputype CPU_TYPE_ARM\n";
1355 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1356 break;
1357 case MachO::CPU_SUBTYPE_ARM_V7S:
1358 outs() << " cputype CPU_TYPE_ARM\n";
1359 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1360 break;
1361 default:
1362 printUnknownCPUType(cputype, cpusubtype);
1363 break;
1364 }
1365 break;
1366 case MachO::CPU_TYPE_ARM64:
1367 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1368 case MachO::CPU_SUBTYPE_ARM64_ALL:
1369 outs() << " cputype CPU_TYPE_ARM64\n";
1370 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1371 break;
1372 default:
1373 printUnknownCPUType(cputype, cpusubtype);
1374 break;
1375 }
1376 break;
1377 default:
1378 printUnknownCPUType(cputype, cpusubtype);
1379 break;
1380 }
1381}
1382
1383static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1384 bool verbose) {
1385 outs() << "Fat headers\n";
1386 if (verbose)
1387 outs() << "fat_magic FAT_MAGIC\n";
1388 else
1389 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1390
1391 uint32_t nfat_arch = UB->getNumberOfObjects();
1392 StringRef Buf = UB->getData();
1393 uint64_t size = Buf.size();
1394 uint64_t big_size = sizeof(struct MachO::fat_header) +
1395 nfat_arch * sizeof(struct MachO::fat_arch);
1396 outs() << "nfat_arch " << UB->getNumberOfObjects();
1397 if (nfat_arch == 0)
1398 outs() << " (malformed, contains zero architecture types)\n";
1399 else if (big_size > size)
1400 outs() << " (malformed, architectures past end of file)\n";
1401 else
1402 outs() << "\n";
1403
1404 for (uint32_t i = 0; i < nfat_arch; ++i) {
1405 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1406 uint32_t cputype = OFA.getCPUType();
1407 uint32_t cpusubtype = OFA.getCPUSubType();
1408 outs() << "architecture ";
1409 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1410 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1411 uint32_t other_cputype = other_OFA.getCPUType();
1412 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001413 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001414 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001415 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001416 outs() << "(illegal duplicate architecture) ";
1417 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001418 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001419 }
1420 if (verbose) {
1421 outs() << OFA.getArchTypeName() << "\n";
1422 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1423 } else {
1424 outs() << i << "\n";
1425 outs() << " cputype " << cputype << "\n";
1426 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1427 << "\n";
1428 }
1429 if (verbose &&
1430 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1431 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1432 else
1433 outs() << " capabilities "
1434 << format("0x%" PRIx32,
1435 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1436 outs() << " offset " << OFA.getOffset();
1437 if (OFA.getOffset() > size)
1438 outs() << " (past end of file)";
1439 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1440 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1441 outs() << "\n";
1442 outs() << " size " << OFA.getSize();
1443 big_size = OFA.getOffset() + OFA.getSize();
1444 if (big_size > size)
1445 outs() << " (past end of file)";
1446 outs() << "\n";
1447 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1448 << ")\n";
1449 }
1450}
1451
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001452static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001453 bool print_offset) {
1454 if (print_offset)
1455 outs() << C.getChildOffset() << "\t";
1456 sys::fs::perms Mode = C.getAccessMode();
1457 if (verbose) {
1458 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1459 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1460 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001461 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1462 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1463 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1464 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1465 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1466 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1467 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1468 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1469 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001470 } else {
1471 outs() << format("0%o ", Mode);
1472 }
1473
1474 unsigned UID = C.getUID();
1475 outs() << format("%3d/", UID);
1476 unsigned GID = C.getGID();
1477 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001478 ErrorOr<uint64_t> Size = C.getRawSize();
1479 if (std::error_code EC = Size.getError())
1480 report_fatal_error(EC.message());
1481 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001482
1483 StringRef RawLastModified = C.getRawLastModified();
1484 if (verbose) {
1485 unsigned Seconds;
1486 if (RawLastModified.getAsInteger(10, Seconds))
1487 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1488 else {
1489 // Since cime(3) returns a 26 character string of the form:
1490 // "Sun Sep 16 01:03:52 1973\n\0"
1491 // just print 24 characters.
1492 time_t t = Seconds;
1493 outs() << format("%.24s ", ctime(&t));
1494 }
1495 } else {
1496 outs() << RawLastModified << " ";
1497 }
1498
1499 if (verbose) {
1500 ErrorOr<StringRef> NameOrErr = C.getName();
1501 if (NameOrErr.getError()) {
1502 StringRef RawName = C.getRawName();
1503 outs() << RawName << "\n";
1504 } else {
1505 StringRef Name = NameOrErr.get();
1506 outs() << Name << "\n";
1507 }
1508 } else {
1509 StringRef RawName = C.getRawName();
1510 outs() << RawName << "\n";
1511 }
1512}
1513
1514static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001515 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1516 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001517 if (std::error_code EC = I->getError())
1518 report_fatal_error(EC.message());
1519 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001520 printArchiveChild(C, verbose, print_offset);
1521 }
1522}
1523
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001524// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1525// -arch flags selecting just those slices as specified by them and also parses
1526// archive files. Then for each individual Mach-O file ProcessMachO() is
1527// called to process the file based on the command line options.
1528void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001529 // Check for -arch all and verifiy the -arch flags are valid.
1530 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1531 if (ArchFlags[i] == "all") {
1532 ArchAll = true;
1533 } else {
1534 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1535 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1536 "'for the -arch option\n";
1537 return;
1538 }
1539 }
1540 }
1541
1542 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001543 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1544 if (!BinaryOrErr)
1545 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001546 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001547
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001548 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1549 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001550 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001551 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001552 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1553 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001554 if (std::error_code EC = I->getError())
1555 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001556 auto &C = I->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001557 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1558 if (!ChildOrErr) {
1559 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1560 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001561 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001562 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001563 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1564 if (!checkMachOAndArchFlags(O, Filename))
1565 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001566 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001567 }
1568 }
1569 return;
1570 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001571 if (UniversalHeaders) {
1572 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001573 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001574 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001575 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1576 // If we have a list of architecture flags specified dump only those.
1577 if (!ArchAll && ArchFlags.size() != 0) {
1578 // Look for a slice in the universal binary that matches each ArchFlag.
1579 bool ArchFound;
1580 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1581 ArchFound = false;
1582 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1583 E = UB->end_objects();
1584 I != E; ++I) {
1585 if (ArchFlags[i] == I->getArchTypeName()) {
1586 ArchFound = true;
1587 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1588 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001589 std::string ArchitectureName = "";
1590 if (ArchFlags.size() > 1)
1591 ArchitectureName = I->getArchTypeName();
1592 if (ObjOrErr) {
1593 ObjectFile &O = *ObjOrErr.get();
1594 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001595 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001596 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1597 I->getAsArchive()) {
1598 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001599 outs() << "Archive : " << Filename;
1600 if (!ArchitectureName.empty())
1601 outs() << " (architecture " << ArchitectureName << ")";
1602 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001603 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001604 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001605 for (Archive::child_iterator AI = A->child_begin(),
1606 AE = A->child_end();
1607 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001608 if (std::error_code EC = AI->getError())
1609 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001610 auto &C = AI->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001611 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1612 if (!ChildOrErr) {
1613 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1614 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001615 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001616 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001617 if (MachOObjectFile *O =
1618 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001619 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001620 }
1621 }
1622 }
1623 }
1624 if (!ArchFound) {
1625 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1626 << "architecture: " + ArchFlags[i] + "\n";
1627 return;
1628 }
1629 }
1630 return;
1631 }
1632 // No architecture flags were specified so if this contains a slice that
1633 // matches the host architecture dump only that.
1634 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001635 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1636 E = UB->end_objects();
1637 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001638 if (MachOObjectFile::getHostArch().getArchName() ==
1639 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001640 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001641 std::string ArchiveName;
1642 ArchiveName.clear();
1643 if (ObjOrErr) {
1644 ObjectFile &O = *ObjOrErr.get();
1645 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001646 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001647 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1648 I->getAsArchive()) {
1649 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001650 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001651 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001652 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001653 for (Archive::child_iterator AI = A->child_begin(),
1654 AE = A->child_end();
1655 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001656 if (std::error_code EC = AI->getError())
1657 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001658 auto &C = AI->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001659 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1660 if (!ChildOrErr) {
1661 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1662 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001663 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001664 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001665 if (MachOObjectFile *O =
1666 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001667 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001668 }
1669 }
1670 return;
1671 }
1672 }
1673 }
1674 // Either all architectures have been specified or none have been specified
1675 // and this does not contain the host architecture so dump all the slices.
1676 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1677 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1678 E = UB->end_objects();
1679 I != E; ++I) {
1680 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001681 std::string ArchitectureName = "";
1682 if (moreThanOneArch)
1683 ArchitectureName = I->getArchTypeName();
1684 if (ObjOrErr) {
1685 ObjectFile &Obj = *ObjOrErr.get();
1686 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001687 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001688 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1689 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001690 outs() << "Archive : " << Filename;
1691 if (!ArchitectureName.empty())
1692 outs() << " (architecture " << ArchitectureName << ")";
1693 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001694 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001695 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001696 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1697 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001698 if (std::error_code EC = AI->getError())
1699 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001700 auto &C = AI->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001701 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1702 if (!ChildOrErr) {
1703 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1704 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001705 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001706 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001707 if (MachOObjectFile *O =
1708 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1709 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001710 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1711 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001712 }
1713 }
1714 }
1715 }
1716 return;
1717 }
1718 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1719 if (!checkMachOAndArchFlags(O, Filename))
1720 return;
1721 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001722 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001723 } else
1724 errs() << "llvm-objdump: '" << Filename << "': "
1725 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001726 return;
1727 }
1728 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001729}
1730
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001731typedef std::pair<uint64_t, const char *> BindInfoEntry;
1732typedef std::vector<BindInfoEntry> BindTable;
1733typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001734
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001735// The block of info used by the Symbolizer call backs.
1736struct DisassembleInfo {
1737 bool verbose;
1738 MachOObjectFile *O;
1739 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001740 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001741 std::vector<SectionRef> *Sections;
1742 const char *class_name;
1743 const char *selector_name;
1744 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001745 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001746 uint64_t adrp_addr;
1747 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001748 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001749 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001750};
1751
1752// SymbolizerGetOpInfo() is the operand information call back function.
1753// This is called to get the symbolic information for operand(s) of an
1754// instruction when it is being done. This routine does this from
1755// the relocation information, symbol table, etc. That block of information
1756// is a pointer to the struct DisassembleInfo that was passed when the
1757// disassembler context was created and passed to back to here when
1758// called back by the disassembler for instruction operands that could have
1759// relocation information. The address of the instruction containing operand is
1760// at the Pc parameter. The immediate value the operand has is passed in
1761// op_info->Value and is at Offset past the start of the instruction and has a
1762// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1763// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1764// names and addends of the symbolic expression to add for the operand. The
1765// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1766// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001767static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1768 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001769 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1770 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001771 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001772
1773 // Make sure all fields returned are zero if we don't set them.
1774 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1775 op_info->Value = value;
1776
1777 // If the TagType is not the value 1 which it code knows about or if no
1778 // verbose symbolic information is wanted then just return 0, indicating no
1779 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001780 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001781 return 0;
1782
1783 unsigned int Arch = info->O->getArch();
1784 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001785 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1786 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001787 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1788 // TODO:
1789 // Search the external relocation entries of a fully linked image
1790 // (if any) for an entry that matches this segment offset.
1791 // uint32_t seg_offset = (Pc + Offset);
1792 return 0;
1793 }
1794 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1795 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001796 uint32_t sect_addr = info->S.getAddress();
1797 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1798 bool reloc_found = false;
1799 DataRefImpl Rel;
1800 MachO::any_relocation_info RE;
1801 bool isExtern = false;
1802 SymbolRef Symbol;
1803 bool r_scattered = false;
1804 uint32_t r_value, pair_r_value, r_type;
1805 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001806 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001807 if (RelocOffset == sect_offset) {
1808 Rel = Reloc.getRawDataRefImpl();
1809 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001810 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001811 r_scattered = info->O->isRelocationScattered(RE);
1812 if (r_scattered) {
1813 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001814 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1815 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1816 DataRefImpl RelNext = Rel;
1817 info->O->moveRelocationNext(RelNext);
1818 MachO::any_relocation_info RENext;
1819 RENext = info->O->getRelocation(RelNext);
1820 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001821 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001822 else
1823 return 0;
1824 }
1825 } else {
1826 isExtern = info->O->getPlainRelocationExternal(RE);
1827 if (isExtern) {
1828 symbol_iterator RelocSym = Reloc.getSymbol();
1829 Symbol = *RelocSym;
1830 }
1831 }
1832 reloc_found = true;
1833 break;
1834 }
1835 }
1836 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001837 Expected<StringRef> SymName = Symbol.getName();
1838 if (!SymName) {
1839 std::string Buf;
1840 raw_string_ostream OS(Buf);
1841 logAllUnhandledErrors(SymName.takeError(), OS, "");
1842 OS.flush();
1843 report_fatal_error(Buf);
1844 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001845 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001846 op_info->AddSymbol.Present = 1;
1847 op_info->AddSymbol.Name = name;
1848 // For i386 extern relocation entries the value in the instruction is
1849 // the offset from the symbol, and value is already set in op_info->Value.
1850 return 1;
1851 }
1852 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1853 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001854 const char *add = GuessSymbolName(r_value, info->AddrMap);
1855 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001856 uint32_t offset = value - (r_value - pair_r_value);
1857 op_info->AddSymbol.Present = 1;
1858 if (add != nullptr)
1859 op_info->AddSymbol.Name = add;
1860 else
1861 op_info->AddSymbol.Value = r_value;
1862 op_info->SubtractSymbol.Present = 1;
1863 if (sub != nullptr)
1864 op_info->SubtractSymbol.Name = sub;
1865 else
1866 op_info->SubtractSymbol.Value = pair_r_value;
1867 op_info->Value = offset;
1868 return 1;
1869 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001870 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001871 }
1872 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001873 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1874 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001875 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1876 // TODO:
1877 // Search the external relocation entries of a fully linked image
1878 // (if any) for an entry that matches this segment offset.
1879 // uint64_t seg_offset = (Pc + Offset);
1880 return 0;
1881 }
1882 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1883 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001884 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001885 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1886 bool reloc_found = false;
1887 DataRefImpl Rel;
1888 MachO::any_relocation_info RE;
1889 bool isExtern = false;
1890 SymbolRef Symbol;
1891 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001892 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001893 if (RelocOffset == sect_offset) {
1894 Rel = Reloc.getRawDataRefImpl();
1895 RE = info->O->getRelocation(Rel);
1896 // NOTE: Scattered relocations don't exist on x86_64.
1897 isExtern = info->O->getPlainRelocationExternal(RE);
1898 if (isExtern) {
1899 symbol_iterator RelocSym = Reloc.getSymbol();
1900 Symbol = *RelocSym;
1901 }
1902 reloc_found = true;
1903 break;
1904 }
1905 }
1906 if (reloc_found && isExtern) {
1907 // The Value passed in will be adjusted by the Pc if the instruction
1908 // adds the Pc. But for x86_64 external relocation entries the Value
1909 // is the offset from the external symbol.
1910 if (info->O->getAnyRelocationPCRel(RE))
1911 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001912 Expected<StringRef> SymName = Symbol.getName();
1913 if (!SymName) {
1914 std::string Buf;
1915 raw_string_ostream OS(Buf);
1916 logAllUnhandledErrors(SymName.takeError(), OS, "");
1917 OS.flush();
1918 report_fatal_error(Buf);
1919 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001920 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001921 unsigned Type = info->O->getAnyRelocationType(RE);
1922 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1923 DataRefImpl RelNext = Rel;
1924 info->O->moveRelocationNext(RelNext);
1925 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1926 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1927 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1928 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1929 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1930 op_info->SubtractSymbol.Present = 1;
1931 op_info->SubtractSymbol.Name = name;
1932 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1933 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001934 Expected<StringRef> SymNameNext = Symbol.getName();
1935 if (!SymNameNext) {
1936 std::string Buf;
1937 raw_string_ostream OS(Buf);
1938 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1939 OS.flush();
1940 report_fatal_error(Buf);
1941 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001942 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001943 }
1944 }
1945 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1946 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1947 op_info->AddSymbol.Present = 1;
1948 op_info->AddSymbol.Name = name;
1949 return 1;
1950 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001951 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001952 }
1953 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001954 if (Offset != 0 || (Size != 4 && Size != 2))
1955 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001956 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1957 // TODO:
1958 // Search the external relocation entries of a fully linked image
1959 // (if any) for an entry that matches this segment offset.
1960 // uint32_t seg_offset = (Pc + Offset);
1961 return 0;
1962 }
1963 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1964 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001965 uint32_t sect_addr = info->S.getAddress();
1966 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001967 DataRefImpl Rel;
1968 MachO::any_relocation_info RE;
1969 bool isExtern = false;
1970 SymbolRef Symbol;
1971 bool r_scattered = false;
1972 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001973 auto Reloc =
1974 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1975 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001976 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001977 return RelocOffset == sect_offset;
1978 });
1979
1980 if (Reloc == info->S.relocations().end())
1981 return 0;
1982
1983 Rel = Reloc->getRawDataRefImpl();
1984 RE = info->O->getRelocation(Rel);
1985 r_length = info->O->getAnyRelocationLength(RE);
1986 r_scattered = info->O->isRelocationScattered(RE);
1987 if (r_scattered) {
1988 r_value = info->O->getScatteredRelocationValue(RE);
1989 r_type = info->O->getScatteredRelocationType(RE);
1990 } else {
1991 r_type = info->O->getAnyRelocationType(RE);
1992 isExtern = info->O->getPlainRelocationExternal(RE);
1993 if (isExtern) {
1994 symbol_iterator RelocSym = Reloc->getSymbol();
1995 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001996 }
1997 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001998 if (r_type == MachO::ARM_RELOC_HALF ||
1999 r_type == MachO::ARM_RELOC_SECTDIFF ||
2000 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2001 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2002 DataRefImpl RelNext = Rel;
2003 info->O->moveRelocationNext(RelNext);
2004 MachO::any_relocation_info RENext;
2005 RENext = info->O->getRelocation(RelNext);
2006 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2007 if (info->O->isRelocationScattered(RENext))
2008 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2009 }
2010
2011 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002012 Expected<StringRef> SymName = Symbol.getName();
2013 if (!SymName) {
2014 std::string Buf;
2015 raw_string_ostream OS(Buf);
2016 logAllUnhandledErrors(SymName.takeError(), OS, "");
2017 OS.flush();
2018 report_fatal_error(Buf);
2019 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002020 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002021 op_info->AddSymbol.Present = 1;
2022 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002023 switch (r_type) {
2024 case MachO::ARM_RELOC_HALF:
2025 if ((r_length & 0x1) == 1) {
2026 op_info->Value = value << 16 | other_half;
2027 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2028 } else {
2029 op_info->Value = other_half << 16 | value;
2030 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002031 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002032 break;
2033 default:
2034 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002035 }
2036 return 1;
2037 }
2038 // If we have a branch that is not an external relocation entry then
2039 // return 0 so the code in tryAddingSymbolicOperand() can use the
2040 // SymbolLookUp call back with the branch target address to look up the
2041 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002042 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2043 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002044 return 0;
2045
2046 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002047 if (r_type == MachO::ARM_RELOC_HALF ||
2048 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2049 if ((r_length & 0x1) == 1)
2050 value = value << 16 | other_half;
2051 else
2052 value = other_half << 16 | value;
2053 }
2054 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2055 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2056 offset = value - r_value;
2057 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002058 }
2059
David Blaikie33dd45d02015-03-23 18:39:02 +00002060 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002061 if ((r_length & 0x1) == 1)
2062 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2063 else
2064 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002065 const char *add = GuessSymbolName(r_value, info->AddrMap);
2066 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002067 int32_t offset = value - (r_value - pair_r_value);
2068 op_info->AddSymbol.Present = 1;
2069 if (add != nullptr)
2070 op_info->AddSymbol.Name = add;
2071 else
2072 op_info->AddSymbol.Value = r_value;
2073 op_info->SubtractSymbol.Present = 1;
2074 if (sub != nullptr)
2075 op_info->SubtractSymbol.Name = sub;
2076 else
2077 op_info->SubtractSymbol.Value = pair_r_value;
2078 op_info->Value = offset;
2079 return 1;
2080 }
2081
Kevin Enderby930fdc72014-11-06 19:00:13 +00002082 op_info->AddSymbol.Present = 1;
2083 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002084 if (r_type == MachO::ARM_RELOC_HALF) {
2085 if ((r_length & 0x1) == 1)
2086 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2087 else
2088 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002089 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002090 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002091 if (add != nullptr) {
2092 op_info->AddSymbol.Name = add;
2093 return 1;
2094 }
2095 op_info->AddSymbol.Value = value;
2096 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002097 }
2098 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002099 if (Offset != 0 || Size != 4)
2100 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002101 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2102 // TODO:
2103 // Search the external relocation entries of a fully linked image
2104 // (if any) for an entry that matches this segment offset.
2105 // uint64_t seg_offset = (Pc + Offset);
2106 return 0;
2107 }
2108 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2109 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002110 uint64_t sect_addr = info->S.getAddress();
2111 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002112 auto Reloc =
2113 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2114 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002115 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002116 return RelocOffset == sect_offset;
2117 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002118
David Blaikie33dd45d02015-03-23 18:39:02 +00002119 if (Reloc == info->S.relocations().end())
2120 return 0;
2121
2122 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2123 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2124 uint32_t r_type = info->O->getAnyRelocationType(RE);
2125 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2126 DataRefImpl RelNext = Rel;
2127 info->O->moveRelocationNext(RelNext);
2128 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2129 if (value == 0) {
2130 value = info->O->getPlainRelocationSymbolNum(RENext);
2131 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002132 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002133 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002134 // NOTE: Scattered relocations don't exist on arm64.
2135 if (!info->O->getPlainRelocationExternal(RE))
2136 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002137 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2138 if (!SymName) {
2139 std::string Buf;
2140 raw_string_ostream OS(Buf);
2141 logAllUnhandledErrors(SymName.takeError(), OS, "");
2142 OS.flush();
2143 report_fatal_error(Buf);
2144 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002145 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002146 op_info->AddSymbol.Present = 1;
2147 op_info->AddSymbol.Name = name;
2148
2149 switch (r_type) {
2150 case MachO::ARM64_RELOC_PAGE21:
2151 /* @page */
2152 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2153 break;
2154 case MachO::ARM64_RELOC_PAGEOFF12:
2155 /* @pageoff */
2156 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2157 break;
2158 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2159 /* @gotpage */
2160 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2161 break;
2162 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2163 /* @gotpageoff */
2164 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2165 break;
2166 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2167 /* @tvlppage is not implemented in llvm-mc */
2168 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2169 break;
2170 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2171 /* @tvlppageoff is not implemented in llvm-mc */
2172 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2173 break;
2174 default:
2175 case MachO::ARM64_RELOC_BRANCH26:
2176 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2177 break;
2178 }
2179 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002180 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002181 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002182}
2183
Kevin Enderbybf246f52014-09-24 23:08:22 +00002184// GuessCstringPointer is passed the address of what might be a pointer to a
2185// literal string in a cstring section. If that address is in a cstring section
2186// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002187static const char *GuessCstringPointer(uint64_t ReferenceValue,
2188 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002189 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002190 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2191 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2192 for (unsigned J = 0; J < Seg.nsects; ++J) {
2193 MachO::section_64 Sec = info->O->getSection64(Load, J);
2194 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2195 if (section_type == MachO::S_CSTRING_LITERALS &&
2196 ReferenceValue >= Sec.addr &&
2197 ReferenceValue < Sec.addr + Sec.size) {
2198 uint64_t sect_offset = ReferenceValue - Sec.addr;
2199 uint64_t object_offset = Sec.offset + sect_offset;
2200 StringRef MachOContents = info->O->getData();
2201 uint64_t object_size = MachOContents.size();
2202 const char *object_addr = (const char *)MachOContents.data();
2203 if (object_offset < object_size) {
2204 const char *name = object_addr + object_offset;
2205 return name;
2206 } else {
2207 return nullptr;
2208 }
2209 }
2210 }
2211 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2212 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2213 for (unsigned J = 0; J < Seg.nsects; ++J) {
2214 MachO::section Sec = info->O->getSection(Load, J);
2215 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2216 if (section_type == MachO::S_CSTRING_LITERALS &&
2217 ReferenceValue >= Sec.addr &&
2218 ReferenceValue < Sec.addr + Sec.size) {
2219 uint64_t sect_offset = ReferenceValue - Sec.addr;
2220 uint64_t object_offset = Sec.offset + sect_offset;
2221 StringRef MachOContents = info->O->getData();
2222 uint64_t object_size = MachOContents.size();
2223 const char *object_addr = (const char *)MachOContents.data();
2224 if (object_offset < object_size) {
2225 const char *name = object_addr + object_offset;
2226 return name;
2227 } else {
2228 return nullptr;
2229 }
2230 }
2231 }
2232 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002233 }
2234 return nullptr;
2235}
2236
Kevin Enderby85974882014-09-26 22:20:44 +00002237// GuessIndirectSymbol returns the name of the indirect symbol for the
2238// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2239// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2240// symbol name being referenced by the stub or pointer.
2241static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2242 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002243 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2244 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002245 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002246 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2247 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2248 for (unsigned J = 0; J < Seg.nsects; ++J) {
2249 MachO::section_64 Sec = info->O->getSection64(Load, J);
2250 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2251 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2252 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2253 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2254 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2255 section_type == MachO::S_SYMBOL_STUBS) &&
2256 ReferenceValue >= Sec.addr &&
2257 ReferenceValue < Sec.addr + Sec.size) {
2258 uint32_t stride;
2259 if (section_type == MachO::S_SYMBOL_STUBS)
2260 stride = Sec.reserved2;
2261 else
2262 stride = 8;
2263 if (stride == 0)
2264 return nullptr;
2265 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2266 if (index < Dysymtab.nindirectsyms) {
2267 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002268 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002269 if (indirect_symbol < Symtab.nsyms) {
2270 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2271 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002272 Expected<StringRef> SymName = Symbol.getName();
2273 if (!SymName) {
2274 std::string Buf;
2275 raw_string_ostream OS(Buf);
2276 logAllUnhandledErrors(SymName.takeError(), OS, "");
2277 OS.flush();
2278 report_fatal_error(Buf);
2279 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002280 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002281 return name;
2282 }
2283 }
2284 }
2285 }
2286 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2287 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2288 for (unsigned J = 0; J < Seg.nsects; ++J) {
2289 MachO::section Sec = info->O->getSection(Load, J);
2290 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2291 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2292 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2293 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2294 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2295 section_type == MachO::S_SYMBOL_STUBS) &&
2296 ReferenceValue >= Sec.addr &&
2297 ReferenceValue < Sec.addr + Sec.size) {
2298 uint32_t stride;
2299 if (section_type == MachO::S_SYMBOL_STUBS)
2300 stride = Sec.reserved2;
2301 else
2302 stride = 4;
2303 if (stride == 0)
2304 return nullptr;
2305 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2306 if (index < Dysymtab.nindirectsyms) {
2307 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002308 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002309 if (indirect_symbol < Symtab.nsyms) {
2310 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2311 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002312 Expected<StringRef> SymName = Symbol.getName();
2313 if (!SymName) {
2314 std::string Buf;
2315 raw_string_ostream OS(Buf);
2316 logAllUnhandledErrors(SymName.takeError(), OS, "");
2317 OS.flush();
2318 report_fatal_error(Buf);
2319 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002320 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002321 return name;
2322 }
2323 }
2324 }
2325 }
2326 }
Kevin Enderby85974882014-09-26 22:20:44 +00002327 }
2328 return nullptr;
2329}
2330
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002331// method_reference() is called passing it the ReferenceName that might be
2332// a reference it to an Objective-C method call. If so then it allocates and
2333// assembles a method call string with the values last seen and saved in
2334// the DisassembleInfo's class_name and selector_name fields. This is saved
2335// into the method field of the info and any previous string is free'ed.
2336// Then the class_name field in the info is set to nullptr. The method call
2337// string is set into ReferenceName and ReferenceType is set to
2338// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2339// then both ReferenceType and ReferenceName are left unchanged.
2340static void method_reference(struct DisassembleInfo *info,
2341 uint64_t *ReferenceType,
2342 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002343 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002344 if (*ReferenceName != nullptr) {
2345 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002346 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002347 if (info->method != nullptr)
2348 free(info->method);
2349 if (info->class_name != nullptr) {
2350 info->method = (char *)malloc(5 + strlen(info->class_name) +
2351 strlen(info->selector_name));
2352 if (info->method != nullptr) {
2353 strcpy(info->method, "+[");
2354 strcat(info->method, info->class_name);
2355 strcat(info->method, " ");
2356 strcat(info->method, info->selector_name);
2357 strcat(info->method, "]");
2358 *ReferenceName = info->method;
2359 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2360 }
2361 } else {
2362 info->method = (char *)malloc(9 + strlen(info->selector_name));
2363 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002364 if (Arch == Triple::x86_64)
2365 strcpy(info->method, "-[%rdi ");
2366 else if (Arch == Triple::aarch64)
2367 strcpy(info->method, "-[x0 ");
2368 else
2369 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002370 strcat(info->method, info->selector_name);
2371 strcat(info->method, "]");
2372 *ReferenceName = info->method;
2373 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2374 }
2375 }
2376 info->class_name = nullptr;
2377 }
2378 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002379 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002380 if (info->method != nullptr)
2381 free(info->method);
2382 info->method = (char *)malloc(17 + strlen(info->selector_name));
2383 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002384 if (Arch == Triple::x86_64)
2385 strcpy(info->method, "-[[%rdi super] ");
2386 else if (Arch == Triple::aarch64)
2387 strcpy(info->method, "-[[x0 super] ");
2388 else
2389 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002390 strcat(info->method, info->selector_name);
2391 strcat(info->method, "]");
2392 *ReferenceName = info->method;
2393 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2394 }
2395 info->class_name = nullptr;
2396 }
2397 }
2398 }
2399}
2400
2401// GuessPointerPointer() is passed the address of what might be a pointer to
2402// a reference to an Objective-C class, selector, message ref or cfstring.
2403// If so the value of the pointer is returned and one of the booleans are set
2404// to true. If not zero is returned and all the booleans are set to false.
2405static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2406 struct DisassembleInfo *info,
2407 bool &classref, bool &selref, bool &msgref,
2408 bool &cfstring) {
2409 classref = false;
2410 selref = false;
2411 msgref = false;
2412 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002413 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002414 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2415 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2416 for (unsigned J = 0; J < Seg.nsects; ++J) {
2417 MachO::section_64 Sec = info->O->getSection64(Load, J);
2418 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2419 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2420 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2421 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2422 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2423 ReferenceValue >= Sec.addr &&
2424 ReferenceValue < Sec.addr + Sec.size) {
2425 uint64_t sect_offset = ReferenceValue - Sec.addr;
2426 uint64_t object_offset = Sec.offset + sect_offset;
2427 StringRef MachOContents = info->O->getData();
2428 uint64_t object_size = MachOContents.size();
2429 const char *object_addr = (const char *)MachOContents.data();
2430 if (object_offset < object_size) {
2431 uint64_t pointer_value;
2432 memcpy(&pointer_value, object_addr + object_offset,
2433 sizeof(uint64_t));
2434 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2435 sys::swapByteOrder(pointer_value);
2436 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2437 selref = true;
2438 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2439 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2440 classref = true;
2441 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2442 ReferenceValue + 8 < Sec.addr + Sec.size) {
2443 msgref = true;
2444 memcpy(&pointer_value, object_addr + object_offset + 8,
2445 sizeof(uint64_t));
2446 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2447 sys::swapByteOrder(pointer_value);
2448 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2449 cfstring = true;
2450 return pointer_value;
2451 } else {
2452 return 0;
2453 }
2454 }
2455 }
2456 }
2457 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002458 }
2459 return 0;
2460}
2461
2462// get_pointer_64 returns a pointer to the bytes in the object file at the
2463// Address from a section in the Mach-O file. And indirectly returns the
2464// offset into the section, number of bytes left in the section past the offset
2465// and which section is was being referenced. If the Address is not in a
2466// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002467static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2468 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002469 DisassembleInfo *info,
2470 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002471 offset = 0;
2472 left = 0;
2473 S = SectionRef();
2474 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2475 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2476 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002477 if (SectSize == 0)
2478 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002479 if (objc_only) {
2480 StringRef SectName;
2481 ((*(info->Sections))[SectIdx]).getName(SectName);
2482 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2483 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2484 if (SegName != "__OBJC" && SectName != "__cstring")
2485 continue;
2486 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002487 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2488 S = (*(info->Sections))[SectIdx];
2489 offset = Address - SectAddress;
2490 left = SectSize - offset;
2491 StringRef SectContents;
2492 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2493 return SectContents.data() + offset;
2494 }
2495 }
2496 return nullptr;
2497}
2498
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002499static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2500 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002501 DisassembleInfo *info,
2502 bool objc_only = false) {
2503 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002504}
2505
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002506// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2507// the symbol indirectly through n_value. Based on the relocation information
2508// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002509// If no relocation information is found and a non-zero ReferenceValue for the
2510// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002511static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2512 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002513 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002514 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002515 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002516 return nullptr;
2517
2518 // See if there is an external relocation entry at the sect_offset.
2519 bool reloc_found = false;
2520 DataRefImpl Rel;
2521 MachO::any_relocation_info RE;
2522 bool isExtern = false;
2523 SymbolRef Symbol;
2524 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002525 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002526 if (RelocOffset == sect_offset) {
2527 Rel = Reloc.getRawDataRefImpl();
2528 RE = info->O->getRelocation(Rel);
2529 if (info->O->isRelocationScattered(RE))
2530 continue;
2531 isExtern = info->O->getPlainRelocationExternal(RE);
2532 if (isExtern) {
2533 symbol_iterator RelocSym = Reloc.getSymbol();
2534 Symbol = *RelocSym;
2535 }
2536 reloc_found = true;
2537 break;
2538 }
2539 }
2540 // If there is an external relocation entry for a symbol in this section
2541 // at this section_offset then use that symbol's value for the n_value
2542 // and return its name.
2543 const char *SymbolName = nullptr;
2544 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002545 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002546 Expected<StringRef> NameOrError = Symbol.getName();
2547 if (!NameOrError) {
2548 std::string Buf;
2549 raw_string_ostream OS(Buf);
2550 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2551 OS.flush();
2552 report_fatal_error(Buf);
2553 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002554 StringRef Name = *NameOrError;
2555 if (!Name.empty()) {
2556 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002557 return SymbolName;
2558 }
2559 }
2560
2561 // TODO: For fully linked images, look through the external relocation
2562 // entries off the dynamic symtab command. For these the r_offset is from the
2563 // start of the first writeable segment in the Mach-O file. So the offset
2564 // to this section from that segment is passed to this routine by the caller,
2565 // as the database_offset. Which is the difference of the section's starting
2566 // address and the first writable segment.
2567 //
2568 // NOTE: need add passing the database_offset to this routine.
2569
Kevin Enderby0fc11822015-04-01 20:57:01 +00002570 // We did not find an external relocation entry so look up the ReferenceValue
2571 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002572 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002573
2574 return SymbolName;
2575}
2576
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002577static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2578 DisassembleInfo *info,
2579 uint32_t ReferenceValue) {
2580 uint64_t n_value64;
2581 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2582}
2583
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002584// These are structs in the Objective-C meta data and read to produce the
2585// comments for disassembly. While these are part of the ABI they are no
2586// public defintions. So the are here not in include/llvm/Support/MachO.h .
2587
2588// The cfstring object in a 64-bit Mach-O file.
2589struct cfstring64_t {
2590 uint64_t isa; // class64_t * (64-bit pointer)
2591 uint64_t flags; // flag bits
2592 uint64_t characters; // char * (64-bit pointer)
2593 uint64_t length; // number of non-NULL characters in above
2594};
2595
2596// The class object in a 64-bit Mach-O file.
2597struct class64_t {
2598 uint64_t isa; // class64_t * (64-bit pointer)
2599 uint64_t superclass; // class64_t * (64-bit pointer)
2600 uint64_t cache; // Cache (64-bit pointer)
2601 uint64_t vtable; // IMP * (64-bit pointer)
2602 uint64_t data; // class_ro64_t * (64-bit pointer)
2603};
2604
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002605struct class32_t {
2606 uint32_t isa; /* class32_t * (32-bit pointer) */
2607 uint32_t superclass; /* class32_t * (32-bit pointer) */
2608 uint32_t cache; /* Cache (32-bit pointer) */
2609 uint32_t vtable; /* IMP * (32-bit pointer) */
2610 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2611};
2612
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002613struct class_ro64_t {
2614 uint32_t flags;
2615 uint32_t instanceStart;
2616 uint32_t instanceSize;
2617 uint32_t reserved;
2618 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2619 uint64_t name; // const char * (64-bit pointer)
2620 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2621 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2622 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2623 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2624 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2625};
2626
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002627struct class_ro32_t {
2628 uint32_t flags;
2629 uint32_t instanceStart;
2630 uint32_t instanceSize;
2631 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2632 uint32_t name; /* const char * (32-bit pointer) */
2633 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2634 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2635 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2636 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2637 uint32_t baseProperties; /* const struct objc_property_list *
2638 (32-bit pointer) */
2639};
2640
2641/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002642#define RO_META (1 << 0)
2643#define RO_ROOT (1 << 1)
2644#define RO_HAS_CXX_STRUCTORS (1 << 2)
2645
2646struct method_list64_t {
2647 uint32_t entsize;
2648 uint32_t count;
2649 /* struct method64_t first; These structures follow inline */
2650};
2651
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002652struct method_list32_t {
2653 uint32_t entsize;
2654 uint32_t count;
2655 /* struct method32_t first; These structures follow inline */
2656};
2657
Kevin Enderby0fc11822015-04-01 20:57:01 +00002658struct method64_t {
2659 uint64_t name; /* SEL (64-bit pointer) */
2660 uint64_t types; /* const char * (64-bit pointer) */
2661 uint64_t imp; /* IMP (64-bit pointer) */
2662};
2663
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002664struct method32_t {
2665 uint32_t name; /* SEL (32-bit pointer) */
2666 uint32_t types; /* const char * (32-bit pointer) */
2667 uint32_t imp; /* IMP (32-bit pointer) */
2668};
2669
Kevin Enderby0fc11822015-04-01 20:57:01 +00002670struct protocol_list64_t {
2671 uint64_t count; /* uintptr_t (a 64-bit value) */
2672 /* struct protocol64_t * list[0]; These pointers follow inline */
2673};
2674
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002675struct protocol_list32_t {
2676 uint32_t count; /* uintptr_t (a 32-bit value) */
2677 /* struct protocol32_t * list[0]; These pointers follow inline */
2678};
2679
Kevin Enderby0fc11822015-04-01 20:57:01 +00002680struct protocol64_t {
2681 uint64_t isa; /* id * (64-bit pointer) */
2682 uint64_t name; /* const char * (64-bit pointer) */
2683 uint64_t protocols; /* struct protocol_list64_t *
2684 (64-bit pointer) */
2685 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2686 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2687 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2688 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2689 uint64_t instanceProperties; /* struct objc_property_list *
2690 (64-bit pointer) */
2691};
2692
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002693struct protocol32_t {
2694 uint32_t isa; /* id * (32-bit pointer) */
2695 uint32_t name; /* const char * (32-bit pointer) */
2696 uint32_t protocols; /* struct protocol_list_t *
2697 (32-bit pointer) */
2698 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2699 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2700 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2701 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2702 uint32_t instanceProperties; /* struct objc_property_list *
2703 (32-bit pointer) */
2704};
2705
Kevin Enderby0fc11822015-04-01 20:57:01 +00002706struct ivar_list64_t {
2707 uint32_t entsize;
2708 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002709 /* struct ivar64_t first; These structures follow inline */
2710};
2711
2712struct ivar_list32_t {
2713 uint32_t entsize;
2714 uint32_t count;
2715 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002716};
2717
2718struct ivar64_t {
2719 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2720 uint64_t name; /* const char * (64-bit pointer) */
2721 uint64_t type; /* const char * (64-bit pointer) */
2722 uint32_t alignment;
2723 uint32_t size;
2724};
2725
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002726struct ivar32_t {
2727 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2728 uint32_t name; /* const char * (32-bit pointer) */
2729 uint32_t type; /* const char * (32-bit pointer) */
2730 uint32_t alignment;
2731 uint32_t size;
2732};
2733
Kevin Enderby0fc11822015-04-01 20:57:01 +00002734struct objc_property_list64 {
2735 uint32_t entsize;
2736 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002737 /* struct objc_property64 first; These structures follow inline */
2738};
2739
2740struct objc_property_list32 {
2741 uint32_t entsize;
2742 uint32_t count;
2743 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002744};
2745
2746struct objc_property64 {
2747 uint64_t name; /* const char * (64-bit pointer) */
2748 uint64_t attributes; /* const char * (64-bit pointer) */
2749};
2750
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002751struct objc_property32 {
2752 uint32_t name; /* const char * (32-bit pointer) */
2753 uint32_t attributes; /* const char * (32-bit pointer) */
2754};
2755
Kevin Enderby0fc11822015-04-01 20:57:01 +00002756struct category64_t {
2757 uint64_t name; /* const char * (64-bit pointer) */
2758 uint64_t cls; /* struct class_t * (64-bit pointer) */
2759 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2760 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2761 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2762 uint64_t instanceProperties; /* struct objc_property_list *
2763 (64-bit pointer) */
2764};
2765
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002766struct category32_t {
2767 uint32_t name; /* const char * (32-bit pointer) */
2768 uint32_t cls; /* struct class_t * (32-bit pointer) */
2769 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2770 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2771 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2772 uint32_t instanceProperties; /* struct objc_property_list *
2773 (32-bit pointer) */
2774};
2775
Kevin Enderby0fc11822015-04-01 20:57:01 +00002776struct objc_image_info64 {
2777 uint32_t version;
2778 uint32_t flags;
2779};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002780struct objc_image_info32 {
2781 uint32_t version;
2782 uint32_t flags;
2783};
Kevin Enderby846c0002015-04-16 17:19:59 +00002784struct imageInfo_t {
2785 uint32_t version;
2786 uint32_t flags;
2787};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002788/* masks for objc_image_info.flags */
2789#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2790#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2791
2792struct message_ref64 {
2793 uint64_t imp; /* IMP (64-bit pointer) */
2794 uint64_t sel; /* SEL (64-bit pointer) */
2795};
2796
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002797struct message_ref32 {
2798 uint32_t imp; /* IMP (32-bit pointer) */
2799 uint32_t sel; /* SEL (32-bit pointer) */
2800};
2801
Kevin Enderby846c0002015-04-16 17:19:59 +00002802// Objective-C 1 (32-bit only) meta data structs.
2803
2804struct objc_module_t {
2805 uint32_t version;
2806 uint32_t size;
2807 uint32_t name; /* char * (32-bit pointer) */
2808 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2809};
2810
2811struct objc_symtab_t {
2812 uint32_t sel_ref_cnt;
2813 uint32_t refs; /* SEL * (32-bit pointer) */
2814 uint16_t cls_def_cnt;
2815 uint16_t cat_def_cnt;
2816 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2817};
2818
2819struct objc_class_t {
2820 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2821 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2822 uint32_t name; /* const char * (32-bit pointer) */
2823 int32_t version;
2824 int32_t info;
2825 int32_t instance_size;
2826 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2827 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2828 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2829 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2830};
2831
2832#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2833// class is not a metaclass
2834#define CLS_CLASS 0x1
2835// class is a metaclass
2836#define CLS_META 0x2
2837
2838struct objc_category_t {
2839 uint32_t category_name; /* char * (32-bit pointer) */
2840 uint32_t class_name; /* char * (32-bit pointer) */
2841 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2842 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2843 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2844};
2845
2846struct objc_ivar_t {
2847 uint32_t ivar_name; /* char * (32-bit pointer) */
2848 uint32_t ivar_type; /* char * (32-bit pointer) */
2849 int32_t ivar_offset;
2850};
2851
2852struct objc_ivar_list_t {
2853 int32_t ivar_count;
2854 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2855};
2856
2857struct objc_method_list_t {
2858 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2859 int32_t method_count;
2860 // struct objc_method_t method_list[1]; /* variable length structure */
2861};
2862
2863struct objc_method_t {
2864 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2865 uint32_t method_types; /* char * (32-bit pointer) */
2866 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2867 (32-bit pointer) */
2868};
2869
2870struct objc_protocol_list_t {
2871 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2872 int32_t count;
2873 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2874 // (32-bit pointer) */
2875};
2876
2877struct objc_protocol_t {
2878 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2879 uint32_t protocol_name; /* char * (32-bit pointer) */
2880 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2881 uint32_t instance_methods; /* struct objc_method_description_list *
2882 (32-bit pointer) */
2883 uint32_t class_methods; /* struct objc_method_description_list *
2884 (32-bit pointer) */
2885};
2886
2887struct objc_method_description_list_t {
2888 int32_t count;
2889 // struct objc_method_description_t list[1];
2890};
2891
2892struct objc_method_description_t {
2893 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2894 uint32_t types; /* char * (32-bit pointer) */
2895};
2896
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002897inline void swapStruct(struct cfstring64_t &cfs) {
2898 sys::swapByteOrder(cfs.isa);
2899 sys::swapByteOrder(cfs.flags);
2900 sys::swapByteOrder(cfs.characters);
2901 sys::swapByteOrder(cfs.length);
2902}
2903
2904inline void swapStruct(struct class64_t &c) {
2905 sys::swapByteOrder(c.isa);
2906 sys::swapByteOrder(c.superclass);
2907 sys::swapByteOrder(c.cache);
2908 sys::swapByteOrder(c.vtable);
2909 sys::swapByteOrder(c.data);
2910}
2911
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002912inline void swapStruct(struct class32_t &c) {
2913 sys::swapByteOrder(c.isa);
2914 sys::swapByteOrder(c.superclass);
2915 sys::swapByteOrder(c.cache);
2916 sys::swapByteOrder(c.vtable);
2917 sys::swapByteOrder(c.data);
2918}
2919
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002920inline void swapStruct(struct class_ro64_t &cro) {
2921 sys::swapByteOrder(cro.flags);
2922 sys::swapByteOrder(cro.instanceStart);
2923 sys::swapByteOrder(cro.instanceSize);
2924 sys::swapByteOrder(cro.reserved);
2925 sys::swapByteOrder(cro.ivarLayout);
2926 sys::swapByteOrder(cro.name);
2927 sys::swapByteOrder(cro.baseMethods);
2928 sys::swapByteOrder(cro.baseProtocols);
2929 sys::swapByteOrder(cro.ivars);
2930 sys::swapByteOrder(cro.weakIvarLayout);
2931 sys::swapByteOrder(cro.baseProperties);
2932}
2933
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002934inline void swapStruct(struct class_ro32_t &cro) {
2935 sys::swapByteOrder(cro.flags);
2936 sys::swapByteOrder(cro.instanceStart);
2937 sys::swapByteOrder(cro.instanceSize);
2938 sys::swapByteOrder(cro.ivarLayout);
2939 sys::swapByteOrder(cro.name);
2940 sys::swapByteOrder(cro.baseMethods);
2941 sys::swapByteOrder(cro.baseProtocols);
2942 sys::swapByteOrder(cro.ivars);
2943 sys::swapByteOrder(cro.weakIvarLayout);
2944 sys::swapByteOrder(cro.baseProperties);
2945}
2946
Kevin Enderby0fc11822015-04-01 20:57:01 +00002947inline void swapStruct(struct method_list64_t &ml) {
2948 sys::swapByteOrder(ml.entsize);
2949 sys::swapByteOrder(ml.count);
2950}
2951
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002952inline void swapStruct(struct method_list32_t &ml) {
2953 sys::swapByteOrder(ml.entsize);
2954 sys::swapByteOrder(ml.count);
2955}
2956
Kevin Enderby0fc11822015-04-01 20:57:01 +00002957inline void swapStruct(struct method64_t &m) {
2958 sys::swapByteOrder(m.name);
2959 sys::swapByteOrder(m.types);
2960 sys::swapByteOrder(m.imp);
2961}
2962
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002963inline void swapStruct(struct method32_t &m) {
2964 sys::swapByteOrder(m.name);
2965 sys::swapByteOrder(m.types);
2966 sys::swapByteOrder(m.imp);
2967}
2968
Kevin Enderby0fc11822015-04-01 20:57:01 +00002969inline void swapStruct(struct protocol_list64_t &pl) {
2970 sys::swapByteOrder(pl.count);
2971}
2972
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002973inline void swapStruct(struct protocol_list32_t &pl) {
2974 sys::swapByteOrder(pl.count);
2975}
2976
Kevin Enderby0fc11822015-04-01 20:57:01 +00002977inline void swapStruct(struct protocol64_t &p) {
2978 sys::swapByteOrder(p.isa);
2979 sys::swapByteOrder(p.name);
2980 sys::swapByteOrder(p.protocols);
2981 sys::swapByteOrder(p.instanceMethods);
2982 sys::swapByteOrder(p.classMethods);
2983 sys::swapByteOrder(p.optionalInstanceMethods);
2984 sys::swapByteOrder(p.optionalClassMethods);
2985 sys::swapByteOrder(p.instanceProperties);
2986}
2987
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002988inline void swapStruct(struct protocol32_t &p) {
2989 sys::swapByteOrder(p.isa);
2990 sys::swapByteOrder(p.name);
2991 sys::swapByteOrder(p.protocols);
2992 sys::swapByteOrder(p.instanceMethods);
2993 sys::swapByteOrder(p.classMethods);
2994 sys::swapByteOrder(p.optionalInstanceMethods);
2995 sys::swapByteOrder(p.optionalClassMethods);
2996 sys::swapByteOrder(p.instanceProperties);
2997}
2998
Kevin Enderby0fc11822015-04-01 20:57:01 +00002999inline void swapStruct(struct ivar_list64_t &il) {
3000 sys::swapByteOrder(il.entsize);
3001 sys::swapByteOrder(il.count);
3002}
3003
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003004inline void swapStruct(struct ivar_list32_t &il) {
3005 sys::swapByteOrder(il.entsize);
3006 sys::swapByteOrder(il.count);
3007}
3008
Kevin Enderby0fc11822015-04-01 20:57:01 +00003009inline void swapStruct(struct ivar64_t &i) {
3010 sys::swapByteOrder(i.offset);
3011 sys::swapByteOrder(i.name);
3012 sys::swapByteOrder(i.type);
3013 sys::swapByteOrder(i.alignment);
3014 sys::swapByteOrder(i.size);
3015}
3016
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003017inline void swapStruct(struct ivar32_t &i) {
3018 sys::swapByteOrder(i.offset);
3019 sys::swapByteOrder(i.name);
3020 sys::swapByteOrder(i.type);
3021 sys::swapByteOrder(i.alignment);
3022 sys::swapByteOrder(i.size);
3023}
3024
Kevin Enderby0fc11822015-04-01 20:57:01 +00003025inline void swapStruct(struct objc_property_list64 &pl) {
3026 sys::swapByteOrder(pl.entsize);
3027 sys::swapByteOrder(pl.count);
3028}
3029
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003030inline void swapStruct(struct objc_property_list32 &pl) {
3031 sys::swapByteOrder(pl.entsize);
3032 sys::swapByteOrder(pl.count);
3033}
3034
Kevin Enderby0fc11822015-04-01 20:57:01 +00003035inline void swapStruct(struct objc_property64 &op) {
3036 sys::swapByteOrder(op.name);
3037 sys::swapByteOrder(op.attributes);
3038}
3039
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003040inline void swapStruct(struct objc_property32 &op) {
3041 sys::swapByteOrder(op.name);
3042 sys::swapByteOrder(op.attributes);
3043}
3044
Kevin Enderby0fc11822015-04-01 20:57:01 +00003045inline void swapStruct(struct category64_t &c) {
3046 sys::swapByteOrder(c.name);
3047 sys::swapByteOrder(c.cls);
3048 sys::swapByteOrder(c.instanceMethods);
3049 sys::swapByteOrder(c.classMethods);
3050 sys::swapByteOrder(c.protocols);
3051 sys::swapByteOrder(c.instanceProperties);
3052}
3053
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003054inline void swapStruct(struct category32_t &c) {
3055 sys::swapByteOrder(c.name);
3056 sys::swapByteOrder(c.cls);
3057 sys::swapByteOrder(c.instanceMethods);
3058 sys::swapByteOrder(c.classMethods);
3059 sys::swapByteOrder(c.protocols);
3060 sys::swapByteOrder(c.instanceProperties);
3061}
3062
Kevin Enderby0fc11822015-04-01 20:57:01 +00003063inline void swapStruct(struct objc_image_info64 &o) {
3064 sys::swapByteOrder(o.version);
3065 sys::swapByteOrder(o.flags);
3066}
3067
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003068inline void swapStruct(struct objc_image_info32 &o) {
3069 sys::swapByteOrder(o.version);
3070 sys::swapByteOrder(o.flags);
3071}
3072
Kevin Enderby846c0002015-04-16 17:19:59 +00003073inline void swapStruct(struct imageInfo_t &o) {
3074 sys::swapByteOrder(o.version);
3075 sys::swapByteOrder(o.flags);
3076}
3077
Kevin Enderby0fc11822015-04-01 20:57:01 +00003078inline void swapStruct(struct message_ref64 &mr) {
3079 sys::swapByteOrder(mr.imp);
3080 sys::swapByteOrder(mr.sel);
3081}
3082
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003083inline void swapStruct(struct message_ref32 &mr) {
3084 sys::swapByteOrder(mr.imp);
3085 sys::swapByteOrder(mr.sel);
3086}
3087
Kevin Enderby846c0002015-04-16 17:19:59 +00003088inline void swapStruct(struct objc_module_t &module) {
3089 sys::swapByteOrder(module.version);
3090 sys::swapByteOrder(module.size);
3091 sys::swapByteOrder(module.name);
3092 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003093}
Kevin Enderby846c0002015-04-16 17:19:59 +00003094
3095inline void swapStruct(struct objc_symtab_t &symtab) {
3096 sys::swapByteOrder(symtab.sel_ref_cnt);
3097 sys::swapByteOrder(symtab.refs);
3098 sys::swapByteOrder(symtab.cls_def_cnt);
3099 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003100}
Kevin Enderby846c0002015-04-16 17:19:59 +00003101
3102inline void swapStruct(struct objc_class_t &objc_class) {
3103 sys::swapByteOrder(objc_class.isa);
3104 sys::swapByteOrder(objc_class.super_class);
3105 sys::swapByteOrder(objc_class.name);
3106 sys::swapByteOrder(objc_class.version);
3107 sys::swapByteOrder(objc_class.info);
3108 sys::swapByteOrder(objc_class.instance_size);
3109 sys::swapByteOrder(objc_class.ivars);
3110 sys::swapByteOrder(objc_class.methodLists);
3111 sys::swapByteOrder(objc_class.cache);
3112 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003113}
Kevin Enderby846c0002015-04-16 17:19:59 +00003114
3115inline void swapStruct(struct objc_category_t &objc_category) {
3116 sys::swapByteOrder(objc_category.category_name);
3117 sys::swapByteOrder(objc_category.class_name);
3118 sys::swapByteOrder(objc_category.instance_methods);
3119 sys::swapByteOrder(objc_category.class_methods);
3120 sys::swapByteOrder(objc_category.protocols);
3121}
3122
3123inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3124 sys::swapByteOrder(objc_ivar_list.ivar_count);
3125}
3126
3127inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3128 sys::swapByteOrder(objc_ivar.ivar_name);
3129 sys::swapByteOrder(objc_ivar.ivar_type);
3130 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003131}
Kevin Enderby846c0002015-04-16 17:19:59 +00003132
3133inline void swapStruct(struct objc_method_list_t &method_list) {
3134 sys::swapByteOrder(method_list.obsolete);
3135 sys::swapByteOrder(method_list.method_count);
3136}
3137
3138inline void swapStruct(struct objc_method_t &method) {
3139 sys::swapByteOrder(method.method_name);
3140 sys::swapByteOrder(method.method_types);
3141 sys::swapByteOrder(method.method_imp);
3142}
3143
3144inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3145 sys::swapByteOrder(protocol_list.next);
3146 sys::swapByteOrder(protocol_list.count);
3147}
3148
3149inline void swapStruct(struct objc_protocol_t &protocol) {
3150 sys::swapByteOrder(protocol.isa);
3151 sys::swapByteOrder(protocol.protocol_name);
3152 sys::swapByteOrder(protocol.protocol_list);
3153 sys::swapByteOrder(protocol.instance_methods);
3154 sys::swapByteOrder(protocol.class_methods);
3155}
3156
3157inline void swapStruct(struct objc_method_description_list_t &mdl) {
3158 sys::swapByteOrder(mdl.count);
3159}
3160
3161inline void swapStruct(struct objc_method_description_t &md) {
3162 sys::swapByteOrder(md.name);
3163 sys::swapByteOrder(md.types);
3164}
3165
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003166static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3167 struct DisassembleInfo *info);
3168
3169// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3170// to an Objective-C class and returns the class name. It is also passed the
3171// address of the pointer, so when the pointer is zero as it can be in an .o
3172// file, that is used to look for an external relocation entry with a symbol
3173// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003174static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3175 uint64_t ReferenceValue,
3176 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003177 const char *r;
3178 uint32_t offset, left;
3179 SectionRef S;
3180
3181 // The pointer_value can be 0 in an object file and have a relocation
3182 // entry for the class symbol at the ReferenceValue (the address of the
3183 // pointer).
3184 if (pointer_value == 0) {
3185 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3186 if (r == nullptr || left < sizeof(uint64_t))
3187 return nullptr;
3188 uint64_t n_value;
3189 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3190 if (symbol_name == nullptr)
3191 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003192 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003193 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3194 return class_name + 2;
3195 else
3196 return nullptr;
3197 }
3198
3199 // The case were the pointer_value is non-zero and points to a class defined
3200 // in this Mach-O file.
3201 r = get_pointer_64(pointer_value, offset, left, S, info);
3202 if (r == nullptr || left < sizeof(struct class64_t))
3203 return nullptr;
3204 struct class64_t c;
3205 memcpy(&c, r, sizeof(struct class64_t));
3206 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3207 swapStruct(c);
3208 if (c.data == 0)
3209 return nullptr;
3210 r = get_pointer_64(c.data, offset, left, S, info);
3211 if (r == nullptr || left < sizeof(struct class_ro64_t))
3212 return nullptr;
3213 struct class_ro64_t cro;
3214 memcpy(&cro, r, sizeof(struct class_ro64_t));
3215 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3216 swapStruct(cro);
3217 if (cro.name == 0)
3218 return nullptr;
3219 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3220 return name;
3221}
3222
3223// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3224// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003225static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3226 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003227 const char *r, *name;
3228 uint32_t offset, left;
3229 SectionRef S;
3230 struct cfstring64_t cfs;
3231 uint64_t cfs_characters;
3232
3233 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3234 if (r == nullptr || left < sizeof(struct cfstring64_t))
3235 return nullptr;
3236 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3237 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3238 swapStruct(cfs);
3239 if (cfs.characters == 0) {
3240 uint64_t n_value;
3241 const char *symbol_name = get_symbol_64(
3242 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3243 if (symbol_name == nullptr)
3244 return nullptr;
3245 cfs_characters = n_value;
3246 } else
3247 cfs_characters = cfs.characters;
3248 name = get_pointer_64(cfs_characters, offset, left, S, info);
3249
3250 return name;
3251}
3252
3253// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3254// of a pointer to an Objective-C selector reference when the pointer value is
3255// zero as in a .o file and is likely to have a external relocation entry with
3256// who's symbol's n_value is the real pointer to the selector name. If that is
3257// the case the real pointer to the selector name is returned else 0 is
3258// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003259static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3260 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003261 uint32_t offset, left;
3262 SectionRef S;
3263
3264 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3265 if (r == nullptr || left < sizeof(uint64_t))
3266 return 0;
3267 uint64_t n_value;
3268 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3269 if (symbol_name == nullptr)
3270 return 0;
3271 return n_value;
3272}
3273
Kevin Enderby0fc11822015-04-01 20:57:01 +00003274static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3275 const char *sectname) {
3276 for (const SectionRef &Section : O->sections()) {
3277 StringRef SectName;
3278 Section.getName(SectName);
3279 DataRefImpl Ref = Section.getRawDataRefImpl();
3280 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3281 if (SegName == segname && SectName == sectname)
3282 return Section;
3283 }
3284 return SectionRef();
3285}
3286
3287static void
3288walk_pointer_list_64(const char *listname, const SectionRef S,
3289 MachOObjectFile *O, struct DisassembleInfo *info,
3290 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3291 if (S == SectionRef())
3292 return;
3293
3294 StringRef SectName;
3295 S.getName(SectName);
3296 DataRefImpl Ref = S.getRawDataRefImpl();
3297 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3298 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3299
3300 StringRef BytesStr;
3301 S.getContents(BytesStr);
3302 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3303
3304 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3305 uint32_t left = S.getSize() - i;
3306 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3307 uint64_t p = 0;
3308 memcpy(&p, Contents + i, size);
3309 if (i + sizeof(uint64_t) > S.getSize())
3310 outs() << listname << " list pointer extends past end of (" << SegName
3311 << "," << SectName << ") section\n";
3312 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3313
3314 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3315 sys::swapByteOrder(p);
3316
3317 uint64_t n_value = 0;
3318 const char *name = get_symbol_64(i, S, info, n_value, p);
3319 if (name == nullptr)
3320 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3321
3322 if (n_value != 0) {
3323 outs() << format("0x%" PRIx64, n_value);
3324 if (p != 0)
3325 outs() << " + " << format("0x%" PRIx64, p);
3326 } else
3327 outs() << format("0x%" PRIx64, p);
3328 if (name != nullptr)
3329 outs() << " " << name;
3330 outs() << "\n";
3331
3332 p += n_value;
3333 if (func)
3334 func(p, info);
3335 }
3336}
3337
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003338static void
3339walk_pointer_list_32(const char *listname, const SectionRef S,
3340 MachOObjectFile *O, struct DisassembleInfo *info,
3341 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3342 if (S == SectionRef())
3343 return;
3344
3345 StringRef SectName;
3346 S.getName(SectName);
3347 DataRefImpl Ref = S.getRawDataRefImpl();
3348 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3349 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3350
3351 StringRef BytesStr;
3352 S.getContents(BytesStr);
3353 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3354
3355 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3356 uint32_t left = S.getSize() - i;
3357 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3358 uint32_t p = 0;
3359 memcpy(&p, Contents + i, size);
3360 if (i + sizeof(uint32_t) > S.getSize())
3361 outs() << listname << " list pointer extends past end of (" << SegName
3362 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003363 uint32_t Address = S.getAddress() + i;
3364 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003365
3366 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3367 sys::swapByteOrder(p);
3368 outs() << format("0x%" PRIx32, p);
3369
3370 const char *name = get_symbol_32(i, S, info, p);
3371 if (name != nullptr)
3372 outs() << " " << name;
3373 outs() << "\n";
3374
3375 if (func)
3376 func(p, info);
3377 }
3378}
3379
3380static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003381 if (layout_map == nullptr)
3382 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003383 outs() << " layout map: ";
3384 do {
3385 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3386 left--;
3387 layout_map++;
3388 } while (*layout_map != '\0' && left != 0);
3389 outs() << "\n";
3390}
3391
Kevin Enderby0fc11822015-04-01 20:57:01 +00003392static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3393 uint32_t offset, left;
3394 SectionRef S;
3395 const char *layout_map;
3396
3397 if (p == 0)
3398 return;
3399 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003400 print_layout_map(layout_map, left);
3401}
3402
3403static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3404 uint32_t offset, left;
3405 SectionRef S;
3406 const char *layout_map;
3407
3408 if (p == 0)
3409 return;
3410 layout_map = get_pointer_32(p, offset, left, S, info);
3411 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003412}
3413
3414static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3415 const char *indent) {
3416 struct method_list64_t ml;
3417 struct method64_t m;
3418 const char *r;
3419 uint32_t offset, xoffset, left, i;
3420 SectionRef S, xS;
3421 const char *name, *sym_name;
3422 uint64_t n_value;
3423
3424 r = get_pointer_64(p, offset, left, S, info);
3425 if (r == nullptr)
3426 return;
3427 memset(&ml, '\0', sizeof(struct method_list64_t));
3428 if (left < sizeof(struct method_list64_t)) {
3429 memcpy(&ml, r, left);
3430 outs() << " (method_list_t entends past the end of the section)\n";
3431 } else
3432 memcpy(&ml, r, sizeof(struct method_list64_t));
3433 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3434 swapStruct(ml);
3435 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3436 outs() << indent << "\t\t count " << ml.count << "\n";
3437
3438 p += sizeof(struct method_list64_t);
3439 offset += sizeof(struct method_list64_t);
3440 for (i = 0; i < ml.count; i++) {
3441 r = get_pointer_64(p, offset, left, S, info);
3442 if (r == nullptr)
3443 return;
3444 memset(&m, '\0', sizeof(struct method64_t));
3445 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003446 memcpy(&m, r, left);
3447 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003448 } else
3449 memcpy(&m, r, sizeof(struct method64_t));
3450 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3451 swapStruct(m);
3452
3453 outs() << indent << "\t\t name ";
3454 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3455 info, n_value, m.name);
3456 if (n_value != 0) {
3457 if (info->verbose && sym_name != nullptr)
3458 outs() << sym_name;
3459 else
3460 outs() << format("0x%" PRIx64, n_value);
3461 if (m.name != 0)
3462 outs() << " + " << format("0x%" PRIx64, m.name);
3463 } else
3464 outs() << format("0x%" PRIx64, m.name);
3465 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3466 if (name != nullptr)
3467 outs() << format(" %.*s", left, name);
3468 outs() << "\n";
3469
3470 outs() << indent << "\t\t types ";
3471 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3472 info, n_value, m.types);
3473 if (n_value != 0) {
3474 if (info->verbose && sym_name != nullptr)
3475 outs() << sym_name;
3476 else
3477 outs() << format("0x%" PRIx64, n_value);
3478 if (m.types != 0)
3479 outs() << " + " << format("0x%" PRIx64, m.types);
3480 } else
3481 outs() << format("0x%" PRIx64, m.types);
3482 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3483 if (name != nullptr)
3484 outs() << format(" %.*s", left, name);
3485 outs() << "\n";
3486
3487 outs() << indent << "\t\t imp ";
3488 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3489 n_value, m.imp);
3490 if (info->verbose && name == nullptr) {
3491 if (n_value != 0) {
3492 outs() << format("0x%" PRIx64, n_value) << " ";
3493 if (m.imp != 0)
3494 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3495 } else
3496 outs() << format("0x%" PRIx64, m.imp) << " ";
3497 }
3498 if (name != nullptr)
3499 outs() << name;
3500 outs() << "\n";
3501
3502 p += sizeof(struct method64_t);
3503 offset += sizeof(struct method64_t);
3504 }
3505}
3506
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003507static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3508 const char *indent) {
3509 struct method_list32_t ml;
3510 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003511 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003512 uint32_t offset, xoffset, left, i;
3513 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003514
3515 r = get_pointer_32(p, offset, left, S, info);
3516 if (r == nullptr)
3517 return;
3518 memset(&ml, '\0', sizeof(struct method_list32_t));
3519 if (left < sizeof(struct method_list32_t)) {
3520 memcpy(&ml, r, left);
3521 outs() << " (method_list_t entends past the end of the section)\n";
3522 } else
3523 memcpy(&ml, r, sizeof(struct method_list32_t));
3524 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3525 swapStruct(ml);
3526 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3527 outs() << indent << "\t\t count " << ml.count << "\n";
3528
3529 p += sizeof(struct method_list32_t);
3530 offset += sizeof(struct method_list32_t);
3531 for (i = 0; i < ml.count; i++) {
3532 r = get_pointer_32(p, offset, left, S, info);
3533 if (r == nullptr)
3534 return;
3535 memset(&m, '\0', sizeof(struct method32_t));
3536 if (left < sizeof(struct method32_t)) {
3537 memcpy(&ml, r, left);
3538 outs() << indent << " (method_t entends past the end of the section)\n";
3539 } else
3540 memcpy(&m, r, sizeof(struct method32_t));
3541 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3542 swapStruct(m);
3543
3544 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3545 name = get_pointer_32(m.name, xoffset, left, xS, info);
3546 if (name != nullptr)
3547 outs() << format(" %.*s", left, name);
3548 outs() << "\n";
3549
3550 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3551 name = get_pointer_32(m.types, xoffset, left, xS, info);
3552 if (name != nullptr)
3553 outs() << format(" %.*s", left, name);
3554 outs() << "\n";
3555
3556 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3557 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3558 m.imp);
3559 if (name != nullptr)
3560 outs() << " " << name;
3561 outs() << "\n";
3562
3563 p += sizeof(struct method32_t);
3564 offset += sizeof(struct method32_t);
3565 }
3566}
3567
Kevin Enderby846c0002015-04-16 17:19:59 +00003568static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3569 uint32_t offset, left, xleft;
3570 SectionRef S;
3571 struct objc_method_list_t method_list;
3572 struct objc_method_t method;
3573 const char *r, *methods, *name, *SymbolName;
3574 int32_t i;
3575
3576 r = get_pointer_32(p, offset, left, S, info, true);
3577 if (r == nullptr)
3578 return true;
3579
3580 outs() << "\n";
3581 if (left > sizeof(struct objc_method_list_t)) {
3582 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3583 } else {
3584 outs() << "\t\t objc_method_list extends past end of the section\n";
3585 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3586 memcpy(&method_list, r, left);
3587 }
3588 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3589 swapStruct(method_list);
3590
3591 outs() << "\t\t obsolete "
3592 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3593 outs() << "\t\t method_count " << method_list.method_count << "\n";
3594
3595 methods = r + sizeof(struct objc_method_list_t);
3596 for (i = 0; i < method_list.method_count; i++) {
3597 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3598 outs() << "\t\t remaining method's extend past the of the section\n";
3599 break;
3600 }
3601 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3602 sizeof(struct objc_method_t));
3603 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3604 swapStruct(method);
3605
3606 outs() << "\t\t method_name "
3607 << format("0x%08" PRIx32, method.method_name);
3608 if (info->verbose) {
3609 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3610 if (name != nullptr)
3611 outs() << format(" %.*s", xleft, name);
3612 else
3613 outs() << " (not in an __OBJC section)";
3614 }
3615 outs() << "\n";
3616
3617 outs() << "\t\t method_types "
3618 << format("0x%08" PRIx32, method.method_types);
3619 if (info->verbose) {
3620 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3621 if (name != nullptr)
3622 outs() << format(" %.*s", xleft, name);
3623 else
3624 outs() << " (not in an __OBJC section)";
3625 }
3626 outs() << "\n";
3627
3628 outs() << "\t\t method_imp "
3629 << format("0x%08" PRIx32, method.method_imp) << " ";
3630 if (info->verbose) {
3631 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3632 if (SymbolName != nullptr)
3633 outs() << SymbolName;
3634 }
3635 outs() << "\n";
3636 }
3637 return false;
3638}
3639
Kevin Enderby0fc11822015-04-01 20:57:01 +00003640static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3641 struct protocol_list64_t pl;
3642 uint64_t q, n_value;
3643 struct protocol64_t pc;
3644 const char *r;
3645 uint32_t offset, xoffset, left, i;
3646 SectionRef S, xS;
3647 const char *name, *sym_name;
3648
3649 r = get_pointer_64(p, offset, left, S, info);
3650 if (r == nullptr)
3651 return;
3652 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3653 if (left < sizeof(struct protocol_list64_t)) {
3654 memcpy(&pl, r, left);
3655 outs() << " (protocol_list_t entends past the end of the section)\n";
3656 } else
3657 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3658 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3659 swapStruct(pl);
3660 outs() << " count " << pl.count << "\n";
3661
3662 p += sizeof(struct protocol_list64_t);
3663 offset += sizeof(struct protocol_list64_t);
3664 for (i = 0; i < pl.count; i++) {
3665 r = get_pointer_64(p, offset, left, S, info);
3666 if (r == nullptr)
3667 return;
3668 q = 0;
3669 if (left < sizeof(uint64_t)) {
3670 memcpy(&q, r, left);
3671 outs() << " (protocol_t * entends past the end of the section)\n";
3672 } else
3673 memcpy(&q, r, sizeof(uint64_t));
3674 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3675 sys::swapByteOrder(q);
3676
3677 outs() << "\t\t list[" << i << "] ";
3678 sym_name = get_symbol_64(offset, S, info, n_value, q);
3679 if (n_value != 0) {
3680 if (info->verbose && sym_name != nullptr)
3681 outs() << sym_name;
3682 else
3683 outs() << format("0x%" PRIx64, n_value);
3684 if (q != 0)
3685 outs() << " + " << format("0x%" PRIx64, q);
3686 } else
3687 outs() << format("0x%" PRIx64, q);
3688 outs() << " (struct protocol_t *)\n";
3689
3690 r = get_pointer_64(q + n_value, offset, left, S, info);
3691 if (r == nullptr)
3692 return;
3693 memset(&pc, '\0', sizeof(struct protocol64_t));
3694 if (left < sizeof(struct protocol64_t)) {
3695 memcpy(&pc, r, left);
3696 outs() << " (protocol_t entends past the end of the section)\n";
3697 } else
3698 memcpy(&pc, r, sizeof(struct protocol64_t));
3699 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3700 swapStruct(pc);
3701
3702 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3703
3704 outs() << "\t\t\t name ";
3705 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3706 info, n_value, pc.name);
3707 if (n_value != 0) {
3708 if (info->verbose && sym_name != nullptr)
3709 outs() << sym_name;
3710 else
3711 outs() << format("0x%" PRIx64, n_value);
3712 if (pc.name != 0)
3713 outs() << " + " << format("0x%" PRIx64, pc.name);
3714 } else
3715 outs() << format("0x%" PRIx64, pc.name);
3716 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3717 if (name != nullptr)
3718 outs() << format(" %.*s", left, name);
3719 outs() << "\n";
3720
3721 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3722
3723 outs() << "\t\t instanceMethods ";
3724 sym_name =
3725 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3726 S, info, n_value, pc.instanceMethods);
3727 if (n_value != 0) {
3728 if (info->verbose && sym_name != nullptr)
3729 outs() << sym_name;
3730 else
3731 outs() << format("0x%" PRIx64, n_value);
3732 if (pc.instanceMethods != 0)
3733 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3734 } else
3735 outs() << format("0x%" PRIx64, pc.instanceMethods);
3736 outs() << " (struct method_list_t *)\n";
3737 if (pc.instanceMethods + n_value != 0)
3738 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3739
3740 outs() << "\t\t classMethods ";
3741 sym_name =
3742 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3743 info, n_value, pc.classMethods);
3744 if (n_value != 0) {
3745 if (info->verbose && sym_name != nullptr)
3746 outs() << sym_name;
3747 else
3748 outs() << format("0x%" PRIx64, n_value);
3749 if (pc.classMethods != 0)
3750 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3751 } else
3752 outs() << format("0x%" PRIx64, pc.classMethods);
3753 outs() << " (struct method_list_t *)\n";
3754 if (pc.classMethods + n_value != 0)
3755 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3756
3757 outs() << "\t optionalInstanceMethods "
3758 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3759 outs() << "\t optionalClassMethods "
3760 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3761 outs() << "\t instanceProperties "
3762 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3763
3764 p += sizeof(uint64_t);
3765 offset += sizeof(uint64_t);
3766 }
3767}
3768
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003769static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3770 struct protocol_list32_t pl;
3771 uint32_t q;
3772 struct protocol32_t pc;
3773 const char *r;
3774 uint32_t offset, xoffset, left, i;
3775 SectionRef S, xS;
3776 const char *name;
3777
3778 r = get_pointer_32(p, offset, left, S, info);
3779 if (r == nullptr)
3780 return;
3781 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3782 if (left < sizeof(struct protocol_list32_t)) {
3783 memcpy(&pl, r, left);
3784 outs() << " (protocol_list_t entends past the end of the section)\n";
3785 } else
3786 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3787 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3788 swapStruct(pl);
3789 outs() << " count " << pl.count << "\n";
3790
3791 p += sizeof(struct protocol_list32_t);
3792 offset += sizeof(struct protocol_list32_t);
3793 for (i = 0; i < pl.count; i++) {
3794 r = get_pointer_32(p, offset, left, S, info);
3795 if (r == nullptr)
3796 return;
3797 q = 0;
3798 if (left < sizeof(uint32_t)) {
3799 memcpy(&q, r, left);
3800 outs() << " (protocol_t * entends past the end of the section)\n";
3801 } else
3802 memcpy(&q, r, sizeof(uint32_t));
3803 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3804 sys::swapByteOrder(q);
3805 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3806 << " (struct protocol_t *)\n";
3807 r = get_pointer_32(q, offset, left, S, info);
3808 if (r == nullptr)
3809 return;
3810 memset(&pc, '\0', sizeof(struct protocol32_t));
3811 if (left < sizeof(struct protocol32_t)) {
3812 memcpy(&pc, r, left);
3813 outs() << " (protocol_t entends past the end of the section)\n";
3814 } else
3815 memcpy(&pc, r, sizeof(struct protocol32_t));
3816 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3817 swapStruct(pc);
3818 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3819 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3820 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3821 if (name != nullptr)
3822 outs() << format(" %.*s", left, name);
3823 outs() << "\n";
3824 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3825 outs() << "\t\t instanceMethods "
3826 << format("0x%" PRIx32, pc.instanceMethods)
3827 << " (struct method_list_t *)\n";
3828 if (pc.instanceMethods != 0)
3829 print_method_list32_t(pc.instanceMethods, info, "\t");
3830 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3831 << " (struct method_list_t *)\n";
3832 if (pc.classMethods != 0)
3833 print_method_list32_t(pc.classMethods, info, "\t");
3834 outs() << "\t optionalInstanceMethods "
3835 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3836 outs() << "\t optionalClassMethods "
3837 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3838 outs() << "\t instanceProperties "
3839 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3840 p += sizeof(uint32_t);
3841 offset += sizeof(uint32_t);
3842 }
3843}
3844
Kevin Enderby846c0002015-04-16 17:19:59 +00003845static void print_indent(uint32_t indent) {
3846 for (uint32_t i = 0; i < indent;) {
3847 if (indent - i >= 8) {
3848 outs() << "\t";
3849 i += 8;
3850 } else {
3851 for (uint32_t j = i; j < indent; j++)
3852 outs() << " ";
3853 return;
3854 }
3855 }
3856}
3857
3858static bool print_method_description_list(uint32_t p, uint32_t indent,
3859 struct DisassembleInfo *info) {
3860 uint32_t offset, left, xleft;
3861 SectionRef S;
3862 struct objc_method_description_list_t mdl;
3863 struct objc_method_description_t md;
3864 const char *r, *list, *name;
3865 int32_t i;
3866
3867 r = get_pointer_32(p, offset, left, S, info, true);
3868 if (r == nullptr)
3869 return true;
3870
3871 outs() << "\n";
3872 if (left > sizeof(struct objc_method_description_list_t)) {
3873 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3874 } else {
3875 print_indent(indent);
3876 outs() << " objc_method_description_list extends past end of the section\n";
3877 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3878 memcpy(&mdl, r, left);
3879 }
3880 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3881 swapStruct(mdl);
3882
3883 print_indent(indent);
3884 outs() << " count " << mdl.count << "\n";
3885
3886 list = r + sizeof(struct objc_method_description_list_t);
3887 for (i = 0; i < mdl.count; i++) {
3888 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3889 print_indent(indent);
3890 outs() << " remaining list entries extend past the of the section\n";
3891 break;
3892 }
3893 print_indent(indent);
3894 outs() << " list[" << i << "]\n";
3895 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3896 sizeof(struct objc_method_description_t));
3897 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3898 swapStruct(md);
3899
3900 print_indent(indent);
3901 outs() << " name " << format("0x%08" PRIx32, md.name);
3902 if (info->verbose) {
3903 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3904 if (name != nullptr)
3905 outs() << format(" %.*s", xleft, name);
3906 else
3907 outs() << " (not in an __OBJC section)";
3908 }
3909 outs() << "\n";
3910
3911 print_indent(indent);
3912 outs() << " types " << format("0x%08" PRIx32, md.types);
3913 if (info->verbose) {
3914 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3915 if (name != nullptr)
3916 outs() << format(" %.*s", xleft, name);
3917 else
3918 outs() << " (not in an __OBJC section)";
3919 }
3920 outs() << "\n";
3921 }
3922 return false;
3923}
3924
3925static bool print_protocol_list(uint32_t p, uint32_t indent,
3926 struct DisassembleInfo *info);
3927
3928static bool print_protocol(uint32_t p, uint32_t indent,
3929 struct DisassembleInfo *info) {
3930 uint32_t offset, left;
3931 SectionRef S;
3932 struct objc_protocol_t protocol;
3933 const char *r, *name;
3934
3935 r = get_pointer_32(p, offset, left, S, info, true);
3936 if (r == nullptr)
3937 return true;
3938
3939 outs() << "\n";
3940 if (left >= sizeof(struct objc_protocol_t)) {
3941 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3942 } else {
3943 print_indent(indent);
3944 outs() << " Protocol extends past end of the section\n";
3945 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3946 memcpy(&protocol, r, left);
3947 }
3948 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3949 swapStruct(protocol);
3950
3951 print_indent(indent);
3952 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3953 << "\n";
3954
3955 print_indent(indent);
3956 outs() << " protocol_name "
3957 << format("0x%08" PRIx32, protocol.protocol_name);
3958 if (info->verbose) {
3959 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3960 if (name != nullptr)
3961 outs() << format(" %.*s", left, name);
3962 else
3963 outs() << " (not in an __OBJC section)";
3964 }
3965 outs() << "\n";
3966
3967 print_indent(indent);
3968 outs() << " protocol_list "
3969 << format("0x%08" PRIx32, protocol.protocol_list);
3970 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3971 outs() << " (not in an __OBJC section)\n";
3972
3973 print_indent(indent);
3974 outs() << " instance_methods "
3975 << format("0x%08" PRIx32, protocol.instance_methods);
3976 if (print_method_description_list(protocol.instance_methods, indent, info))
3977 outs() << " (not in an __OBJC section)\n";
3978
3979 print_indent(indent);
3980 outs() << " class_methods "
3981 << format("0x%08" PRIx32, protocol.class_methods);
3982 if (print_method_description_list(protocol.class_methods, indent, info))
3983 outs() << " (not in an __OBJC section)\n";
3984
3985 return false;
3986}
3987
3988static bool print_protocol_list(uint32_t p, uint32_t indent,
3989 struct DisassembleInfo *info) {
3990 uint32_t offset, left, l;
3991 SectionRef S;
3992 struct objc_protocol_list_t protocol_list;
3993 const char *r, *list;
3994 int32_t i;
3995
3996 r = get_pointer_32(p, offset, left, S, info, true);
3997 if (r == nullptr)
3998 return true;
3999
4000 outs() << "\n";
4001 if (left > sizeof(struct objc_protocol_list_t)) {
4002 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4003 } else {
4004 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4005 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4006 memcpy(&protocol_list, r, left);
4007 }
4008 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4009 swapStruct(protocol_list);
4010
4011 print_indent(indent);
4012 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4013 << "\n";
4014 print_indent(indent);
4015 outs() << " count " << protocol_list.count << "\n";
4016
4017 list = r + sizeof(struct objc_protocol_list_t);
4018 for (i = 0; i < protocol_list.count; i++) {
4019 if ((i + 1) * sizeof(uint32_t) > left) {
4020 outs() << "\t\t remaining list entries extend past the of the section\n";
4021 break;
4022 }
4023 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4024 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4025 sys::swapByteOrder(l);
4026
4027 print_indent(indent);
4028 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4029 if (print_protocol(l, indent, info))
4030 outs() << "(not in an __OBJC section)\n";
4031 }
4032 return false;
4033}
4034
Kevin Enderby0fc11822015-04-01 20:57:01 +00004035static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4036 struct ivar_list64_t il;
4037 struct ivar64_t i;
4038 const char *r;
4039 uint32_t offset, xoffset, left, j;
4040 SectionRef S, xS;
4041 const char *name, *sym_name, *ivar_offset_p;
4042 uint64_t ivar_offset, n_value;
4043
4044 r = get_pointer_64(p, offset, left, S, info);
4045 if (r == nullptr)
4046 return;
4047 memset(&il, '\0', sizeof(struct ivar_list64_t));
4048 if (left < sizeof(struct ivar_list64_t)) {
4049 memcpy(&il, r, left);
4050 outs() << " (ivar_list_t entends past the end of the section)\n";
4051 } else
4052 memcpy(&il, r, sizeof(struct ivar_list64_t));
4053 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4054 swapStruct(il);
4055 outs() << " entsize " << il.entsize << "\n";
4056 outs() << " count " << il.count << "\n";
4057
4058 p += sizeof(struct ivar_list64_t);
4059 offset += sizeof(struct ivar_list64_t);
4060 for (j = 0; j < il.count; j++) {
4061 r = get_pointer_64(p, offset, left, S, info);
4062 if (r == nullptr)
4063 return;
4064 memset(&i, '\0', sizeof(struct ivar64_t));
4065 if (left < sizeof(struct ivar64_t)) {
4066 memcpy(&i, r, left);
4067 outs() << " (ivar_t entends past the end of the section)\n";
4068 } else
4069 memcpy(&i, r, sizeof(struct ivar64_t));
4070 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4071 swapStruct(i);
4072
4073 outs() << "\t\t\t offset ";
4074 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4075 info, n_value, i.offset);
4076 if (n_value != 0) {
4077 if (info->verbose && sym_name != nullptr)
4078 outs() << sym_name;
4079 else
4080 outs() << format("0x%" PRIx64, n_value);
4081 if (i.offset != 0)
4082 outs() << " + " << format("0x%" PRIx64, i.offset);
4083 } else
4084 outs() << format("0x%" PRIx64, i.offset);
4085 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4086 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4087 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4088 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4089 sys::swapByteOrder(ivar_offset);
4090 outs() << " " << ivar_offset << "\n";
4091 } else
4092 outs() << "\n";
4093
4094 outs() << "\t\t\t name ";
4095 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4096 n_value, i.name);
4097 if (n_value != 0) {
4098 if (info->verbose && sym_name != nullptr)
4099 outs() << sym_name;
4100 else
4101 outs() << format("0x%" PRIx64, n_value);
4102 if (i.name != 0)
4103 outs() << " + " << format("0x%" PRIx64, i.name);
4104 } else
4105 outs() << format("0x%" PRIx64, i.name);
4106 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4107 if (name != nullptr)
4108 outs() << format(" %.*s", left, name);
4109 outs() << "\n";
4110
4111 outs() << "\t\t\t type ";
4112 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4113 n_value, i.name);
4114 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4115 if (n_value != 0) {
4116 if (info->verbose && sym_name != nullptr)
4117 outs() << sym_name;
4118 else
4119 outs() << format("0x%" PRIx64, n_value);
4120 if (i.type != 0)
4121 outs() << " + " << format("0x%" PRIx64, i.type);
4122 } else
4123 outs() << format("0x%" PRIx64, i.type);
4124 if (name != nullptr)
4125 outs() << format(" %.*s", left, name);
4126 outs() << "\n";
4127
4128 outs() << "\t\t\talignment " << i.alignment << "\n";
4129 outs() << "\t\t\t size " << i.size << "\n";
4130
4131 p += sizeof(struct ivar64_t);
4132 offset += sizeof(struct ivar64_t);
4133 }
4134}
4135
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004136static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4137 struct ivar_list32_t il;
4138 struct ivar32_t i;
4139 const char *r;
4140 uint32_t offset, xoffset, left, j;
4141 SectionRef S, xS;
4142 const char *name, *ivar_offset_p;
4143 uint32_t ivar_offset;
4144
4145 r = get_pointer_32(p, offset, left, S, info);
4146 if (r == nullptr)
4147 return;
4148 memset(&il, '\0', sizeof(struct ivar_list32_t));
4149 if (left < sizeof(struct ivar_list32_t)) {
4150 memcpy(&il, r, left);
4151 outs() << " (ivar_list_t entends past the end of the section)\n";
4152 } else
4153 memcpy(&il, r, sizeof(struct ivar_list32_t));
4154 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4155 swapStruct(il);
4156 outs() << " entsize " << il.entsize << "\n";
4157 outs() << " count " << il.count << "\n";
4158
4159 p += sizeof(struct ivar_list32_t);
4160 offset += sizeof(struct ivar_list32_t);
4161 for (j = 0; j < il.count; j++) {
4162 r = get_pointer_32(p, offset, left, S, info);
4163 if (r == nullptr)
4164 return;
4165 memset(&i, '\0', sizeof(struct ivar32_t));
4166 if (left < sizeof(struct ivar32_t)) {
4167 memcpy(&i, r, left);
4168 outs() << " (ivar_t entends past the end of the section)\n";
4169 } else
4170 memcpy(&i, r, sizeof(struct ivar32_t));
4171 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4172 swapStruct(i);
4173
4174 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4175 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4176 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4177 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4178 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4179 sys::swapByteOrder(ivar_offset);
4180 outs() << " " << ivar_offset << "\n";
4181 } else
4182 outs() << "\n";
4183
4184 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4185 name = get_pointer_32(i.name, xoffset, left, xS, info);
4186 if (name != nullptr)
4187 outs() << format(" %.*s", left, name);
4188 outs() << "\n";
4189
4190 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4191 name = get_pointer_32(i.type, xoffset, left, xS, info);
4192 if (name != nullptr)
4193 outs() << format(" %.*s", left, name);
4194 outs() << "\n";
4195
4196 outs() << "\t\t\talignment " << i.alignment << "\n";
4197 outs() << "\t\t\t size " << i.size << "\n";
4198
4199 p += sizeof(struct ivar32_t);
4200 offset += sizeof(struct ivar32_t);
4201 }
4202}
4203
Kevin Enderby0fc11822015-04-01 20:57:01 +00004204static void print_objc_property_list64(uint64_t p,
4205 struct DisassembleInfo *info) {
4206 struct objc_property_list64 opl;
4207 struct objc_property64 op;
4208 const char *r;
4209 uint32_t offset, xoffset, left, j;
4210 SectionRef S, xS;
4211 const char *name, *sym_name;
4212 uint64_t n_value;
4213
4214 r = get_pointer_64(p, offset, left, S, info);
4215 if (r == nullptr)
4216 return;
4217 memset(&opl, '\0', sizeof(struct objc_property_list64));
4218 if (left < sizeof(struct objc_property_list64)) {
4219 memcpy(&opl, r, left);
4220 outs() << " (objc_property_list entends past the end of the section)\n";
4221 } else
4222 memcpy(&opl, r, sizeof(struct objc_property_list64));
4223 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4224 swapStruct(opl);
4225 outs() << " entsize " << opl.entsize << "\n";
4226 outs() << " count " << opl.count << "\n";
4227
4228 p += sizeof(struct objc_property_list64);
4229 offset += sizeof(struct objc_property_list64);
4230 for (j = 0; j < opl.count; j++) {
4231 r = get_pointer_64(p, offset, left, S, info);
4232 if (r == nullptr)
4233 return;
4234 memset(&op, '\0', sizeof(struct objc_property64));
4235 if (left < sizeof(struct objc_property64)) {
4236 memcpy(&op, r, left);
4237 outs() << " (objc_property entends past the end of the section)\n";
4238 } else
4239 memcpy(&op, r, sizeof(struct objc_property64));
4240 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4241 swapStruct(op);
4242
4243 outs() << "\t\t\t name ";
4244 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4245 info, n_value, op.name);
4246 if (n_value != 0) {
4247 if (info->verbose && sym_name != nullptr)
4248 outs() << sym_name;
4249 else
4250 outs() << format("0x%" PRIx64, n_value);
4251 if (op.name != 0)
4252 outs() << " + " << format("0x%" PRIx64, op.name);
4253 } else
4254 outs() << format("0x%" PRIx64, op.name);
4255 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4256 if (name != nullptr)
4257 outs() << format(" %.*s", left, name);
4258 outs() << "\n";
4259
4260 outs() << "\t\t\tattributes ";
4261 sym_name =
4262 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4263 info, n_value, op.attributes);
4264 if (n_value != 0) {
4265 if (info->verbose && sym_name != nullptr)
4266 outs() << sym_name;
4267 else
4268 outs() << format("0x%" PRIx64, n_value);
4269 if (op.attributes != 0)
4270 outs() << " + " << format("0x%" PRIx64, op.attributes);
4271 } else
4272 outs() << format("0x%" PRIx64, op.attributes);
4273 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4274 if (name != nullptr)
4275 outs() << format(" %.*s", left, name);
4276 outs() << "\n";
4277
4278 p += sizeof(struct objc_property64);
4279 offset += sizeof(struct objc_property64);
4280 }
4281}
4282
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004283static void print_objc_property_list32(uint32_t p,
4284 struct DisassembleInfo *info) {
4285 struct objc_property_list32 opl;
4286 struct objc_property32 op;
4287 const char *r;
4288 uint32_t offset, xoffset, left, j;
4289 SectionRef S, xS;
4290 const char *name;
4291
4292 r = get_pointer_32(p, offset, left, S, info);
4293 if (r == nullptr)
4294 return;
4295 memset(&opl, '\0', sizeof(struct objc_property_list32));
4296 if (left < sizeof(struct objc_property_list32)) {
4297 memcpy(&opl, r, left);
4298 outs() << " (objc_property_list entends past the end of the section)\n";
4299 } else
4300 memcpy(&opl, r, sizeof(struct objc_property_list32));
4301 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4302 swapStruct(opl);
4303 outs() << " entsize " << opl.entsize << "\n";
4304 outs() << " count " << opl.count << "\n";
4305
4306 p += sizeof(struct objc_property_list32);
4307 offset += sizeof(struct objc_property_list32);
4308 for (j = 0; j < opl.count; j++) {
4309 r = get_pointer_32(p, offset, left, S, info);
4310 if (r == nullptr)
4311 return;
4312 memset(&op, '\0', sizeof(struct objc_property32));
4313 if (left < sizeof(struct objc_property32)) {
4314 memcpy(&op, r, left);
4315 outs() << " (objc_property entends past the end of the section)\n";
4316 } else
4317 memcpy(&op, r, sizeof(struct objc_property32));
4318 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4319 swapStruct(op);
4320
4321 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4322 name = get_pointer_32(op.name, xoffset, left, xS, info);
4323 if (name != nullptr)
4324 outs() << format(" %.*s", left, name);
4325 outs() << "\n";
4326
4327 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4328 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4329 if (name != nullptr)
4330 outs() << format(" %.*s", left, name);
4331 outs() << "\n";
4332
4333 p += sizeof(struct objc_property32);
4334 offset += sizeof(struct objc_property32);
4335 }
4336}
4337
Richard Smith81ff44d2015-10-09 22:09:56 +00004338static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004339 bool &is_meta_class) {
4340 struct class_ro64_t cro;
4341 const char *r;
4342 uint32_t offset, xoffset, left;
4343 SectionRef S, xS;
4344 const char *name, *sym_name;
4345 uint64_t n_value;
4346
4347 r = get_pointer_64(p, offset, left, S, info);
4348 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004349 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004350 memset(&cro, '\0', sizeof(struct class_ro64_t));
4351 if (left < sizeof(struct class_ro64_t)) {
4352 memcpy(&cro, r, left);
4353 outs() << " (class_ro_t entends past the end of the section)\n";
4354 } else
4355 memcpy(&cro, r, sizeof(struct class_ro64_t));
4356 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4357 swapStruct(cro);
4358 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4359 if (cro.flags & RO_META)
4360 outs() << " RO_META";
4361 if (cro.flags & RO_ROOT)
4362 outs() << " RO_ROOT";
4363 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4364 outs() << " RO_HAS_CXX_STRUCTORS";
4365 outs() << "\n";
4366 outs() << " instanceStart " << cro.instanceStart << "\n";
4367 outs() << " instanceSize " << cro.instanceSize << "\n";
4368 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4369 << "\n";
4370 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4371 << "\n";
4372 print_layout_map64(cro.ivarLayout, info);
4373
4374 outs() << " name ";
4375 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4376 info, n_value, cro.name);
4377 if (n_value != 0) {
4378 if (info->verbose && sym_name != nullptr)
4379 outs() << sym_name;
4380 else
4381 outs() << format("0x%" PRIx64, n_value);
4382 if (cro.name != 0)
4383 outs() << " + " << format("0x%" PRIx64, cro.name);
4384 } else
4385 outs() << format("0x%" PRIx64, cro.name);
4386 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4387 if (name != nullptr)
4388 outs() << format(" %.*s", left, name);
4389 outs() << "\n";
4390
4391 outs() << " baseMethods ";
4392 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4393 S, info, n_value, cro.baseMethods);
4394 if (n_value != 0) {
4395 if (info->verbose && sym_name != nullptr)
4396 outs() << sym_name;
4397 else
4398 outs() << format("0x%" PRIx64, n_value);
4399 if (cro.baseMethods != 0)
4400 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4401 } else
4402 outs() << format("0x%" PRIx64, cro.baseMethods);
4403 outs() << " (struct method_list_t *)\n";
4404 if (cro.baseMethods + n_value != 0)
4405 print_method_list64_t(cro.baseMethods + n_value, info, "");
4406
4407 outs() << " baseProtocols ";
4408 sym_name =
4409 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4410 info, n_value, cro.baseProtocols);
4411 if (n_value != 0) {
4412 if (info->verbose && sym_name != nullptr)
4413 outs() << sym_name;
4414 else
4415 outs() << format("0x%" PRIx64, n_value);
4416 if (cro.baseProtocols != 0)
4417 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4418 } else
4419 outs() << format("0x%" PRIx64, cro.baseProtocols);
4420 outs() << "\n";
4421 if (cro.baseProtocols + n_value != 0)
4422 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4423
4424 outs() << " ivars ";
4425 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004426 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004427 if (n_value != 0) {
4428 if (info->verbose && sym_name != nullptr)
4429 outs() << sym_name;
4430 else
4431 outs() << format("0x%" PRIx64, n_value);
4432 if (cro.ivars != 0)
4433 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4434 } else
4435 outs() << format("0x%" PRIx64, cro.ivars);
4436 outs() << "\n";
4437 if (cro.ivars + n_value != 0)
4438 print_ivar_list64_t(cro.ivars + n_value, info);
4439
4440 outs() << " weakIvarLayout ";
4441 sym_name =
4442 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4443 info, n_value, cro.weakIvarLayout);
4444 if (n_value != 0) {
4445 if (info->verbose && sym_name != nullptr)
4446 outs() << sym_name;
4447 else
4448 outs() << format("0x%" PRIx64, n_value);
4449 if (cro.weakIvarLayout != 0)
4450 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4451 } else
4452 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4453 outs() << "\n";
4454 print_layout_map64(cro.weakIvarLayout + n_value, info);
4455
4456 outs() << " baseProperties ";
4457 sym_name =
4458 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4459 info, n_value, cro.baseProperties);
4460 if (n_value != 0) {
4461 if (info->verbose && sym_name != nullptr)
4462 outs() << sym_name;
4463 else
4464 outs() << format("0x%" PRIx64, n_value);
4465 if (cro.baseProperties != 0)
4466 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4467 } else
4468 outs() << format("0x%" PRIx64, cro.baseProperties);
4469 outs() << "\n";
4470 if (cro.baseProperties + n_value != 0)
4471 print_objc_property_list64(cro.baseProperties + n_value, info);
4472
Rafael Espindolab9091322015-10-24 23:19:10 +00004473 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004474 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004475}
4476
Richard Smith81ff44d2015-10-09 22:09:56 +00004477static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004478 bool &is_meta_class) {
4479 struct class_ro32_t cro;
4480 const char *r;
4481 uint32_t offset, xoffset, left;
4482 SectionRef S, xS;
4483 const char *name;
4484
4485 r = get_pointer_32(p, offset, left, S, info);
4486 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004487 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004488 memset(&cro, '\0', sizeof(struct class_ro32_t));
4489 if (left < sizeof(struct class_ro32_t)) {
4490 memcpy(&cro, r, left);
4491 outs() << " (class_ro_t entends past the end of the section)\n";
4492 } else
4493 memcpy(&cro, r, sizeof(struct class_ro32_t));
4494 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4495 swapStruct(cro);
4496 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4497 if (cro.flags & RO_META)
4498 outs() << " RO_META";
4499 if (cro.flags & RO_ROOT)
4500 outs() << " RO_ROOT";
4501 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4502 outs() << " RO_HAS_CXX_STRUCTORS";
4503 outs() << "\n";
4504 outs() << " instanceStart " << cro.instanceStart << "\n";
4505 outs() << " instanceSize " << cro.instanceSize << "\n";
4506 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4507 << "\n";
4508 print_layout_map32(cro.ivarLayout, info);
4509
4510 outs() << " name " << format("0x%" PRIx32, cro.name);
4511 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4512 if (name != nullptr)
4513 outs() << format(" %.*s", left, name);
4514 outs() << "\n";
4515
4516 outs() << " baseMethods "
4517 << format("0x%" PRIx32, cro.baseMethods)
4518 << " (struct method_list_t *)\n";
4519 if (cro.baseMethods != 0)
4520 print_method_list32_t(cro.baseMethods, info, "");
4521
4522 outs() << " baseProtocols "
4523 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4524 if (cro.baseProtocols != 0)
4525 print_protocol_list32_t(cro.baseProtocols, info);
4526 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4527 << "\n";
4528 if (cro.ivars != 0)
4529 print_ivar_list32_t(cro.ivars, info);
4530 outs() << " weakIvarLayout "
4531 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4532 print_layout_map32(cro.weakIvarLayout, info);
4533 outs() << " baseProperties "
4534 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4535 if (cro.baseProperties != 0)
4536 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004537 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004538 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004539}
4540
Kevin Enderby0fc11822015-04-01 20:57:01 +00004541static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4542 struct class64_t c;
4543 const char *r;
4544 uint32_t offset, left;
4545 SectionRef S;
4546 const char *name;
4547 uint64_t isa_n_value, n_value;
4548
4549 r = get_pointer_64(p, offset, left, S, info);
4550 if (r == nullptr || left < sizeof(struct class64_t))
4551 return;
4552 memset(&c, '\0', sizeof(struct class64_t));
4553 if (left < sizeof(struct class64_t)) {
4554 memcpy(&c, r, left);
4555 outs() << " (class_t entends past the end of the section)\n";
4556 } else
4557 memcpy(&c, r, sizeof(struct class64_t));
4558 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4559 swapStruct(c);
4560
4561 outs() << " isa " << format("0x%" PRIx64, c.isa);
4562 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4563 isa_n_value, c.isa);
4564 if (name != nullptr)
4565 outs() << " " << name;
4566 outs() << "\n";
4567
4568 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4569 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4570 n_value, c.superclass);
4571 if (name != nullptr)
4572 outs() << " " << name;
4573 outs() << "\n";
4574
4575 outs() << " cache " << format("0x%" PRIx64, c.cache);
4576 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4577 n_value, c.cache);
4578 if (name != nullptr)
4579 outs() << " " << name;
4580 outs() << "\n";
4581
4582 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4583 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4584 n_value, c.vtable);
4585 if (name != nullptr)
4586 outs() << " " << name;
4587 outs() << "\n";
4588
4589 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4590 n_value, c.data);
4591 outs() << " data ";
4592 if (n_value != 0) {
4593 if (info->verbose && name != nullptr)
4594 outs() << name;
4595 else
4596 outs() << format("0x%" PRIx64, n_value);
4597 if (c.data != 0)
4598 outs() << " + " << format("0x%" PRIx64, c.data);
4599 } else
4600 outs() << format("0x%" PRIx64, c.data);
4601 outs() << " (struct class_ro_t *)";
4602
4603 // This is a Swift class if some of the low bits of the pointer are set.
4604 if ((c.data + n_value) & 0x7)
4605 outs() << " Swift class";
4606 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004607 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004608 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4609 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004610
Kevin Enderbyaac75382015-10-08 16:56:35 +00004611 if (!is_meta_class &&
4612 c.isa + isa_n_value != p &&
4613 c.isa + isa_n_value != 0 &&
4614 info->depth < 100) {
4615 info->depth++;
4616 outs() << "Meta Class\n";
4617 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004618 }
4619}
4620
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004621static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4622 struct class32_t c;
4623 const char *r;
4624 uint32_t offset, left;
4625 SectionRef S;
4626 const char *name;
4627
4628 r = get_pointer_32(p, offset, left, S, info);
4629 if (r == nullptr)
4630 return;
4631 memset(&c, '\0', sizeof(struct class32_t));
4632 if (left < sizeof(struct class32_t)) {
4633 memcpy(&c, r, left);
4634 outs() << " (class_t entends past the end of the section)\n";
4635 } else
4636 memcpy(&c, r, sizeof(struct class32_t));
4637 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4638 swapStruct(c);
4639
4640 outs() << " isa " << format("0x%" PRIx32, c.isa);
4641 name =
4642 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4643 if (name != nullptr)
4644 outs() << " " << name;
4645 outs() << "\n";
4646
4647 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4648 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4649 c.superclass);
4650 if (name != nullptr)
4651 outs() << " " << name;
4652 outs() << "\n";
4653
4654 outs() << " cache " << format("0x%" PRIx32, c.cache);
4655 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4656 c.cache);
4657 if (name != nullptr)
4658 outs() << " " << name;
4659 outs() << "\n";
4660
4661 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4662 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4663 c.vtable);
4664 if (name != nullptr)
4665 outs() << " " << name;
4666 outs() << "\n";
4667
4668 name =
4669 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4670 outs() << " data " << format("0x%" PRIx32, c.data)
4671 << " (struct class_ro_t *)";
4672
4673 // This is a Swift class if some of the low bits of the pointer are set.
4674 if (c.data & 0x3)
4675 outs() << " Swift class";
4676 outs() << "\n";
4677 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004678 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4679 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004680
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004681 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004682 outs() << "Meta Class\n";
4683 print_class32_t(c.isa, info);
4684 }
4685}
4686
Kevin Enderby846c0002015-04-16 17:19:59 +00004687static void print_objc_class_t(struct objc_class_t *objc_class,
4688 struct DisassembleInfo *info) {
4689 uint32_t offset, left, xleft;
4690 const char *name, *p, *ivar_list;
4691 SectionRef S;
4692 int32_t i;
4693 struct objc_ivar_list_t objc_ivar_list;
4694 struct objc_ivar_t ivar;
4695
4696 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4697 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4698 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4699 if (name != nullptr)
4700 outs() << format(" %.*s", left, name);
4701 else
4702 outs() << " (not in an __OBJC section)";
4703 }
4704 outs() << "\n";
4705
4706 outs() << "\t super_class "
4707 << format("0x%08" PRIx32, objc_class->super_class);
4708 if (info->verbose) {
4709 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4710 if (name != nullptr)
4711 outs() << format(" %.*s", left, name);
4712 else
4713 outs() << " (not in an __OBJC section)";
4714 }
4715 outs() << "\n";
4716
4717 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4718 if (info->verbose) {
4719 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4720 if (name != nullptr)
4721 outs() << format(" %.*s", left, name);
4722 else
4723 outs() << " (not in an __OBJC section)";
4724 }
4725 outs() << "\n";
4726
4727 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4728 << "\n";
4729
4730 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4731 if (info->verbose) {
4732 if (CLS_GETINFO(objc_class, CLS_CLASS))
4733 outs() << " CLS_CLASS";
4734 else if (CLS_GETINFO(objc_class, CLS_META))
4735 outs() << " CLS_META";
4736 }
4737 outs() << "\n";
4738
4739 outs() << "\t instance_size "
4740 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4741
4742 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4743 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4744 if (p != nullptr) {
4745 if (left > sizeof(struct objc_ivar_list_t)) {
4746 outs() << "\n";
4747 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4748 } else {
4749 outs() << " (entends past the end of the section)\n";
4750 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4751 memcpy(&objc_ivar_list, p, left);
4752 }
4753 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4754 swapStruct(objc_ivar_list);
4755 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4756 ivar_list = p + sizeof(struct objc_ivar_list_t);
4757 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4758 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4759 outs() << "\t\t remaining ivar's extend past the of the section\n";
4760 break;
4761 }
4762 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4763 sizeof(struct objc_ivar_t));
4764 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4765 swapStruct(ivar);
4766
4767 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4768 if (info->verbose) {
4769 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4770 if (name != nullptr)
4771 outs() << format(" %.*s", xleft, name);
4772 else
4773 outs() << " (not in an __OBJC section)";
4774 }
4775 outs() << "\n";
4776
4777 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4778 if (info->verbose) {
4779 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4780 if (name != nullptr)
4781 outs() << format(" %.*s", xleft, name);
4782 else
4783 outs() << " (not in an __OBJC section)";
4784 }
4785 outs() << "\n";
4786
4787 outs() << "\t\t ivar_offset "
4788 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4789 }
4790 } else {
4791 outs() << " (not in an __OBJC section)\n";
4792 }
4793
4794 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4795 if (print_method_list(objc_class->methodLists, info))
4796 outs() << " (not in an __OBJC section)\n";
4797
4798 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4799 << "\n";
4800
4801 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4802 if (print_protocol_list(objc_class->protocols, 16, info))
4803 outs() << " (not in an __OBJC section)\n";
4804}
4805
4806static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4807 struct DisassembleInfo *info) {
4808 uint32_t offset, left;
4809 const char *name;
4810 SectionRef S;
4811
4812 outs() << "\t category name "
4813 << format("0x%08" PRIx32, objc_category->category_name);
4814 if (info->verbose) {
4815 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4816 true);
4817 if (name != nullptr)
4818 outs() << format(" %.*s", left, name);
4819 else
4820 outs() << " (not in an __OBJC section)";
4821 }
4822 outs() << "\n";
4823
4824 outs() << "\t\t class name "
4825 << format("0x%08" PRIx32, objc_category->class_name);
4826 if (info->verbose) {
4827 name =
4828 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4829 if (name != nullptr)
4830 outs() << format(" %.*s", left, name);
4831 else
4832 outs() << " (not in an __OBJC section)";
4833 }
4834 outs() << "\n";
4835
4836 outs() << "\t instance methods "
4837 << format("0x%08" PRIx32, objc_category->instance_methods);
4838 if (print_method_list(objc_category->instance_methods, info))
4839 outs() << " (not in an __OBJC section)\n";
4840
4841 outs() << "\t class methods "
4842 << format("0x%08" PRIx32, objc_category->class_methods);
4843 if (print_method_list(objc_category->class_methods, info))
4844 outs() << " (not in an __OBJC section)\n";
4845}
4846
Kevin Enderby0fc11822015-04-01 20:57:01 +00004847static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4848 struct category64_t c;
4849 const char *r;
4850 uint32_t offset, xoffset, left;
4851 SectionRef S, xS;
4852 const char *name, *sym_name;
4853 uint64_t n_value;
4854
4855 r = get_pointer_64(p, offset, left, S, info);
4856 if (r == nullptr)
4857 return;
4858 memset(&c, '\0', sizeof(struct category64_t));
4859 if (left < sizeof(struct category64_t)) {
4860 memcpy(&c, r, left);
4861 outs() << " (category_t entends past the end of the section)\n";
4862 } else
4863 memcpy(&c, r, sizeof(struct category64_t));
4864 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4865 swapStruct(c);
4866
4867 outs() << " name ";
4868 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4869 info, n_value, c.name);
4870 if (n_value != 0) {
4871 if (info->verbose && sym_name != nullptr)
4872 outs() << sym_name;
4873 else
4874 outs() << format("0x%" PRIx64, n_value);
4875 if (c.name != 0)
4876 outs() << " + " << format("0x%" PRIx64, c.name);
4877 } else
4878 outs() << format("0x%" PRIx64, c.name);
4879 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4880 if (name != nullptr)
4881 outs() << format(" %.*s", left, name);
4882 outs() << "\n";
4883
4884 outs() << " cls ";
4885 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4886 n_value, c.cls);
4887 if (n_value != 0) {
4888 if (info->verbose && sym_name != nullptr)
4889 outs() << sym_name;
4890 else
4891 outs() << format("0x%" PRIx64, n_value);
4892 if (c.cls != 0)
4893 outs() << " + " << format("0x%" PRIx64, c.cls);
4894 } else
4895 outs() << format("0x%" PRIx64, c.cls);
4896 outs() << "\n";
4897 if (c.cls + n_value != 0)
4898 print_class64_t(c.cls + n_value, info);
4899
4900 outs() << " instanceMethods ";
4901 sym_name =
4902 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4903 info, n_value, c.instanceMethods);
4904 if (n_value != 0) {
4905 if (info->verbose && sym_name != nullptr)
4906 outs() << sym_name;
4907 else
4908 outs() << format("0x%" PRIx64, n_value);
4909 if (c.instanceMethods != 0)
4910 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4911 } else
4912 outs() << format("0x%" PRIx64, c.instanceMethods);
4913 outs() << "\n";
4914 if (c.instanceMethods + n_value != 0)
4915 print_method_list64_t(c.instanceMethods + n_value, info, "");
4916
4917 outs() << " classMethods ";
4918 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4919 S, info, n_value, c.classMethods);
4920 if (n_value != 0) {
4921 if (info->verbose && sym_name != nullptr)
4922 outs() << sym_name;
4923 else
4924 outs() << format("0x%" PRIx64, n_value);
4925 if (c.classMethods != 0)
4926 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4927 } else
4928 outs() << format("0x%" PRIx64, c.classMethods);
4929 outs() << "\n";
4930 if (c.classMethods + n_value != 0)
4931 print_method_list64_t(c.classMethods + n_value, info, "");
4932
4933 outs() << " protocols ";
4934 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4935 info, n_value, c.protocols);
4936 if (n_value != 0) {
4937 if (info->verbose && sym_name != nullptr)
4938 outs() << sym_name;
4939 else
4940 outs() << format("0x%" PRIx64, n_value);
4941 if (c.protocols != 0)
4942 outs() << " + " << format("0x%" PRIx64, c.protocols);
4943 } else
4944 outs() << format("0x%" PRIx64, c.protocols);
4945 outs() << "\n";
4946 if (c.protocols + n_value != 0)
4947 print_protocol_list64_t(c.protocols + n_value, info);
4948
4949 outs() << "instanceProperties ";
4950 sym_name =
4951 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4952 S, info, n_value, c.instanceProperties);
4953 if (n_value != 0) {
4954 if (info->verbose && sym_name != nullptr)
4955 outs() << sym_name;
4956 else
4957 outs() << format("0x%" PRIx64, n_value);
4958 if (c.instanceProperties != 0)
4959 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4960 } else
4961 outs() << format("0x%" PRIx64, c.instanceProperties);
4962 outs() << "\n";
4963 if (c.instanceProperties + n_value != 0)
4964 print_objc_property_list64(c.instanceProperties + n_value, info);
4965}
4966
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004967static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4968 struct category32_t c;
4969 const char *r;
4970 uint32_t offset, left;
4971 SectionRef S, xS;
4972 const char *name;
4973
4974 r = get_pointer_32(p, offset, left, S, info);
4975 if (r == nullptr)
4976 return;
4977 memset(&c, '\0', sizeof(struct category32_t));
4978 if (left < sizeof(struct category32_t)) {
4979 memcpy(&c, r, left);
4980 outs() << " (category_t entends past the end of the section)\n";
4981 } else
4982 memcpy(&c, r, sizeof(struct category32_t));
4983 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4984 swapStruct(c);
4985
4986 outs() << " name " << format("0x%" PRIx32, c.name);
4987 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4988 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004989 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004990 outs() << " " << name;
4991 outs() << "\n";
4992
4993 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4994 if (c.cls != 0)
4995 print_class32_t(c.cls, info);
4996 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4997 << "\n";
4998 if (c.instanceMethods != 0)
4999 print_method_list32_t(c.instanceMethods, info, "");
5000 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5001 << "\n";
5002 if (c.classMethods != 0)
5003 print_method_list32_t(c.classMethods, info, "");
5004 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5005 if (c.protocols != 0)
5006 print_protocol_list32_t(c.protocols, info);
5007 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5008 << "\n";
5009 if (c.instanceProperties != 0)
5010 print_objc_property_list32(c.instanceProperties, info);
5011}
5012
Kevin Enderby0fc11822015-04-01 20:57:01 +00005013static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5014 uint32_t i, left, offset, xoffset;
5015 uint64_t p, n_value;
5016 struct message_ref64 mr;
5017 const char *name, *sym_name;
5018 const char *r;
5019 SectionRef xS;
5020
5021 if (S == SectionRef())
5022 return;
5023
5024 StringRef SectName;
5025 S.getName(SectName);
5026 DataRefImpl Ref = S.getRawDataRefImpl();
5027 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5028 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5029 offset = 0;
5030 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5031 p = S.getAddress() + i;
5032 r = get_pointer_64(p, offset, left, S, info);
5033 if (r == nullptr)
5034 return;
5035 memset(&mr, '\0', sizeof(struct message_ref64));
5036 if (left < sizeof(struct message_ref64)) {
5037 memcpy(&mr, r, left);
5038 outs() << " (message_ref entends past the end of the section)\n";
5039 } else
5040 memcpy(&mr, r, sizeof(struct message_ref64));
5041 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5042 swapStruct(mr);
5043
5044 outs() << " imp ";
5045 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5046 n_value, mr.imp);
5047 if (n_value != 0) {
5048 outs() << format("0x%" PRIx64, n_value) << " ";
5049 if (mr.imp != 0)
5050 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5051 } else
5052 outs() << format("0x%" PRIx64, mr.imp) << " ";
5053 if (name != nullptr)
5054 outs() << " " << name;
5055 outs() << "\n";
5056
5057 outs() << " sel ";
5058 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5059 info, n_value, mr.sel);
5060 if (n_value != 0) {
5061 if (info->verbose && sym_name != nullptr)
5062 outs() << sym_name;
5063 else
5064 outs() << format("0x%" PRIx64, n_value);
5065 if (mr.sel != 0)
5066 outs() << " + " << format("0x%" PRIx64, mr.sel);
5067 } else
5068 outs() << format("0x%" PRIx64, mr.sel);
5069 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5070 if (name != nullptr)
5071 outs() << format(" %.*s", left, name);
5072 outs() << "\n";
5073
5074 offset += sizeof(struct message_ref64);
5075 }
5076}
5077
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005078static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5079 uint32_t i, left, offset, xoffset, p;
5080 struct message_ref32 mr;
5081 const char *name, *r;
5082 SectionRef xS;
5083
5084 if (S == SectionRef())
5085 return;
5086
5087 StringRef SectName;
5088 S.getName(SectName);
5089 DataRefImpl Ref = S.getRawDataRefImpl();
5090 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5091 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5092 offset = 0;
5093 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5094 p = S.getAddress() + i;
5095 r = get_pointer_32(p, offset, left, S, info);
5096 if (r == nullptr)
5097 return;
5098 memset(&mr, '\0', sizeof(struct message_ref32));
5099 if (left < sizeof(struct message_ref32)) {
5100 memcpy(&mr, r, left);
5101 outs() << " (message_ref entends past the end of the section)\n";
5102 } else
5103 memcpy(&mr, r, sizeof(struct message_ref32));
5104 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5105 swapStruct(mr);
5106
5107 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5108 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5109 mr.imp);
5110 if (name != nullptr)
5111 outs() << " " << name;
5112 outs() << "\n";
5113
5114 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5115 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5116 if (name != nullptr)
5117 outs() << " " << name;
5118 outs() << "\n";
5119
5120 offset += sizeof(struct message_ref32);
5121 }
5122}
5123
Kevin Enderby0fc11822015-04-01 20:57:01 +00005124static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5125 uint32_t left, offset, swift_version;
5126 uint64_t p;
5127 struct objc_image_info64 o;
5128 const char *r;
5129
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005130 if (S == SectionRef())
5131 return;
5132
Kevin Enderby0fc11822015-04-01 20:57:01 +00005133 StringRef SectName;
5134 S.getName(SectName);
5135 DataRefImpl Ref = S.getRawDataRefImpl();
5136 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5137 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5138 p = S.getAddress();
5139 r = get_pointer_64(p, offset, left, S, info);
5140 if (r == nullptr)
5141 return;
5142 memset(&o, '\0', sizeof(struct objc_image_info64));
5143 if (left < sizeof(struct objc_image_info64)) {
5144 memcpy(&o, r, left);
5145 outs() << " (objc_image_info entends past the end of the section)\n";
5146 } else
5147 memcpy(&o, r, sizeof(struct objc_image_info64));
5148 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5149 swapStruct(o);
5150 outs() << " version " << o.version << "\n";
5151 outs() << " flags " << format("0x%" PRIx32, o.flags);
5152 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5153 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5154 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5155 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5156 swift_version = (o.flags >> 8) & 0xff;
5157 if (swift_version != 0) {
5158 if (swift_version == 1)
5159 outs() << " Swift 1.0";
5160 else if (swift_version == 2)
5161 outs() << " Swift 1.1";
5162 else
5163 outs() << " unknown future Swift version (" << swift_version << ")";
5164 }
5165 outs() << "\n";
5166}
5167
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005168static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5169 uint32_t left, offset, swift_version, p;
5170 struct objc_image_info32 o;
5171 const char *r;
5172
Kevin Enderby19be2512016-04-21 19:49:29 +00005173 if (S == SectionRef())
5174 return;
5175
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005176 StringRef SectName;
5177 S.getName(SectName);
5178 DataRefImpl Ref = S.getRawDataRefImpl();
5179 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5180 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5181 p = S.getAddress();
5182 r = get_pointer_32(p, offset, left, S, info);
5183 if (r == nullptr)
5184 return;
5185 memset(&o, '\0', sizeof(struct objc_image_info32));
5186 if (left < sizeof(struct objc_image_info32)) {
5187 memcpy(&o, r, left);
5188 outs() << " (objc_image_info entends past the end of the section)\n";
5189 } else
5190 memcpy(&o, r, sizeof(struct objc_image_info32));
5191 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5192 swapStruct(o);
5193 outs() << " version " << o.version << "\n";
5194 outs() << " flags " << format("0x%" PRIx32, o.flags);
5195 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5196 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5197 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5198 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5199 swift_version = (o.flags >> 8) & 0xff;
5200 if (swift_version != 0) {
5201 if (swift_version == 1)
5202 outs() << " Swift 1.0";
5203 else if (swift_version == 2)
5204 outs() << " Swift 1.1";
5205 else
5206 outs() << " unknown future Swift version (" << swift_version << ")";
5207 }
5208 outs() << "\n";
5209}
5210
Kevin Enderby846c0002015-04-16 17:19:59 +00005211static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5212 uint32_t left, offset, p;
5213 struct imageInfo_t o;
5214 const char *r;
5215
5216 StringRef SectName;
5217 S.getName(SectName);
5218 DataRefImpl Ref = S.getRawDataRefImpl();
5219 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5220 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5221 p = S.getAddress();
5222 r = get_pointer_32(p, offset, left, S, info);
5223 if (r == nullptr)
5224 return;
5225 memset(&o, '\0', sizeof(struct imageInfo_t));
5226 if (left < sizeof(struct imageInfo_t)) {
5227 memcpy(&o, r, left);
5228 outs() << " (imageInfo entends past the end of the section)\n";
5229 } else
5230 memcpy(&o, r, sizeof(struct imageInfo_t));
5231 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5232 swapStruct(o);
5233 outs() << " version " << o.version << "\n";
5234 outs() << " flags " << format("0x%" PRIx32, o.flags);
5235 if (o.flags & 0x1)
5236 outs() << " F&C";
5237 if (o.flags & 0x2)
5238 outs() << " GC";
5239 if (o.flags & 0x4)
5240 outs() << " GC-only";
5241 else
5242 outs() << " RR";
5243 outs() << "\n";
5244}
5245
Kevin Enderby0fc11822015-04-01 20:57:01 +00005246static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5247 SymbolAddressMap AddrMap;
5248 if (verbose)
5249 CreateSymbolAddressMap(O, &AddrMap);
5250
5251 std::vector<SectionRef> Sections;
5252 for (const SectionRef &Section : O->sections()) {
5253 StringRef SectName;
5254 Section.getName(SectName);
5255 Sections.push_back(Section);
5256 }
5257
5258 struct DisassembleInfo info;
5259 // Set up the block of info used by the Symbolizer call backs.
5260 info.verbose = verbose;
5261 info.O = O;
5262 info.AddrMap = &AddrMap;
5263 info.Sections = &Sections;
5264 info.class_name = nullptr;
5265 info.selector_name = nullptr;
5266 info.method = nullptr;
5267 info.demangled_name = nullptr;
5268 info.bindtable = nullptr;
5269 info.adrp_addr = 0;
5270 info.adrp_inst = 0;
5271
Kevin Enderbyaac75382015-10-08 16:56:35 +00005272 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005273 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5274 if (CL == SectionRef())
5275 CL = get_section(O, "__DATA", "__objc_classlist");
5276 info.S = CL;
5277 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005278
Davide Italiano62507042015-12-11 22:27:59 +00005279 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5280 if (CR == SectionRef())
5281 CR = get_section(O, "__DATA", "__objc_classrefs");
5282 info.S = CR;
5283 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005284
Davide Italiano62507042015-12-11 22:27:59 +00005285 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5286 if (SR == SectionRef())
5287 SR = get_section(O, "__DATA", "__objc_superrefs");
5288 info.S = SR;
5289 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005290
Davide Italiano62507042015-12-11 22:27:59 +00005291 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5292 if (CA == SectionRef())
5293 CA = get_section(O, "__DATA", "__objc_catlist");
5294 info.S = CA;
5295 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005296
Davide Italiano62507042015-12-11 22:27:59 +00005297 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5298 if (PL == SectionRef())
5299 PL = get_section(O, "__DATA", "__objc_protolist");
5300 info.S = PL;
5301 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005302
Davide Italiano62507042015-12-11 22:27:59 +00005303 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5304 if (MR == SectionRef())
5305 MR = get_section(O, "__DATA", "__objc_msgrefs");
5306 info.S = MR;
5307 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005308
Davide Italiano62507042015-12-11 22:27:59 +00005309 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5310 if (II == SectionRef())
5311 II = get_section(O, "__DATA", "__objc_imageinfo");
5312 info.S = II;
5313 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005314
5315 if (info.bindtable != nullptr)
5316 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005317}
5318
5319static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005320 SymbolAddressMap AddrMap;
5321 if (verbose)
5322 CreateSymbolAddressMap(O, &AddrMap);
5323
5324 std::vector<SectionRef> Sections;
5325 for (const SectionRef &Section : O->sections()) {
5326 StringRef SectName;
5327 Section.getName(SectName);
5328 Sections.push_back(Section);
5329 }
5330
5331 struct DisassembleInfo info;
5332 // Set up the block of info used by the Symbolizer call backs.
5333 info.verbose = verbose;
5334 info.O = O;
5335 info.AddrMap = &AddrMap;
5336 info.Sections = &Sections;
5337 info.class_name = nullptr;
5338 info.selector_name = nullptr;
5339 info.method = nullptr;
5340 info.demangled_name = nullptr;
5341 info.bindtable = nullptr;
5342 info.adrp_addr = 0;
5343 info.adrp_inst = 0;
5344
5345 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5346 if (CL != SectionRef()) {
5347 info.S = CL;
5348 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5349 } else {
5350 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5351 info.S = CL;
5352 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5353 }
5354
5355 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5356 if (CR != SectionRef()) {
5357 info.S = CR;
5358 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5359 } else {
5360 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5361 info.S = CR;
5362 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5363 }
5364
5365 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5366 if (SR != SectionRef()) {
5367 info.S = SR;
5368 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5369 } else {
5370 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5371 info.S = SR;
5372 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5373 }
5374
5375 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5376 if (CA != SectionRef()) {
5377 info.S = CA;
5378 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5379 } else {
5380 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5381 info.S = CA;
5382 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5383 }
5384
5385 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5386 if (PL != SectionRef()) {
5387 info.S = PL;
5388 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5389 } else {
5390 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5391 info.S = PL;
5392 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5393 }
5394
5395 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5396 if (MR != SectionRef()) {
5397 info.S = MR;
5398 print_message_refs32(MR, &info);
5399 } else {
5400 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5401 info.S = MR;
5402 print_message_refs32(MR, &info);
5403 }
5404
5405 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5406 if (II != SectionRef()) {
5407 info.S = II;
5408 print_image_info32(II, &info);
5409 } else {
5410 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5411 info.S = II;
5412 print_image_info32(II, &info);
5413 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005414}
5415
5416static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005417 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5418 const char *r, *name, *defs;
5419 struct objc_module_t module;
5420 SectionRef S, xS;
5421 struct objc_symtab_t symtab;
5422 struct objc_class_t objc_class;
5423 struct objc_category_t objc_category;
5424
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005425 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005426 S = get_section(O, "__OBJC", "__module_info");
5427 if (S == SectionRef())
5428 return false;
5429
5430 SymbolAddressMap AddrMap;
5431 if (verbose)
5432 CreateSymbolAddressMap(O, &AddrMap);
5433
5434 std::vector<SectionRef> Sections;
5435 for (const SectionRef &Section : O->sections()) {
5436 StringRef SectName;
5437 Section.getName(SectName);
5438 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005439 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005440
5441 struct DisassembleInfo info;
5442 // Set up the block of info used by the Symbolizer call backs.
5443 info.verbose = verbose;
5444 info.O = O;
5445 info.AddrMap = &AddrMap;
5446 info.Sections = &Sections;
5447 info.class_name = nullptr;
5448 info.selector_name = nullptr;
5449 info.method = nullptr;
5450 info.demangled_name = nullptr;
5451 info.bindtable = nullptr;
5452 info.adrp_addr = 0;
5453 info.adrp_inst = 0;
5454
5455 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5456 p = S.getAddress() + i;
5457 r = get_pointer_32(p, offset, left, S, &info, true);
5458 if (r == nullptr)
5459 return true;
5460 memset(&module, '\0', sizeof(struct objc_module_t));
5461 if (left < sizeof(struct objc_module_t)) {
5462 memcpy(&module, r, left);
5463 outs() << " (module extends past end of __module_info section)\n";
5464 } else
5465 memcpy(&module, r, sizeof(struct objc_module_t));
5466 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5467 swapStruct(module);
5468
5469 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5470 outs() << " version " << module.version << "\n";
5471 outs() << " size " << module.size << "\n";
5472 outs() << " name ";
5473 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5474 if (name != nullptr)
5475 outs() << format("%.*s", left, name);
5476 else
5477 outs() << format("0x%08" PRIx32, module.name)
5478 << "(not in an __OBJC section)";
5479 outs() << "\n";
5480
5481 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5482 if (module.symtab == 0 || r == nullptr) {
5483 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5484 << " (not in an __OBJC section)\n";
5485 continue;
5486 }
5487 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5488 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5489 defs_left = 0;
5490 defs = nullptr;
5491 if (left < sizeof(struct objc_symtab_t)) {
5492 memcpy(&symtab, r, left);
5493 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5494 } else {
5495 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5496 if (left > sizeof(struct objc_symtab_t)) {
5497 defs_left = left - sizeof(struct objc_symtab_t);
5498 defs = r + sizeof(struct objc_symtab_t);
5499 }
5500 }
5501 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5502 swapStruct(symtab);
5503
5504 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5505 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5506 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5507 if (r == nullptr)
5508 outs() << " (not in an __OBJC section)";
5509 outs() << "\n";
5510 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5511 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5512 if (symtab.cls_def_cnt > 0)
5513 outs() << "\tClass Definitions\n";
5514 for (j = 0; j < symtab.cls_def_cnt; j++) {
5515 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5516 outs() << "\t(remaining class defs entries entends past the end of the "
5517 << "section)\n";
5518 break;
5519 }
5520 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5521 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5522 sys::swapByteOrder(def);
5523
5524 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5525 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5526 if (r != nullptr) {
5527 if (left > sizeof(struct objc_class_t)) {
5528 outs() << "\n";
5529 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5530 } else {
5531 outs() << " (entends past the end of the section)\n";
5532 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5533 memcpy(&objc_class, r, left);
5534 }
5535 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5536 swapStruct(objc_class);
5537 print_objc_class_t(&objc_class, &info);
5538 } else {
5539 outs() << "(not in an __OBJC section)\n";
5540 }
5541
5542 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5543 outs() << "\tMeta Class";
5544 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5545 if (r != nullptr) {
5546 if (left > sizeof(struct objc_class_t)) {
5547 outs() << "\n";
5548 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5549 } else {
5550 outs() << " (entends past the end of the section)\n";
5551 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5552 memcpy(&objc_class, r, left);
5553 }
5554 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5555 swapStruct(objc_class);
5556 print_objc_class_t(&objc_class, &info);
5557 } else {
5558 outs() << "(not in an __OBJC section)\n";
5559 }
5560 }
5561 }
5562 if (symtab.cat_def_cnt > 0)
5563 outs() << "\tCategory Definitions\n";
5564 for (j = 0; j < symtab.cat_def_cnt; j++) {
5565 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5566 outs() << "\t(remaining category defs entries entends past the end of "
5567 << "the section)\n";
5568 break;
5569 }
5570 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5571 sizeof(uint32_t));
5572 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5573 sys::swapByteOrder(def);
5574
5575 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5576 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5577 << format("0x%08" PRIx32, def);
5578 if (r != nullptr) {
5579 if (left > sizeof(struct objc_category_t)) {
5580 outs() << "\n";
5581 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5582 } else {
5583 outs() << " (entends past the end of the section)\n";
5584 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5585 memcpy(&objc_category, r, left);
5586 }
5587 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5588 swapStruct(objc_category);
5589 print_objc_objc_category_t(&objc_category, &info);
5590 } else {
5591 outs() << "(not in an __OBJC section)\n";
5592 }
5593 }
5594 }
5595 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5596 if (II != SectionRef())
5597 print_image_info(II, &info);
5598
5599 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005600}
5601
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005602static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5603 uint32_t size, uint32_t addr) {
5604 SymbolAddressMap AddrMap;
5605 CreateSymbolAddressMap(O, &AddrMap);
5606
5607 std::vector<SectionRef> Sections;
5608 for (const SectionRef &Section : O->sections()) {
5609 StringRef SectName;
5610 Section.getName(SectName);
5611 Sections.push_back(Section);
5612 }
5613
5614 struct DisassembleInfo info;
5615 // Set up the block of info used by the Symbolizer call backs.
5616 info.verbose = true;
5617 info.O = O;
5618 info.AddrMap = &AddrMap;
5619 info.Sections = &Sections;
5620 info.class_name = nullptr;
5621 info.selector_name = nullptr;
5622 info.method = nullptr;
5623 info.demangled_name = nullptr;
5624 info.bindtable = nullptr;
5625 info.adrp_addr = 0;
5626 info.adrp_inst = 0;
5627
5628 const char *p;
5629 struct objc_protocol_t protocol;
5630 uint32_t left, paddr;
5631 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5632 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5633 left = size - (p - sect);
5634 if (left < sizeof(struct objc_protocol_t)) {
5635 outs() << "Protocol extends past end of __protocol section\n";
5636 memcpy(&protocol, p, left);
5637 } else
5638 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5639 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5640 swapStruct(protocol);
5641 paddr = addr + (p - sect);
5642 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5643 if (print_protocol(paddr, 0, &info))
5644 outs() << "(not in an __OBJC section)\n";
5645 }
5646}
5647
Kevin Enderby0fc11822015-04-01 20:57:01 +00005648static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5649 if (O->is64Bit())
5650 printObjc2_64bit_MetaData(O, verbose);
5651 else {
5652 MachO::mach_header H;
5653 H = O->getHeader();
5654 if (H.cputype == MachO::CPU_TYPE_ARM)
5655 printObjc2_32bit_MetaData(O, verbose);
5656 else {
5657 // This is the 32-bit non-arm cputype case. Which is normally
5658 // the first Objective-C ABI. But it may be the case of a
5659 // binary for the iOS simulator which is the second Objective-C
5660 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5661 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005662 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005663 printObjc2_32bit_MetaData(O, verbose);
5664 }
5665 }
5666}
5667
Kevin Enderbybf246f52014-09-24 23:08:22 +00005668// GuessLiteralPointer returns a string which for the item in the Mach-O file
5669// for the address passed in as ReferenceValue for printing as a comment with
5670// the instruction and also returns the corresponding type of that item
5671// indirectly through ReferenceType.
5672//
5673// If ReferenceValue is an address of literal cstring then a pointer to the
5674// cstring is returned and ReferenceType is set to
5675// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5676//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005677// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5678// Class ref that name is returned and the ReferenceType is set accordingly.
5679//
5680// Lastly, literals which are Symbol address in a literal pool are looked for
5681// and if found the symbol name is returned and ReferenceType is set to
5682// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5683//
5684// If there is no item in the Mach-O file for the address passed in as
5685// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005686static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5687 uint64_t ReferencePC,
5688 uint64_t *ReferenceType,
5689 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005690 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005691 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5692 uint64_t sect_addr = info->S.getAddress();
5693 uint64_t sect_offset = ReferencePC - sect_addr;
5694 bool reloc_found = false;
5695 DataRefImpl Rel;
5696 MachO::any_relocation_info RE;
5697 bool isExtern = false;
5698 SymbolRef Symbol;
5699 for (const RelocationRef &Reloc : info->S.relocations()) {
5700 uint64_t RelocOffset = Reloc.getOffset();
5701 if (RelocOffset == sect_offset) {
5702 Rel = Reloc.getRawDataRefImpl();
5703 RE = info->O->getRelocation(Rel);
5704 if (info->O->isRelocationScattered(RE))
5705 continue;
5706 isExtern = info->O->getPlainRelocationExternal(RE);
5707 if (isExtern) {
5708 symbol_iterator RelocSym = Reloc.getSymbol();
5709 Symbol = *RelocSym;
5710 }
5711 reloc_found = true;
5712 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005713 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005714 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005715 // If there is an external relocation entry for a symbol in a section
5716 // then used that symbol's value for the value of the reference.
5717 if (reloc_found && isExtern) {
5718 if (info->O->getAnyRelocationPCRel(RE)) {
5719 unsigned Type = info->O->getAnyRelocationType(RE);
5720 if (Type == MachO::X86_64_RELOC_SIGNED) {
5721 ReferenceValue = Symbol.getValue();
5722 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005723 }
5724 }
5725 }
5726
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005727 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5728 // Message refs and Class refs.
5729 bool classref, selref, msgref, cfstring;
5730 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5731 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005732 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005733 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5734 // And the pointer_value in that section is typically zero as it will be
5735 // set by dyld as part of the "bind information".
5736 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5737 if (name != nullptr) {
5738 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005739 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005740 if (class_name != nullptr && class_name[1] == '_' &&
5741 class_name[2] != '\0') {
5742 info->class_name = class_name + 2;
5743 return name;
5744 }
5745 }
5746 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005747
David Blaikie33dd45d02015-03-23 18:39:02 +00005748 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005749 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5750 const char *name =
5751 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5752 if (name != nullptr)
5753 info->class_name = name;
5754 else
5755 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005756 return name;
5757 }
5758
David Blaikie33dd45d02015-03-23 18:39:02 +00005759 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005760 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5761 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5762 return name;
5763 }
5764
David Blaikie33dd45d02015-03-23 18:39:02 +00005765 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005766 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5767
5768 if (pointer_value != 0)
5769 ReferenceValue = pointer_value;
5770
5771 const char *name = GuessCstringPointer(ReferenceValue, info);
5772 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005773 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005774 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5775 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005776 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005777 info->class_name = nullptr;
5778 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5779 info->selector_name = name;
5780 } else
5781 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5782 return name;
5783 }
5784
5785 // Lastly look for an indirect symbol with this ReferenceValue which is in
5786 // a literal pool. If found return that symbol name.
5787 name = GuessIndirectSymbol(ReferenceValue, info);
5788 if (name) {
5789 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5790 return name;
5791 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005792
5793 return nullptr;
5794}
5795
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005796// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005797// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005798// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5799// is created and returns the symbol name that matches the ReferenceValue or
5800// nullptr if none. The ReferenceType is passed in for the IN type of
5801// reference the instruction is making from the values in defined in the header
5802// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5803// Out type and the ReferenceName will also be set which is added as a comment
5804// to the disassembled instruction.
5805//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005806#if HAVE_CXXABI_H
5807// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005808// returned through ReferenceName and ReferenceType is set to
5809// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005810#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005811//
5812// When this is called to get a symbol name for a branch target then the
5813// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5814// SymbolValue will be looked for in the indirect symbol table to determine if
5815// it is an address for a symbol stub. If so then the symbol name for that
5816// stub is returned indirectly through ReferenceName and then ReferenceType is
5817// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5818//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005819// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005820// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5821// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5822// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005823// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005824static const char *SymbolizerSymbolLookUp(void *DisInfo,
5825 uint64_t ReferenceValue,
5826 uint64_t *ReferenceType,
5827 uint64_t ReferencePC,
5828 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005829 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005830 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005831 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005832 *ReferenceName = nullptr;
5833 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005834 return nullptr;
5835 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005836
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005837 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005838
Kevin Enderby85974882014-09-26 22:20:44 +00005839 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5840 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005841 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005842 method_reference(info, ReferenceType, ReferenceName);
5843 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5844 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5845 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005846#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005847 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005848 if (info->demangled_name != nullptr)
5849 free(info->demangled_name);
5850 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005851 info->demangled_name =
5852 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005853 if (info->demangled_name != nullptr) {
5854 *ReferenceName = info->demangled_name;
5855 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5856 } else
5857 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5858 } else
5859#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005860 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5861 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5862 *ReferenceName =
5863 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005864 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005865 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005866 else
5867 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005868 // If this is arm64 and the reference is an adrp instruction save the
5869 // instruction, passed in ReferenceValue and the address of the instruction
5870 // for use later if we see and add immediate instruction.
5871 } else if (info->O->getArch() == Triple::aarch64 &&
5872 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5873 info->adrp_inst = ReferenceValue;
5874 info->adrp_addr = ReferencePC;
5875 SymbolName = nullptr;
5876 *ReferenceName = nullptr;
5877 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5878 // If this is arm64 and reference is an add immediate instruction and we
5879 // have
5880 // seen an adrp instruction just before it and the adrp's Xd register
5881 // matches
5882 // this add's Xn register reconstruct the value being referenced and look to
5883 // see if it is a literal pointer. Note the add immediate instruction is
5884 // passed in ReferenceValue.
5885 } else if (info->O->getArch() == Triple::aarch64 &&
5886 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5887 ReferencePC - 4 == info->adrp_addr &&
5888 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5889 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5890 uint32_t addxri_inst;
5891 uint64_t adrp_imm, addxri_imm;
5892
5893 adrp_imm =
5894 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5895 if (info->adrp_inst & 0x0200000)
5896 adrp_imm |= 0xfffffffffc000000LL;
5897
5898 addxri_inst = ReferenceValue;
5899 addxri_imm = (addxri_inst >> 10) & 0xfff;
5900 if (((addxri_inst >> 22) & 0x3) == 1)
5901 addxri_imm <<= 12;
5902
5903 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5904 (adrp_imm << 12) + addxri_imm;
5905
5906 *ReferenceName =
5907 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5908 if (*ReferenceName == nullptr)
5909 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5910 // If this is arm64 and the reference is a load register instruction and we
5911 // have seen an adrp instruction just before it and the adrp's Xd register
5912 // matches this add's Xn register reconstruct the value being referenced and
5913 // look to see if it is a literal pointer. Note the load register
5914 // instruction is passed in ReferenceValue.
5915 } else if (info->O->getArch() == Triple::aarch64 &&
5916 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5917 ReferencePC - 4 == info->adrp_addr &&
5918 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5919 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5920 uint32_t ldrxui_inst;
5921 uint64_t adrp_imm, ldrxui_imm;
5922
5923 adrp_imm =
5924 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5925 if (info->adrp_inst & 0x0200000)
5926 adrp_imm |= 0xfffffffffc000000LL;
5927
5928 ldrxui_inst = ReferenceValue;
5929 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5930
5931 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5932 (adrp_imm << 12) + (ldrxui_imm << 3);
5933
5934 *ReferenceName =
5935 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5936 if (*ReferenceName == nullptr)
5937 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5938 }
5939 // If this arm64 and is an load register (PC-relative) instruction the
5940 // ReferenceValue is the PC plus the immediate value.
5941 else if (info->O->getArch() == Triple::aarch64 &&
5942 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5943 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5944 *ReferenceName =
5945 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5946 if (*ReferenceName == nullptr)
5947 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005948 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005949#if HAVE_CXXABI_H
5950 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5951 if (info->demangled_name != nullptr)
5952 free(info->demangled_name);
5953 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005954 info->demangled_name =
5955 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005956 if (info->demangled_name != nullptr) {
5957 *ReferenceName = info->demangled_name;
5958 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5959 }
5960 }
5961#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005962 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005963 *ReferenceName = nullptr;
5964 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5965 }
5966
5967 return SymbolName;
5968}
5969
Kevin Enderbybf246f52014-09-24 23:08:22 +00005970/// \brief Emits the comments that are stored in the CommentStream.
5971/// Each comment in the CommentStream must end with a newline.
5972static void emitComments(raw_svector_ostream &CommentStream,
5973 SmallString<128> &CommentsToEmit,
5974 formatted_raw_ostream &FormattedOS,
5975 const MCAsmInfo &MAI) {
5976 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005977 StringRef Comments = CommentsToEmit.str();
5978 // Get the default information for printing a comment.
5979 const char *CommentBegin = MAI.getCommentString();
5980 unsigned CommentColumn = MAI.getCommentColumn();
5981 bool IsFirst = true;
5982 while (!Comments.empty()) {
5983 if (!IsFirst)
5984 FormattedOS << '\n';
5985 // Emit a line of comments.
5986 FormattedOS.PadToColumn(CommentColumn);
5987 size_t Position = Comments.find('\n');
5988 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5989 // Move after the newline character.
5990 Comments = Comments.substr(Position + 1);
5991 IsFirst = false;
5992 }
5993 FormattedOS.flush();
5994
5995 // Tell the comment stream that the vector changed underneath it.
5996 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005997}
5998
Kevin Enderby95df54c2015-02-04 01:01:38 +00005999static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6000 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006001 const char *McpuDefault = nullptr;
6002 const Target *ThumbTarget = nullptr;
6003 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006004 if (!TheTarget) {
6005 // GetTarget prints out stuff.
6006 return;
6007 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006008 if (MCPU.empty() && McpuDefault)
6009 MCPU = McpuDefault;
6010
Ahmed Charles56440fd2014-03-06 05:51:42 +00006011 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006012 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006013 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006014 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006015
Kevin Enderbyc9595622014-08-06 23:24:41 +00006016 // Package up features to be passed to target/subtarget
6017 std::string FeaturesStr;
6018 if (MAttrs.size()) {
6019 SubtargetFeatures Features;
6020 for (unsigned i = 0; i != MAttrs.size(); ++i)
6021 Features.AddFeature(MAttrs[i]);
6022 FeaturesStr = Features.getString();
6023 }
6024
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006025 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006026 std::unique_ptr<const MCRegisterInfo> MRI(
6027 TheTarget->createMCRegInfo(TripleName));
6028 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006029 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006030 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006031 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006032 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006033 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006034 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006035 std::unique_ptr<MCSymbolizer> Symbolizer;
6036 struct DisassembleInfo SymbolizerInfo;
6037 std::unique_ptr<MCRelocationInfo> RelInfo(
6038 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6039 if (RelInfo) {
6040 Symbolizer.reset(TheTarget->createMCSymbolizer(
6041 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006042 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006043 DisAsm->setSymbolizer(std::move(Symbolizer));
6044 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006045 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006046 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006047 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006048 // Set the display preference for hex vs. decimal immediates.
6049 IP->setPrintImmHex(PrintImmHex);
6050 // Comment stream and backing vector.
6051 SmallString<128> CommentsToEmit;
6052 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006053 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6054 // if it is done then arm64 comments for string literals don't get printed
6055 // and some constant get printed instead and not setting it causes intel
6056 // (32-bit and 64-bit) comments printed with different spacing before the
6057 // comment causing different diffs with the 'C' disassembler library API.
6058 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006059
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006060 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006061 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006062 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006063 return;
6064 }
6065
Tim Northover09ca33e2016-04-22 23:23:31 +00006066 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006067 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6068 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6069 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006070 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006071 std::unique_ptr<MCInstPrinter> ThumbIP;
6072 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006073 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6074 struct DisassembleInfo ThumbSymbolizerInfo;
6075 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006076 if (ThumbTarget) {
6077 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6078 ThumbAsmInfo.reset(
6079 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6080 ThumbSTI.reset(
6081 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6082 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6083 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006084 MCContext *PtrThumbCtx = ThumbCtx.get();
6085 ThumbRelInfo.reset(
6086 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6087 if (ThumbRelInfo) {
6088 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6089 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006090 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006091 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6092 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006093 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6094 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006095 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6096 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006097 // Set the display preference for hex vs. decimal immediates.
6098 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006099 }
6100
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006101 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006102 errs() << "error: couldn't initialize disassembler for target "
6103 << ThumbTripleName << '\n';
6104 return;
6105 }
6106
Charles Davis8bdfafd2013-09-01 04:28:48 +00006107 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006108
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006109 // FIXME: Using the -cfg command line option, this code used to be able to
6110 // annotate relocations with the referenced symbol's name, and if this was
6111 // inside a __[cf]string section, the data it points to. This is now replaced
6112 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006113 std::vector<SectionRef> Sections;
6114 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006115 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006116 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006117
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006118 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006119 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006120
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006121 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006122 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006123
Kevin Enderby273ae012013-06-06 17:20:50 +00006124 // Build a data in code table that is sorted on by the address of each entry.
6125 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006126 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006127 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006128 else
6129 BaseAddress = BaseSegmentAddress;
6130 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006131 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006132 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006133 uint32_t Offset;
6134 DI->getOffset(Offset);
6135 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6136 }
6137 array_pod_sort(Dices.begin(), Dices.end());
6138
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006139#ifndef NDEBUG
6140 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6141#else
6142 raw_ostream &DebugOut = nulls();
6143#endif
6144
Ahmed Charles56440fd2014-03-06 05:51:42 +00006145 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006146 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006147 // Try to find debug info and set up the DIContext for it.
6148 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006149 // A separate DSym file path was specified, parse it as a macho file,
6150 // get the sections and supply it to the section name parsing machinery.
6151 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006152 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006153 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006154 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006155 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006156 return;
6157 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006158 DbgObj =
6159 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6160 .get()
6161 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006162 }
6163
Eric Christopher7370b552012-11-12 21:40:38 +00006164 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006165 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006166 }
6167
Colin LeMahieufcc32762015-07-29 19:08:10 +00006168 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006169 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006170
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006171 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006172 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006173 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6174 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006175
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006176 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006177
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006178 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006179 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006180 continue;
6181
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006182 StringRef BytesStr;
6183 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006184 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6185 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006186 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006187
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006188 bool symbolTableWorked = false;
6189
Kevin Enderbybf246f52014-09-24 23:08:22 +00006190 // Create a map of symbol addresses to symbol names for use by
6191 // the SymbolizerSymbolLookUp() routine.
6192 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006193 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006194 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006195 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6196 if (!STOrErr) {
6197 std::string Buf;
6198 raw_string_ostream OS(Buf);
6199 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6200 OS.flush();
6201 report_fatal_error(Buf);
6202 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006203 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006204 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6205 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006206 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006207 Expected<StringRef> SymNameOrErr = Symbol.getName();
6208 if (!SymNameOrErr) {
6209 std::string Buf;
6210 raw_string_ostream OS(Buf);
6211 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6212 OS.flush();
6213 report_fatal_error(Buf);
6214 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006215 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006216 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006217 if (!DisSymName.empty() && DisSymName == SymName)
6218 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006219 }
6220 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006221 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006222 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6223 return;
6224 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006225 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006226 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006227 SymbolizerInfo.O = MachOOF;
6228 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006229 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006230 SymbolizerInfo.Sections = &Sections;
6231 SymbolizerInfo.class_name = nullptr;
6232 SymbolizerInfo.selector_name = nullptr;
6233 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006234 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006235 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006236 SymbolizerInfo.adrp_addr = 0;
6237 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006238 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006239 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006240 ThumbSymbolizerInfo.O = MachOOF;
6241 ThumbSymbolizerInfo.S = Sections[SectIdx];
6242 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6243 ThumbSymbolizerInfo.Sections = &Sections;
6244 ThumbSymbolizerInfo.class_name = nullptr;
6245 ThumbSymbolizerInfo.selector_name = nullptr;
6246 ThumbSymbolizerInfo.method = nullptr;
6247 ThumbSymbolizerInfo.demangled_name = nullptr;
6248 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006249 ThumbSymbolizerInfo.adrp_addr = 0;
6250 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006251
Kevin Enderby4b627be2016-04-28 20:14:13 +00006252 unsigned int Arch = MachOOF->getArch();
6253
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006254 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006255 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006256 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6257 if (!SymNameOrErr) {
6258 std::string Buf;
6259 raw_string_ostream OS(Buf);
6260 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6261 OS.flush();
6262 report_fatal_error(Buf);
6263 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006264 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006265
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006266 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6267 if (!STOrErr) {
6268 std::string Buf;
6269 raw_string_ostream OS(Buf);
6270 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6271 OS.flush();
6272 report_fatal_error(Buf);
6273 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006274 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006275 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006276 continue;
6277
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006278 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006279 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006280 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006281 continue;
6282
Kevin Enderby6a221752015-03-17 17:10:57 +00006283 // If we are only disassembling one symbol see if this is that symbol.
6284 if (!DisSymName.empty() && DisSymName != SymName)
6285 continue;
6286
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006287 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006288 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006289 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006290 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006291
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006292 // Stop disassembling either at the beginning of the next symbol or at
6293 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006294 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006295 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006296 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006297 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006298 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6299 if (!STOrErr) {
6300 std::string Buf;
6301 raw_string_ostream OS(Buf);
6302 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6303 OS.flush();
6304 report_fatal_error(Buf);
6305 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006306 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006307 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006308 containsNextSym =
6309 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006310 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006311 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006312 break;
6313 }
6314 ++NextSymIdx;
6315 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006316
Rafael Espindola80291272014-10-08 15:28:58 +00006317 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006318 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006319 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006320
6321 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006322
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006323 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006324 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6325
6326 // We only need the dedicated Thumb target if there's a real choice
6327 // (i.e. we're not targeting M-class) and the function is Thumb.
6328 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006329
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006330 outs() << SymName << ":\n";
6331 DILineInfo lastLine;
6332 for (uint64_t Index = Start; Index < End; Index += Size) {
6333 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006334
Kevin Enderbybf246f52014-09-24 23:08:22 +00006335 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006336 if (!NoLeadingAddr) {
6337 if (FullLeadingAddr) {
6338 if (MachOOF->is64Bit())
6339 outs() << format("%016" PRIx64, PC);
6340 else
6341 outs() << format("%08" PRIx64, PC);
6342 } else {
6343 outs() << format("%8" PRIx64 ":", PC);
6344 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006345 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006346 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006347 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006348
6349 // Check the data in code table here to see if this is data not an
6350 // instruction to be disassembled.
6351 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006352 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006353 dice_table_iterator DTI =
6354 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6355 compareDiceTableEntries);
6356 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006357 uint16_t Length;
6358 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006359 uint16_t Kind;
6360 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006361 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006362 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6363 (PC == (DTI->first + Length - 1)) && (Length & 1))
6364 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006365 continue;
6366 }
6367
Kevin Enderbybf246f52014-09-24 23:08:22 +00006368 SmallVector<char, 64> AnnotationsBytes;
6369 raw_svector_ostream Annotations(AnnotationsBytes);
6370
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006371 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006372 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006373 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006374 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006375 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006376 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006377 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006378 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006379 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006380 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006381 }
6382 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006383 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006384 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006385 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006386 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006387 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006388 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006389
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006390 // Print debug info.
6391 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006392 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006393 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006394 if (dli != lastLine && dli.Line != 0)
6395 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6396 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006397 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006398 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006399 outs() << "\n";
6400 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006401 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006402 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006403 outs() << format("\t.byte 0x%02x #bad opcode\n",
6404 *(Bytes.data() + Index) & 0xff);
6405 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006406 } else if (Arch == Triple::aarch64 ||
6407 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006408 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6409 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6410 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6411 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6412 outs() << format("\t.long\t0x%08x\n", opcode);
6413 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006414 } else if (Arch == Triple::arm) {
6415 assert(IsThumb && "ARM mode should have been dealt with above");
6416 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6417 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6418 outs() << format("\t.short\t0x%04x\n", opcode);
6419 Size = 2;
6420 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006421 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6422 if (Size == 0)
6423 Size = 1; // skip illegible bytes
6424 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006425 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006426 }
6427 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006428 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006429 // Reading the symbol table didn't work, disassemble the whole section.
6430 uint64_t SectAddress = Sections[SectIdx].getAddress();
6431 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006432 uint64_t InstSize;
6433 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006434 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006435
Kevin Enderbybf246f52014-09-24 23:08:22 +00006436 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006437 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6438 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006439 if (!NoLeadingAddr) {
6440 if (FullLeadingAddr) {
6441 if (MachOOF->is64Bit())
6442 outs() << format("%016" PRIx64, PC);
6443 else
6444 outs() << format("%08" PRIx64, PC);
6445 } else {
6446 outs() << format("%8" PRIx64 ":", PC);
6447 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006448 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006449 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006450 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006451 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006452 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006453 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006454 outs() << "\n";
6455 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006456 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006457 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006458 outs() << format("\t.byte 0x%02x #bad opcode\n",
6459 *(Bytes.data() + Index) & 0xff);
6460 InstSize = 1; // skip exactly one illegible byte and move on.
6461 } else {
6462 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6463 if (InstSize == 0)
6464 InstSize = 1; // skip illegible bytes
6465 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006466 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006467 }
6468 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006469 // The TripleName's need to be reset if we are called again for a different
6470 // archtecture.
6471 TripleName = "";
6472 ThumbTripleName = "";
6473
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006474 if (SymbolizerInfo.method != nullptr)
6475 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006476 if (SymbolizerInfo.demangled_name != nullptr)
6477 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006478 if (SymbolizerInfo.bindtable != nullptr)
6479 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006480 if (ThumbSymbolizerInfo.method != nullptr)
6481 free(ThumbSymbolizerInfo.method);
6482 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6483 free(ThumbSymbolizerInfo.demangled_name);
6484 if (ThumbSymbolizerInfo.bindtable != nullptr)
6485 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006486 }
6487}
Tim Northover4bd286a2014-08-01 13:07:19 +00006488
Tim Northover39c70bb2014-08-12 11:52:59 +00006489//===----------------------------------------------------------------------===//
6490// __compact_unwind section dumping
6491//===----------------------------------------------------------------------===//
6492
Tim Northover4bd286a2014-08-01 13:07:19 +00006493namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006494
6495template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006496 using llvm::support::little;
6497 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006498
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006499 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6500 Buf += sizeof(T);
6501 return Val;
6502}
Tim Northover39c70bb2014-08-12 11:52:59 +00006503
Tim Northover4bd286a2014-08-01 13:07:19 +00006504struct CompactUnwindEntry {
6505 uint32_t OffsetInSection;
6506
6507 uint64_t FunctionAddr;
6508 uint32_t Length;
6509 uint32_t CompactEncoding;
6510 uint64_t PersonalityAddr;
6511 uint64_t LSDAAddr;
6512
6513 RelocationRef FunctionReloc;
6514 RelocationRef PersonalityReloc;
6515 RelocationRef LSDAReloc;
6516
6517 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006518 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006519 if (Is64)
6520 read<uint64_t>(Contents.data() + Offset);
6521 else
6522 read<uint32_t>(Contents.data() + Offset);
6523 }
6524
6525private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006526 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006527 FunctionAddr = readNext<UIntPtr>(Buf);
6528 Length = readNext<uint32_t>(Buf);
6529 CompactEncoding = readNext<uint32_t>(Buf);
6530 PersonalityAddr = readNext<UIntPtr>(Buf);
6531 LSDAAddr = readNext<UIntPtr>(Buf);
6532 }
6533};
6534}
6535
6536/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6537/// and data being relocated, determine the best base Name and Addend to use for
6538/// display purposes.
6539///
6540/// 1. An Extern relocation will directly reference a symbol (and the data is
6541/// then already an addend), so use that.
6542/// 2. Otherwise the data is an offset in the object file's layout; try to find
6543// a symbol before it in the same section, and use the offset from there.
6544/// 3. Finally, if all that fails, fall back to an offset from the start of the
6545/// referenced section.
6546static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6547 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006548 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006549 StringRef &Name, uint64_t &Addend) {
6550 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006551 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6552 if (!NameOrErr) {
6553 std::string Buf;
6554 raw_string_ostream OS(Buf);
6555 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6556 OS.flush();
6557 report_fatal_error(Buf);
6558 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006559 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006560 Addend = Addr;
6561 return;
6562 }
6563
6564 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006565 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006566
Rafael Espindola80291272014-10-08 15:28:58 +00006567 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006568
6569 auto Sym = Symbols.upper_bound(Addr);
6570 if (Sym == Symbols.begin()) {
6571 // The first symbol in the object is after this reference, the best we can
6572 // do is section-relative notation.
6573 RelocSection.getName(Name);
6574 Addend = Addr - SectionAddr;
6575 return;
6576 }
6577
6578 // Go back one so that SymbolAddress <= Addr.
6579 --Sym;
6580
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006581 auto SectOrErr = Sym->second.getSection();
6582 if (!SectOrErr) {
6583 std::string Buf;
6584 raw_string_ostream OS(Buf);
6585 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
6586 OS.flush();
6587 report_fatal_error(Buf);
6588 }
6589 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006590 if (RelocSection == *SymSection) {
6591 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006592 Expected<StringRef> NameOrErr = Sym->second.getName();
6593 if (!NameOrErr) {
6594 std::string Buf;
6595 raw_string_ostream OS(Buf);
6596 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6597 OS.flush();
6598 report_fatal_error(Buf);
6599 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006600 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006601 Addend = Addr - Sym->first;
6602 return;
6603 }
6604
6605 // There is a symbol before this reference, but it's in a different
6606 // section. Probably not helpful to mention it, so use the section name.
6607 RelocSection.getName(Name);
6608 Addend = Addr - SectionAddr;
6609}
6610
6611static void printUnwindRelocDest(const MachOObjectFile *Obj,
6612 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006613 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006614 StringRef Name;
6615 uint64_t Addend;
6616
Rafael Espindola854038e2015-06-26 14:51:16 +00006617 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006618 return;
6619
Tim Northover4bd286a2014-08-01 13:07:19 +00006620 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6621
6622 outs() << Name;
6623 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006624 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006625}
6626
6627static void
6628printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6629 std::map<uint64_t, SymbolRef> &Symbols,
6630 const SectionRef &CompactUnwind) {
6631
6632 assert(Obj->isLittleEndian() &&
6633 "There should not be a big-endian .o with __compact_unwind");
6634
6635 bool Is64 = Obj->is64Bit();
6636 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6637 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6638
6639 StringRef Contents;
6640 CompactUnwind.getContents(Contents);
6641
6642 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6643
6644 // First populate the initial raw offsets, encodings and so on from the entry.
6645 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6646 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6647 CompactUnwinds.push_back(Entry);
6648 }
6649
6650 // Next we need to look at the relocations to find out what objects are
6651 // actually being referred to.
6652 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006653 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006654
6655 uint32_t EntryIdx = RelocAddress / EntrySize;
6656 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6657 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6658
6659 if (OffsetInEntry == 0)
6660 Entry.FunctionReloc = Reloc;
6661 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6662 Entry.PersonalityReloc = Reloc;
6663 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6664 Entry.LSDAReloc = Reloc;
6665 else
6666 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6667 }
6668
6669 // Finally, we're ready to print the data we've gathered.
6670 outs() << "Contents of __compact_unwind section:\n";
6671 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006672 outs() << " Entry at offset "
6673 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006674
6675 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006676 outs() << " start: " << format("0x%" PRIx64,
6677 Entry.FunctionAddr) << ' ';
6678 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006679 outs() << '\n';
6680
6681 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006682 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6683 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006684 // 3. The 32-bit compact encoding.
6685 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006686 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006687
6688 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006689 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006690 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006691 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006692 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6693 Entry.PersonalityAddr);
6694 outs() << '\n';
6695 }
6696
6697 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006698 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006699 outs() << " LSDA: " << format("0x%" PRIx64,
6700 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006701 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6702 outs() << '\n';
6703 }
6704 }
6705}
6706
Tim Northover39c70bb2014-08-12 11:52:59 +00006707//===----------------------------------------------------------------------===//
6708// __unwind_info section dumping
6709//===----------------------------------------------------------------------===//
6710
6711static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6712 const char *Pos = PageStart;
6713 uint32_t Kind = readNext<uint32_t>(Pos);
6714 (void)Kind;
6715 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6716
6717 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6718 uint16_t NumEntries = readNext<uint16_t>(Pos);
6719
6720 Pos = PageStart + EntriesStart;
6721 for (unsigned i = 0; i < NumEntries; ++i) {
6722 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6723 uint32_t Encoding = readNext<uint32_t>(Pos);
6724
6725 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006726 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6727 << ", "
6728 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006729 }
6730}
6731
6732static void printCompressedSecondLevelUnwindPage(
6733 const char *PageStart, uint32_t FunctionBase,
6734 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6735 const char *Pos = PageStart;
6736 uint32_t Kind = readNext<uint32_t>(Pos);
6737 (void)Kind;
6738 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6739
6740 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6741 uint16_t NumEntries = readNext<uint16_t>(Pos);
6742
6743 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6744 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006745 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6746 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006747
6748 Pos = PageStart + EntriesStart;
6749 for (unsigned i = 0; i < NumEntries; ++i) {
6750 uint32_t Entry = readNext<uint32_t>(Pos);
6751 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6752 uint32_t EncodingIdx = Entry >> 24;
6753
6754 uint32_t Encoding;
6755 if (EncodingIdx < CommonEncodings.size())
6756 Encoding = CommonEncodings[EncodingIdx];
6757 else
6758 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6759
6760 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006761 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6762 << ", "
6763 << "encoding[" << EncodingIdx
6764 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006765 }
6766}
6767
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006768static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6769 std::map<uint64_t, SymbolRef> &Symbols,
6770 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006771
6772 assert(Obj->isLittleEndian() &&
6773 "There should not be a big-endian .o with __unwind_info");
6774
6775 outs() << "Contents of __unwind_info section:\n";
6776
6777 StringRef Contents;
6778 UnwindInfo.getContents(Contents);
6779 const char *Pos = Contents.data();
6780
6781 //===----------------------------------
6782 // Section header
6783 //===----------------------------------
6784
6785 uint32_t Version = readNext<uint32_t>(Pos);
6786 outs() << " Version: "
6787 << format("0x%" PRIx32, Version) << '\n';
6788 assert(Version == 1 && "only understand version 1");
6789
6790 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6791 outs() << " Common encodings array section offset: "
6792 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6793 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6794 outs() << " Number of common encodings in array: "
6795 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6796
6797 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6798 outs() << " Personality function array section offset: "
6799 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6800 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6801 outs() << " Number of personality functions in array: "
6802 << format("0x%" PRIx32, NumPersonalities) << '\n';
6803
6804 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6805 outs() << " Index array section offset: "
6806 << format("0x%" PRIx32, IndicesStart) << '\n';
6807 uint32_t NumIndices = readNext<uint32_t>(Pos);
6808 outs() << " Number of indices in array: "
6809 << format("0x%" PRIx32, NumIndices) << '\n';
6810
6811 //===----------------------------------
6812 // A shared list of common encodings
6813 //===----------------------------------
6814
6815 // These occupy indices in the range [0, N] whenever an encoding is referenced
6816 // from a compressed 2nd level index table. In practice the linker only
6817 // creates ~128 of these, so that indices are available to embed encodings in
6818 // the 2nd level index.
6819
6820 SmallVector<uint32_t, 64> CommonEncodings;
6821 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6822 Pos = Contents.data() + CommonEncodingsStart;
6823 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6824 uint32_t Encoding = readNext<uint32_t>(Pos);
6825 CommonEncodings.push_back(Encoding);
6826
6827 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6828 << '\n';
6829 }
6830
Tim Northover39c70bb2014-08-12 11:52:59 +00006831 //===----------------------------------
6832 // Personality functions used in this executable
6833 //===----------------------------------
6834
6835 // There should be only a handful of these (one per source language,
6836 // roughly). Particularly since they only get 2 bits in the compact encoding.
6837
6838 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6839 Pos = Contents.data() + PersonalitiesStart;
6840 for (unsigned i = 0; i < NumPersonalities; ++i) {
6841 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6842 outs() << " personality[" << i + 1
6843 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6844 }
6845
6846 //===----------------------------------
6847 // The level 1 index entries
6848 //===----------------------------------
6849
6850 // These specify an approximate place to start searching for the more detailed
6851 // information, sorted by PC.
6852
6853 struct IndexEntry {
6854 uint32_t FunctionOffset;
6855 uint32_t SecondLevelPageStart;
6856 uint32_t LSDAStart;
6857 };
6858
6859 SmallVector<IndexEntry, 4> IndexEntries;
6860
6861 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6862 Pos = Contents.data() + IndicesStart;
6863 for (unsigned i = 0; i < NumIndices; ++i) {
6864 IndexEntry Entry;
6865
6866 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6867 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6868 Entry.LSDAStart = readNext<uint32_t>(Pos);
6869 IndexEntries.push_back(Entry);
6870
6871 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006872 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6873 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006874 << "2nd level page offset="
6875 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006876 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006877 }
6878
Tim Northover39c70bb2014-08-12 11:52:59 +00006879 //===----------------------------------
6880 // Next come the LSDA tables
6881 //===----------------------------------
6882
6883 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6884 // the first top-level index's LSDAOffset to the last (sentinel).
6885
6886 outs() << " LSDA descriptors:\n";
6887 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6888 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6889 (2 * sizeof(uint32_t));
6890 for (int i = 0; i < NumLSDAs; ++i) {
6891 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6892 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6893 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006894 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6895 << ", "
6896 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006897 }
6898
6899 //===----------------------------------
6900 // Finally, the 2nd level indices
6901 //===----------------------------------
6902
6903 // Generally these are 4K in size, and have 2 possible forms:
6904 // + Regular stores up to 511 entries with disparate encodings
6905 // + Compressed stores up to 1021 entries if few enough compact encoding
6906 // values are used.
6907 outs() << " Second level indices:\n";
6908 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6909 // The final sentinel top-level index has no associated 2nd level page
6910 if (IndexEntries[i].SecondLevelPageStart == 0)
6911 break;
6912
6913 outs() << " Second level index[" << i << "]: "
6914 << "offset in section="
6915 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6916 << ", "
6917 << "base function offset="
6918 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6919
6920 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006921 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006922 if (Kind == 2)
6923 printRegularSecondLevelUnwindPage(Pos);
6924 else if (Kind == 3)
6925 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6926 CommonEncodings);
6927 else
6928 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006929 }
6930}
6931
Tim Northover4bd286a2014-08-01 13:07:19 +00006932void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6933 std::map<uint64_t, SymbolRef> Symbols;
6934 for (const SymbolRef &SymRef : Obj->symbols()) {
6935 // Discard any undefined or absolute symbols. They're not going to take part
6936 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006937 auto SectOrErr = SymRef.getSection();
6938 if (!SectOrErr) {
6939 // TODO: Actually report errors helpfully.
6940 consumeError(SectOrErr.takeError());
6941 continue;
6942 }
6943 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006944 if (Section == Obj->section_end())
6945 continue;
6946
Rafael Espindoladea00162015-07-03 17:44:18 +00006947 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00006948 Symbols.insert(std::make_pair(Addr, SymRef));
6949 }
6950
6951 for (const SectionRef &Section : Obj->sections()) {
6952 StringRef SectName;
6953 Section.getName(SectName);
6954 if (SectName == "__compact_unwind")
6955 printMachOCompactUnwindSection(Obj, Symbols, Section);
6956 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006957 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006958 }
6959}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006960
6961static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6962 uint32_t cpusubtype, uint32_t filetype,
6963 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6964 bool verbose) {
6965 outs() << "Mach header\n";
6966 outs() << " magic cputype cpusubtype caps filetype ncmds "
6967 "sizeofcmds flags\n";
6968 if (verbose) {
6969 if (magic == MachO::MH_MAGIC)
6970 outs() << " MH_MAGIC";
6971 else if (magic == MachO::MH_MAGIC_64)
6972 outs() << "MH_MAGIC_64";
6973 else
6974 outs() << format(" 0x%08" PRIx32, magic);
6975 switch (cputype) {
6976 case MachO::CPU_TYPE_I386:
6977 outs() << " I386";
6978 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6979 case MachO::CPU_SUBTYPE_I386_ALL:
6980 outs() << " ALL";
6981 break;
6982 default:
6983 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6984 break;
6985 }
6986 break;
6987 case MachO::CPU_TYPE_X86_64:
6988 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006989 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6990 case MachO::CPU_SUBTYPE_X86_64_ALL:
6991 outs() << " ALL";
6992 break;
6993 case MachO::CPU_SUBTYPE_X86_64_H:
6994 outs() << " Haswell";
6995 break;
6996 default:
6997 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6998 break;
6999 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007000 break;
7001 case MachO::CPU_TYPE_ARM:
7002 outs() << " ARM";
7003 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7004 case MachO::CPU_SUBTYPE_ARM_ALL:
7005 outs() << " ALL";
7006 break;
7007 case MachO::CPU_SUBTYPE_ARM_V4T:
7008 outs() << " V4T";
7009 break;
7010 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7011 outs() << " V5TEJ";
7012 break;
7013 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7014 outs() << " XSCALE";
7015 break;
7016 case MachO::CPU_SUBTYPE_ARM_V6:
7017 outs() << " V6";
7018 break;
7019 case MachO::CPU_SUBTYPE_ARM_V6M:
7020 outs() << " V6M";
7021 break;
7022 case MachO::CPU_SUBTYPE_ARM_V7:
7023 outs() << " V7";
7024 break;
7025 case MachO::CPU_SUBTYPE_ARM_V7EM:
7026 outs() << " V7EM";
7027 break;
7028 case MachO::CPU_SUBTYPE_ARM_V7K:
7029 outs() << " V7K";
7030 break;
7031 case MachO::CPU_SUBTYPE_ARM_V7M:
7032 outs() << " V7M";
7033 break;
7034 case MachO::CPU_SUBTYPE_ARM_V7S:
7035 outs() << " V7S";
7036 break;
7037 default:
7038 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7039 break;
7040 }
7041 break;
7042 case MachO::CPU_TYPE_ARM64:
7043 outs() << " ARM64";
7044 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7045 case MachO::CPU_SUBTYPE_ARM64_ALL:
7046 outs() << " ALL";
7047 break;
7048 default:
7049 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7050 break;
7051 }
7052 break;
7053 case MachO::CPU_TYPE_POWERPC:
7054 outs() << " PPC";
7055 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7056 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7057 outs() << " ALL";
7058 break;
7059 default:
7060 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7061 break;
7062 }
7063 break;
7064 case MachO::CPU_TYPE_POWERPC64:
7065 outs() << " PPC64";
7066 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7067 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7068 outs() << " ALL";
7069 break;
7070 default:
7071 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7072 break;
7073 }
7074 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007075 default:
7076 outs() << format(" %7d", cputype);
7077 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7078 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007079 }
7080 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007081 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007082 } else {
7083 outs() << format(" 0x%02" PRIx32,
7084 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7085 }
7086 switch (filetype) {
7087 case MachO::MH_OBJECT:
7088 outs() << " OBJECT";
7089 break;
7090 case MachO::MH_EXECUTE:
7091 outs() << " EXECUTE";
7092 break;
7093 case MachO::MH_FVMLIB:
7094 outs() << " FVMLIB";
7095 break;
7096 case MachO::MH_CORE:
7097 outs() << " CORE";
7098 break;
7099 case MachO::MH_PRELOAD:
7100 outs() << " PRELOAD";
7101 break;
7102 case MachO::MH_DYLIB:
7103 outs() << " DYLIB";
7104 break;
7105 case MachO::MH_DYLIB_STUB:
7106 outs() << " DYLIB_STUB";
7107 break;
7108 case MachO::MH_DYLINKER:
7109 outs() << " DYLINKER";
7110 break;
7111 case MachO::MH_BUNDLE:
7112 outs() << " BUNDLE";
7113 break;
7114 case MachO::MH_DSYM:
7115 outs() << " DSYM";
7116 break;
7117 case MachO::MH_KEXT_BUNDLE:
7118 outs() << " KEXTBUNDLE";
7119 break;
7120 default:
7121 outs() << format(" %10u", filetype);
7122 break;
7123 }
7124 outs() << format(" %5u", ncmds);
7125 outs() << format(" %10u", sizeofcmds);
7126 uint32_t f = flags;
7127 if (f & MachO::MH_NOUNDEFS) {
7128 outs() << " NOUNDEFS";
7129 f &= ~MachO::MH_NOUNDEFS;
7130 }
7131 if (f & MachO::MH_INCRLINK) {
7132 outs() << " INCRLINK";
7133 f &= ~MachO::MH_INCRLINK;
7134 }
7135 if (f & MachO::MH_DYLDLINK) {
7136 outs() << " DYLDLINK";
7137 f &= ~MachO::MH_DYLDLINK;
7138 }
7139 if (f & MachO::MH_BINDATLOAD) {
7140 outs() << " BINDATLOAD";
7141 f &= ~MachO::MH_BINDATLOAD;
7142 }
7143 if (f & MachO::MH_PREBOUND) {
7144 outs() << " PREBOUND";
7145 f &= ~MachO::MH_PREBOUND;
7146 }
7147 if (f & MachO::MH_SPLIT_SEGS) {
7148 outs() << " SPLIT_SEGS";
7149 f &= ~MachO::MH_SPLIT_SEGS;
7150 }
7151 if (f & MachO::MH_LAZY_INIT) {
7152 outs() << " LAZY_INIT";
7153 f &= ~MachO::MH_LAZY_INIT;
7154 }
7155 if (f & MachO::MH_TWOLEVEL) {
7156 outs() << " TWOLEVEL";
7157 f &= ~MachO::MH_TWOLEVEL;
7158 }
7159 if (f & MachO::MH_FORCE_FLAT) {
7160 outs() << " FORCE_FLAT";
7161 f &= ~MachO::MH_FORCE_FLAT;
7162 }
7163 if (f & MachO::MH_NOMULTIDEFS) {
7164 outs() << " NOMULTIDEFS";
7165 f &= ~MachO::MH_NOMULTIDEFS;
7166 }
7167 if (f & MachO::MH_NOFIXPREBINDING) {
7168 outs() << " NOFIXPREBINDING";
7169 f &= ~MachO::MH_NOFIXPREBINDING;
7170 }
7171 if (f & MachO::MH_PREBINDABLE) {
7172 outs() << " PREBINDABLE";
7173 f &= ~MachO::MH_PREBINDABLE;
7174 }
7175 if (f & MachO::MH_ALLMODSBOUND) {
7176 outs() << " ALLMODSBOUND";
7177 f &= ~MachO::MH_ALLMODSBOUND;
7178 }
7179 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7180 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7181 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7182 }
7183 if (f & MachO::MH_CANONICAL) {
7184 outs() << " CANONICAL";
7185 f &= ~MachO::MH_CANONICAL;
7186 }
7187 if (f & MachO::MH_WEAK_DEFINES) {
7188 outs() << " WEAK_DEFINES";
7189 f &= ~MachO::MH_WEAK_DEFINES;
7190 }
7191 if (f & MachO::MH_BINDS_TO_WEAK) {
7192 outs() << " BINDS_TO_WEAK";
7193 f &= ~MachO::MH_BINDS_TO_WEAK;
7194 }
7195 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7196 outs() << " ALLOW_STACK_EXECUTION";
7197 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7198 }
7199 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7200 outs() << " DEAD_STRIPPABLE_DYLIB";
7201 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7202 }
7203 if (f & MachO::MH_PIE) {
7204 outs() << " PIE";
7205 f &= ~MachO::MH_PIE;
7206 }
7207 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7208 outs() << " NO_REEXPORTED_DYLIBS";
7209 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7210 }
7211 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7212 outs() << " MH_HAS_TLV_DESCRIPTORS";
7213 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7214 }
7215 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7216 outs() << " MH_NO_HEAP_EXECUTION";
7217 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7218 }
7219 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7220 outs() << " APP_EXTENSION_SAFE";
7221 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7222 }
7223 if (f != 0 || flags == 0)
7224 outs() << format(" 0x%08" PRIx32, f);
7225 } else {
7226 outs() << format(" 0x%08" PRIx32, magic);
7227 outs() << format(" %7d", cputype);
7228 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7229 outs() << format(" 0x%02" PRIx32,
7230 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7231 outs() << format(" %10u", filetype);
7232 outs() << format(" %5u", ncmds);
7233 outs() << format(" %10u", sizeofcmds);
7234 outs() << format(" 0x%08" PRIx32, flags);
7235 }
7236 outs() << "\n";
7237}
7238
Kevin Enderby956366c2014-08-29 22:30:52 +00007239static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7240 StringRef SegName, uint64_t vmaddr,
7241 uint64_t vmsize, uint64_t fileoff,
7242 uint64_t filesize, uint32_t maxprot,
7243 uint32_t initprot, uint32_t nsects,
7244 uint32_t flags, uint32_t object_size,
7245 bool verbose) {
7246 uint64_t expected_cmdsize;
7247 if (cmd == MachO::LC_SEGMENT) {
7248 outs() << " cmd LC_SEGMENT\n";
7249 expected_cmdsize = nsects;
7250 expected_cmdsize *= sizeof(struct MachO::section);
7251 expected_cmdsize += sizeof(struct MachO::segment_command);
7252 } else {
7253 outs() << " cmd LC_SEGMENT_64\n";
7254 expected_cmdsize = nsects;
7255 expected_cmdsize *= sizeof(struct MachO::section_64);
7256 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7257 }
7258 outs() << " cmdsize " << cmdsize;
7259 if (cmdsize != expected_cmdsize)
7260 outs() << " Inconsistent size\n";
7261 else
7262 outs() << "\n";
7263 outs() << " segname " << SegName << "\n";
7264 if (cmd == MachO::LC_SEGMENT_64) {
7265 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7266 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7267 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007268 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7269 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007270 }
7271 outs() << " fileoff " << fileoff;
7272 if (fileoff > object_size)
7273 outs() << " (past end of file)\n";
7274 else
7275 outs() << "\n";
7276 outs() << " filesize " << filesize;
7277 if (fileoff + filesize > object_size)
7278 outs() << " (past end of file)\n";
7279 else
7280 outs() << "\n";
7281 if (verbose) {
7282 if ((maxprot &
7283 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7284 MachO::VM_PROT_EXECUTE)) != 0)
7285 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7286 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007287 outs() << " maxprot ";
7288 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7289 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7290 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007291 }
7292 if ((initprot &
7293 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7294 MachO::VM_PROT_EXECUTE)) != 0)
7295 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7296 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007297 outs() << " initprot ";
7298 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7299 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7300 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007301 }
7302 } else {
7303 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7304 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7305 }
7306 outs() << " nsects " << nsects << "\n";
7307 if (verbose) {
7308 outs() << " flags";
7309 if (flags == 0)
7310 outs() << " (none)\n";
7311 else {
7312 if (flags & MachO::SG_HIGHVM) {
7313 outs() << " HIGHVM";
7314 flags &= ~MachO::SG_HIGHVM;
7315 }
7316 if (flags & MachO::SG_FVMLIB) {
7317 outs() << " FVMLIB";
7318 flags &= ~MachO::SG_FVMLIB;
7319 }
7320 if (flags & MachO::SG_NORELOC) {
7321 outs() << " NORELOC";
7322 flags &= ~MachO::SG_NORELOC;
7323 }
7324 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7325 outs() << " PROTECTED_VERSION_1";
7326 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7327 }
7328 if (flags)
7329 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7330 else
7331 outs() << "\n";
7332 }
7333 } else {
7334 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7335 }
7336}
7337
7338static void PrintSection(const char *sectname, const char *segname,
7339 uint64_t addr, uint64_t size, uint32_t offset,
7340 uint32_t align, uint32_t reloff, uint32_t nreloc,
7341 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7342 uint32_t cmd, const char *sg_segname,
7343 uint32_t filetype, uint32_t object_size,
7344 bool verbose) {
7345 outs() << "Section\n";
7346 outs() << " sectname " << format("%.16s\n", sectname);
7347 outs() << " segname " << format("%.16s", segname);
7348 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7349 outs() << " (does not match segment)\n";
7350 else
7351 outs() << "\n";
7352 if (cmd == MachO::LC_SEGMENT_64) {
7353 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7354 outs() << " size " << format("0x%016" PRIx64, size);
7355 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007356 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7357 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007358 }
7359 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7360 outs() << " (past end of file)\n";
7361 else
7362 outs() << "\n";
7363 outs() << " offset " << offset;
7364 if (offset > object_size)
7365 outs() << " (past end of file)\n";
7366 else
7367 outs() << "\n";
7368 uint32_t align_shifted = 1 << align;
7369 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7370 outs() << " reloff " << reloff;
7371 if (reloff > object_size)
7372 outs() << " (past end of file)\n";
7373 else
7374 outs() << "\n";
7375 outs() << " nreloc " << nreloc;
7376 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7377 outs() << " (past end of file)\n";
7378 else
7379 outs() << "\n";
7380 uint32_t section_type = flags & MachO::SECTION_TYPE;
7381 if (verbose) {
7382 outs() << " type";
7383 if (section_type == MachO::S_REGULAR)
7384 outs() << " S_REGULAR\n";
7385 else if (section_type == MachO::S_ZEROFILL)
7386 outs() << " S_ZEROFILL\n";
7387 else if (section_type == MachO::S_CSTRING_LITERALS)
7388 outs() << " S_CSTRING_LITERALS\n";
7389 else if (section_type == MachO::S_4BYTE_LITERALS)
7390 outs() << " S_4BYTE_LITERALS\n";
7391 else if (section_type == MachO::S_8BYTE_LITERALS)
7392 outs() << " S_8BYTE_LITERALS\n";
7393 else if (section_type == MachO::S_16BYTE_LITERALS)
7394 outs() << " S_16BYTE_LITERALS\n";
7395 else if (section_type == MachO::S_LITERAL_POINTERS)
7396 outs() << " S_LITERAL_POINTERS\n";
7397 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7398 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7399 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7400 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7401 else if (section_type == MachO::S_SYMBOL_STUBS)
7402 outs() << " S_SYMBOL_STUBS\n";
7403 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7404 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7405 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7406 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7407 else if (section_type == MachO::S_COALESCED)
7408 outs() << " S_COALESCED\n";
7409 else if (section_type == MachO::S_INTERPOSING)
7410 outs() << " S_INTERPOSING\n";
7411 else if (section_type == MachO::S_DTRACE_DOF)
7412 outs() << " S_DTRACE_DOF\n";
7413 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7414 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7415 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7416 outs() << " S_THREAD_LOCAL_REGULAR\n";
7417 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7418 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7419 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7420 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7421 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7422 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7423 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7424 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7425 else
7426 outs() << format("0x%08" PRIx32, section_type) << "\n";
7427 outs() << "attributes";
7428 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7429 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7430 outs() << " PURE_INSTRUCTIONS";
7431 if (section_attributes & MachO::S_ATTR_NO_TOC)
7432 outs() << " NO_TOC";
7433 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7434 outs() << " STRIP_STATIC_SYMS";
7435 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7436 outs() << " NO_DEAD_STRIP";
7437 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7438 outs() << " LIVE_SUPPORT";
7439 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7440 outs() << " SELF_MODIFYING_CODE";
7441 if (section_attributes & MachO::S_ATTR_DEBUG)
7442 outs() << " DEBUG";
7443 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7444 outs() << " SOME_INSTRUCTIONS";
7445 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7446 outs() << " EXT_RELOC";
7447 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7448 outs() << " LOC_RELOC";
7449 if (section_attributes == 0)
7450 outs() << " (none)";
7451 outs() << "\n";
7452 } else
7453 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7454 outs() << " reserved1 " << reserved1;
7455 if (section_type == MachO::S_SYMBOL_STUBS ||
7456 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7457 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7458 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7459 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7460 outs() << " (index into indirect symbol table)\n";
7461 else
7462 outs() << "\n";
7463 outs() << " reserved2 " << reserved2;
7464 if (section_type == MachO::S_SYMBOL_STUBS)
7465 outs() << " (size of stubs)\n";
7466 else
7467 outs() << "\n";
7468}
7469
David Majnemer73cc6ff2014-11-13 19:48:56 +00007470static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007471 uint32_t object_size) {
7472 outs() << " cmd LC_SYMTAB\n";
7473 outs() << " cmdsize " << st.cmdsize;
7474 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7475 outs() << " Incorrect size\n";
7476 else
7477 outs() << "\n";
7478 outs() << " symoff " << st.symoff;
7479 if (st.symoff > object_size)
7480 outs() << " (past end of file)\n";
7481 else
7482 outs() << "\n";
7483 outs() << " nsyms " << st.nsyms;
7484 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007485 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007486 big_size = st.nsyms;
7487 big_size *= sizeof(struct MachO::nlist_64);
7488 big_size += st.symoff;
7489 if (big_size > object_size)
7490 outs() << " (past end of file)\n";
7491 else
7492 outs() << "\n";
7493 } else {
7494 big_size = st.nsyms;
7495 big_size *= sizeof(struct MachO::nlist);
7496 big_size += st.symoff;
7497 if (big_size > object_size)
7498 outs() << " (past end of file)\n";
7499 else
7500 outs() << "\n";
7501 }
7502 outs() << " stroff " << st.stroff;
7503 if (st.stroff > object_size)
7504 outs() << " (past end of file)\n";
7505 else
7506 outs() << "\n";
7507 outs() << " strsize " << st.strsize;
7508 big_size = st.stroff;
7509 big_size += st.strsize;
7510 if (big_size > object_size)
7511 outs() << " (past end of file)\n";
7512 else
7513 outs() << "\n";
7514}
7515
7516static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7517 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007518 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007519 outs() << " cmd LC_DYSYMTAB\n";
7520 outs() << " cmdsize " << dyst.cmdsize;
7521 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7522 outs() << " Incorrect size\n";
7523 else
7524 outs() << "\n";
7525 outs() << " ilocalsym " << dyst.ilocalsym;
7526 if (dyst.ilocalsym > nsyms)
7527 outs() << " (greater than the number of symbols)\n";
7528 else
7529 outs() << "\n";
7530 outs() << " nlocalsym " << dyst.nlocalsym;
7531 uint64_t big_size;
7532 big_size = dyst.ilocalsym;
7533 big_size += dyst.nlocalsym;
7534 if (big_size > nsyms)
7535 outs() << " (past the end of the symbol table)\n";
7536 else
7537 outs() << "\n";
7538 outs() << " iextdefsym " << dyst.iextdefsym;
7539 if (dyst.iextdefsym > nsyms)
7540 outs() << " (greater than the number of symbols)\n";
7541 else
7542 outs() << "\n";
7543 outs() << " nextdefsym " << dyst.nextdefsym;
7544 big_size = dyst.iextdefsym;
7545 big_size += dyst.nextdefsym;
7546 if (big_size > nsyms)
7547 outs() << " (past the end of the symbol table)\n";
7548 else
7549 outs() << "\n";
7550 outs() << " iundefsym " << dyst.iundefsym;
7551 if (dyst.iundefsym > nsyms)
7552 outs() << " (greater than the number of symbols)\n";
7553 else
7554 outs() << "\n";
7555 outs() << " nundefsym " << dyst.nundefsym;
7556 big_size = dyst.iundefsym;
7557 big_size += dyst.nundefsym;
7558 if (big_size > nsyms)
7559 outs() << " (past the end of the symbol table)\n";
7560 else
7561 outs() << "\n";
7562 outs() << " tocoff " << dyst.tocoff;
7563 if (dyst.tocoff > object_size)
7564 outs() << " (past end of file)\n";
7565 else
7566 outs() << "\n";
7567 outs() << " ntoc " << dyst.ntoc;
7568 big_size = dyst.ntoc;
7569 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7570 big_size += dyst.tocoff;
7571 if (big_size > object_size)
7572 outs() << " (past end of file)\n";
7573 else
7574 outs() << "\n";
7575 outs() << " modtaboff " << dyst.modtaboff;
7576 if (dyst.modtaboff > object_size)
7577 outs() << " (past end of file)\n";
7578 else
7579 outs() << "\n";
7580 outs() << " nmodtab " << dyst.nmodtab;
7581 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007582 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007583 modtabend = dyst.nmodtab;
7584 modtabend *= sizeof(struct MachO::dylib_module_64);
7585 modtabend += dyst.modtaboff;
7586 } else {
7587 modtabend = dyst.nmodtab;
7588 modtabend *= sizeof(struct MachO::dylib_module);
7589 modtabend += dyst.modtaboff;
7590 }
7591 if (modtabend > object_size)
7592 outs() << " (past end of file)\n";
7593 else
7594 outs() << "\n";
7595 outs() << " extrefsymoff " << dyst.extrefsymoff;
7596 if (dyst.extrefsymoff > object_size)
7597 outs() << " (past end of file)\n";
7598 else
7599 outs() << "\n";
7600 outs() << " nextrefsyms " << dyst.nextrefsyms;
7601 big_size = dyst.nextrefsyms;
7602 big_size *= sizeof(struct MachO::dylib_reference);
7603 big_size += dyst.extrefsymoff;
7604 if (big_size > object_size)
7605 outs() << " (past end of file)\n";
7606 else
7607 outs() << "\n";
7608 outs() << " indirectsymoff " << dyst.indirectsymoff;
7609 if (dyst.indirectsymoff > object_size)
7610 outs() << " (past end of file)\n";
7611 else
7612 outs() << "\n";
7613 outs() << " nindirectsyms " << dyst.nindirectsyms;
7614 big_size = dyst.nindirectsyms;
7615 big_size *= sizeof(uint32_t);
7616 big_size += dyst.indirectsymoff;
7617 if (big_size > object_size)
7618 outs() << " (past end of file)\n";
7619 else
7620 outs() << "\n";
7621 outs() << " extreloff " << dyst.extreloff;
7622 if (dyst.extreloff > object_size)
7623 outs() << " (past end of file)\n";
7624 else
7625 outs() << "\n";
7626 outs() << " nextrel " << dyst.nextrel;
7627 big_size = dyst.nextrel;
7628 big_size *= sizeof(struct MachO::relocation_info);
7629 big_size += dyst.extreloff;
7630 if (big_size > object_size)
7631 outs() << " (past end of file)\n";
7632 else
7633 outs() << "\n";
7634 outs() << " locreloff " << dyst.locreloff;
7635 if (dyst.locreloff > object_size)
7636 outs() << " (past end of file)\n";
7637 else
7638 outs() << "\n";
7639 outs() << " nlocrel " << dyst.nlocrel;
7640 big_size = dyst.nlocrel;
7641 big_size *= sizeof(struct MachO::relocation_info);
7642 big_size += dyst.locreloff;
7643 if (big_size > object_size)
7644 outs() << " (past end of file)\n";
7645 else
7646 outs() << "\n";
7647}
7648
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007649static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7650 uint32_t object_size) {
7651 if (dc.cmd == MachO::LC_DYLD_INFO)
7652 outs() << " cmd LC_DYLD_INFO\n";
7653 else
7654 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7655 outs() << " cmdsize " << dc.cmdsize;
7656 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7657 outs() << " Incorrect size\n";
7658 else
7659 outs() << "\n";
7660 outs() << " rebase_off " << dc.rebase_off;
7661 if (dc.rebase_off > object_size)
7662 outs() << " (past end of file)\n";
7663 else
7664 outs() << "\n";
7665 outs() << " rebase_size " << dc.rebase_size;
7666 uint64_t big_size;
7667 big_size = dc.rebase_off;
7668 big_size += dc.rebase_size;
7669 if (big_size > object_size)
7670 outs() << " (past end of file)\n";
7671 else
7672 outs() << "\n";
7673 outs() << " bind_off " << dc.bind_off;
7674 if (dc.bind_off > object_size)
7675 outs() << " (past end of file)\n";
7676 else
7677 outs() << "\n";
7678 outs() << " bind_size " << dc.bind_size;
7679 big_size = dc.bind_off;
7680 big_size += dc.bind_size;
7681 if (big_size > object_size)
7682 outs() << " (past end of file)\n";
7683 else
7684 outs() << "\n";
7685 outs() << " weak_bind_off " << dc.weak_bind_off;
7686 if (dc.weak_bind_off > object_size)
7687 outs() << " (past end of file)\n";
7688 else
7689 outs() << "\n";
7690 outs() << " weak_bind_size " << dc.weak_bind_size;
7691 big_size = dc.weak_bind_off;
7692 big_size += dc.weak_bind_size;
7693 if (big_size > object_size)
7694 outs() << " (past end of file)\n";
7695 else
7696 outs() << "\n";
7697 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7698 if (dc.lazy_bind_off > object_size)
7699 outs() << " (past end of file)\n";
7700 else
7701 outs() << "\n";
7702 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7703 big_size = dc.lazy_bind_off;
7704 big_size += dc.lazy_bind_size;
7705 if (big_size > object_size)
7706 outs() << " (past end of file)\n";
7707 else
7708 outs() << "\n";
7709 outs() << " export_off " << dc.export_off;
7710 if (dc.export_off > object_size)
7711 outs() << " (past end of file)\n";
7712 else
7713 outs() << "\n";
7714 outs() << " export_size " << dc.export_size;
7715 big_size = dc.export_off;
7716 big_size += dc.export_size;
7717 if (big_size > object_size)
7718 outs() << " (past end of file)\n";
7719 else
7720 outs() << "\n";
7721}
7722
7723static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7724 const char *Ptr) {
7725 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7726 outs() << " cmd LC_ID_DYLINKER\n";
7727 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7728 outs() << " cmd LC_LOAD_DYLINKER\n";
7729 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7730 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7731 else
7732 outs() << " cmd ?(" << dyld.cmd << ")\n";
7733 outs() << " cmdsize " << dyld.cmdsize;
7734 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7735 outs() << " Incorrect size\n";
7736 else
7737 outs() << "\n";
7738 if (dyld.name >= dyld.cmdsize)
7739 outs() << " name ?(bad offset " << dyld.name << ")\n";
7740 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007741 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007742 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7743 }
7744}
7745
7746static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7747 outs() << " cmd LC_UUID\n";
7748 outs() << " cmdsize " << uuid.cmdsize;
7749 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7750 outs() << " Incorrect size\n";
7751 else
7752 outs() << "\n";
7753 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007754 for (int i = 0; i < 16; ++i) {
7755 outs() << format("%02" PRIX32, uuid.uuid[i]);
7756 if (i == 3 || i == 5 || i == 7 || i == 9)
7757 outs() << "-";
7758 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007759 outs() << "\n";
7760}
7761
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007762static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007763 outs() << " cmd LC_RPATH\n";
7764 outs() << " cmdsize " << rpath.cmdsize;
7765 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7766 outs() << " Incorrect size\n";
7767 else
7768 outs() << "\n";
7769 if (rpath.path >= rpath.cmdsize)
7770 outs() << " path ?(bad offset " << rpath.path << ")\n";
7771 else {
7772 const char *P = (const char *)(Ptr) + rpath.path;
7773 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7774 }
7775}
7776
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007777static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007778 StringRef LoadCmdName;
7779 switch (vd.cmd) {
7780 case MachO::LC_VERSION_MIN_MACOSX:
7781 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7782 break;
7783 case MachO::LC_VERSION_MIN_IPHONEOS:
7784 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7785 break;
7786 case MachO::LC_VERSION_MIN_TVOS:
7787 LoadCmdName = "LC_VERSION_MIN_TVOS";
7788 break;
7789 case MachO::LC_VERSION_MIN_WATCHOS:
7790 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7791 break;
7792 default:
7793 llvm_unreachable("Unknown version min load command");
7794 }
7795
7796 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007797 outs() << " cmdsize " << vd.cmdsize;
7798 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7799 outs() << " Incorrect size\n";
7800 else
7801 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007802 outs() << " version "
7803 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7804 << MachOObjectFile::getVersionMinMinor(vd, false);
7805 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7806 if (Update != 0)
7807 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007808 outs() << "\n";
7809 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007810 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007811 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007812 outs() << " sdk "
7813 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7814 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007815 }
Davide Italiano56baef32015-08-26 12:26:11 +00007816 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7817 if (Update != 0)
7818 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007819 outs() << "\n";
7820}
7821
7822static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7823 outs() << " cmd LC_SOURCE_VERSION\n";
7824 outs() << " cmdsize " << sd.cmdsize;
7825 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7826 outs() << " Incorrect size\n";
7827 else
7828 outs() << "\n";
7829 uint64_t a = (sd.version >> 40) & 0xffffff;
7830 uint64_t b = (sd.version >> 30) & 0x3ff;
7831 uint64_t c = (sd.version >> 20) & 0x3ff;
7832 uint64_t d = (sd.version >> 10) & 0x3ff;
7833 uint64_t e = sd.version & 0x3ff;
7834 outs() << " version " << a << "." << b;
7835 if (e != 0)
7836 outs() << "." << c << "." << d << "." << e;
7837 else if (d != 0)
7838 outs() << "." << c << "." << d;
7839 else if (c != 0)
7840 outs() << "." << c;
7841 outs() << "\n";
7842}
7843
7844static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7845 outs() << " cmd LC_MAIN\n";
7846 outs() << " cmdsize " << ep.cmdsize;
7847 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7848 outs() << " Incorrect size\n";
7849 else
7850 outs() << "\n";
7851 outs() << " entryoff " << ep.entryoff << "\n";
7852 outs() << " stacksize " << ep.stacksize << "\n";
7853}
7854
Kevin Enderby0804f4672014-12-16 23:25:52 +00007855static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7856 uint32_t object_size) {
7857 outs() << " cmd LC_ENCRYPTION_INFO\n";
7858 outs() << " cmdsize " << ec.cmdsize;
7859 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7860 outs() << " Incorrect size\n";
7861 else
7862 outs() << "\n";
7863 outs() << " cryptoff " << ec.cryptoff;
7864 if (ec.cryptoff > object_size)
7865 outs() << " (past end of file)\n";
7866 else
7867 outs() << "\n";
7868 outs() << " cryptsize " << ec.cryptsize;
7869 if (ec.cryptsize > object_size)
7870 outs() << " (past end of file)\n";
7871 else
7872 outs() << "\n";
7873 outs() << " cryptid " << ec.cryptid << "\n";
7874}
7875
Kevin Enderby57538292014-12-17 01:01:30 +00007876static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007877 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007878 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7879 outs() << " cmdsize " << ec.cmdsize;
7880 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7881 outs() << " Incorrect size\n";
7882 else
7883 outs() << "\n";
7884 outs() << " cryptoff " << ec.cryptoff;
7885 if (ec.cryptoff > object_size)
7886 outs() << " (past end of file)\n";
7887 else
7888 outs() << "\n";
7889 outs() << " cryptsize " << ec.cryptsize;
7890 if (ec.cryptsize > object_size)
7891 outs() << " (past end of file)\n";
7892 else
7893 outs() << "\n";
7894 outs() << " cryptid " << ec.cryptid << "\n";
7895 outs() << " pad " << ec.pad << "\n";
7896}
7897
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007898static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7899 const char *Ptr) {
7900 outs() << " cmd LC_LINKER_OPTION\n";
7901 outs() << " cmdsize " << lo.cmdsize;
7902 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7903 outs() << " Incorrect size\n";
7904 else
7905 outs() << "\n";
7906 outs() << " count " << lo.count << "\n";
7907 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7908 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7909 uint32_t i = 0;
7910 while (left > 0) {
7911 while (*string == '\0' && left > 0) {
7912 string++;
7913 left--;
7914 }
7915 if (left > 0) {
7916 i++;
7917 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007918 uint32_t NullPos = StringRef(string, left).find('\0');
7919 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007920 string += len;
7921 left -= len;
7922 }
7923 }
7924 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007925 outs() << " count " << lo.count << " does not match number of strings "
7926 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007927}
7928
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007929static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7930 const char *Ptr) {
7931 outs() << " cmd LC_SUB_FRAMEWORK\n";
7932 outs() << " cmdsize " << sub.cmdsize;
7933 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7934 outs() << " Incorrect size\n";
7935 else
7936 outs() << "\n";
7937 if (sub.umbrella < sub.cmdsize) {
7938 const char *P = Ptr + sub.umbrella;
7939 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7940 } else {
7941 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7942 }
7943}
7944
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00007945static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7946 const char *Ptr) {
7947 outs() << " cmd LC_SUB_UMBRELLA\n";
7948 outs() << " cmdsize " << sub.cmdsize;
7949 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7950 outs() << " Incorrect size\n";
7951 else
7952 outs() << "\n";
7953 if (sub.sub_umbrella < sub.cmdsize) {
7954 const char *P = Ptr + sub.sub_umbrella;
7955 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7956 } else {
7957 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7958 }
7959}
7960
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007961static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007962 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007963 outs() << " cmd LC_SUB_LIBRARY\n";
7964 outs() << " cmdsize " << sub.cmdsize;
7965 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7966 outs() << " Incorrect size\n";
7967 else
7968 outs() << "\n";
7969 if (sub.sub_library < sub.cmdsize) {
7970 const char *P = Ptr + sub.sub_library;
7971 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7972 } else {
7973 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7974 }
7975}
7976
Kevin Enderby186eac32014-12-19 21:06:24 +00007977static void PrintSubClientCommand(MachO::sub_client_command sub,
7978 const char *Ptr) {
7979 outs() << " cmd LC_SUB_CLIENT\n";
7980 outs() << " cmdsize " << sub.cmdsize;
7981 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7982 outs() << " Incorrect size\n";
7983 else
7984 outs() << "\n";
7985 if (sub.client < sub.cmdsize) {
7986 const char *P = Ptr + sub.client;
7987 outs() << " client " << P << " (offset " << sub.client << ")\n";
7988 } else {
7989 outs() << " client ?(bad offset " << sub.client << ")\n";
7990 }
7991}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007992
Kevin Enderby52e4ce42014-12-19 22:25:22 +00007993static void PrintRoutinesCommand(MachO::routines_command r) {
7994 outs() << " cmd LC_ROUTINES\n";
7995 outs() << " cmdsize " << r.cmdsize;
7996 if (r.cmdsize != sizeof(struct MachO::routines_command))
7997 outs() << " Incorrect size\n";
7998 else
7999 outs() << "\n";
8000 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8001 outs() << " init_module " << r.init_module << "\n";
8002 outs() << " reserved1 " << r.reserved1 << "\n";
8003 outs() << " reserved2 " << r.reserved2 << "\n";
8004 outs() << " reserved3 " << r.reserved3 << "\n";
8005 outs() << " reserved4 " << r.reserved4 << "\n";
8006 outs() << " reserved5 " << r.reserved5 << "\n";
8007 outs() << " reserved6 " << r.reserved6 << "\n";
8008}
8009
8010static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8011 outs() << " cmd LC_ROUTINES_64\n";
8012 outs() << " cmdsize " << r.cmdsize;
8013 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8014 outs() << " Incorrect size\n";
8015 else
8016 outs() << "\n";
8017 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8018 outs() << " init_module " << r.init_module << "\n";
8019 outs() << " reserved1 " << r.reserved1 << "\n";
8020 outs() << " reserved2 " << r.reserved2 << "\n";
8021 outs() << " reserved3 " << r.reserved3 << "\n";
8022 outs() << " reserved4 " << r.reserved4 << "\n";
8023 outs() << " reserved5 " << r.reserved5 << "\n";
8024 outs() << " reserved6 " << r.reserved6 << "\n";
8025}
8026
Kevin Enderby48ef5342014-12-23 22:56:39 +00008027static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8028 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8029 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8030 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8031 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8032 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8033 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8034 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8035 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8036 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8037 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8038 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8039 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8040 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8041 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8042 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8043 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8044 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8045 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8046 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8047 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8048 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8049}
8050
Kevin Enderby227df342014-12-23 23:43:59 +00008051static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008052 uint32_t f;
8053 outs() << "\t mmst_reg ";
8054 for (f = 0; f < 10; f++)
8055 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8056 outs() << "\n";
8057 outs() << "\t mmst_rsrv ";
8058 for (f = 0; f < 6; f++)
8059 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8060 outs() << "\n";
8061}
8062
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008063static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008064 uint32_t f;
8065 outs() << "\t xmm_reg ";
8066 for (f = 0; f < 16; f++)
8067 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8068 outs() << "\n";
8069}
8070
8071static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8072 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8073 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8074 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8075 outs() << " denorm " << fpu.fpu_fcw.denorm;
8076 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8077 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8078 outs() << " undfl " << fpu.fpu_fcw.undfl;
8079 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8080 outs() << "\t\t pc ";
8081 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8082 outs() << "FP_PREC_24B ";
8083 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8084 outs() << "FP_PREC_53B ";
8085 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8086 outs() << "FP_PREC_64B ";
8087 else
8088 outs() << fpu.fpu_fcw.pc << " ";
8089 outs() << "rc ";
8090 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8091 outs() << "FP_RND_NEAR ";
8092 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8093 outs() << "FP_RND_DOWN ";
8094 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8095 outs() << "FP_RND_UP ";
8096 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008097 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008098 outs() << "\n";
8099 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8100 outs() << " denorm " << fpu.fpu_fsw.denorm;
8101 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8102 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8103 outs() << " undfl " << fpu.fpu_fsw.undfl;
8104 outs() << " precis " << fpu.fpu_fsw.precis;
8105 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8106 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8107 outs() << " c0 " << fpu.fpu_fsw.c0;
8108 outs() << " c1 " << fpu.fpu_fsw.c1;
8109 outs() << " c2 " << fpu.fpu_fsw.c2;
8110 outs() << " tos " << fpu.fpu_fsw.tos;
8111 outs() << " c3 " << fpu.fpu_fsw.c3;
8112 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8113 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8114 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8115 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8116 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8117 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8118 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8119 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8120 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8121 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8122 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8123 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8124 outs() << "\n";
8125 outs() << "\t fpu_stmm0:\n";
8126 Print_mmst_reg(fpu.fpu_stmm0);
8127 outs() << "\t fpu_stmm1:\n";
8128 Print_mmst_reg(fpu.fpu_stmm1);
8129 outs() << "\t fpu_stmm2:\n";
8130 Print_mmst_reg(fpu.fpu_stmm2);
8131 outs() << "\t fpu_stmm3:\n";
8132 Print_mmst_reg(fpu.fpu_stmm3);
8133 outs() << "\t fpu_stmm4:\n";
8134 Print_mmst_reg(fpu.fpu_stmm4);
8135 outs() << "\t fpu_stmm5:\n";
8136 Print_mmst_reg(fpu.fpu_stmm5);
8137 outs() << "\t fpu_stmm6:\n";
8138 Print_mmst_reg(fpu.fpu_stmm6);
8139 outs() << "\t fpu_stmm7:\n";
8140 Print_mmst_reg(fpu.fpu_stmm7);
8141 outs() << "\t fpu_xmm0:\n";
8142 Print_xmm_reg(fpu.fpu_xmm0);
8143 outs() << "\t fpu_xmm1:\n";
8144 Print_xmm_reg(fpu.fpu_xmm1);
8145 outs() << "\t fpu_xmm2:\n";
8146 Print_xmm_reg(fpu.fpu_xmm2);
8147 outs() << "\t fpu_xmm3:\n";
8148 Print_xmm_reg(fpu.fpu_xmm3);
8149 outs() << "\t fpu_xmm4:\n";
8150 Print_xmm_reg(fpu.fpu_xmm4);
8151 outs() << "\t fpu_xmm5:\n";
8152 Print_xmm_reg(fpu.fpu_xmm5);
8153 outs() << "\t fpu_xmm6:\n";
8154 Print_xmm_reg(fpu.fpu_xmm6);
8155 outs() << "\t fpu_xmm7:\n";
8156 Print_xmm_reg(fpu.fpu_xmm7);
8157 outs() << "\t fpu_xmm8:\n";
8158 Print_xmm_reg(fpu.fpu_xmm8);
8159 outs() << "\t fpu_xmm9:\n";
8160 Print_xmm_reg(fpu.fpu_xmm9);
8161 outs() << "\t fpu_xmm10:\n";
8162 Print_xmm_reg(fpu.fpu_xmm10);
8163 outs() << "\t fpu_xmm11:\n";
8164 Print_xmm_reg(fpu.fpu_xmm11);
8165 outs() << "\t fpu_xmm12:\n";
8166 Print_xmm_reg(fpu.fpu_xmm12);
8167 outs() << "\t fpu_xmm13:\n";
8168 Print_xmm_reg(fpu.fpu_xmm13);
8169 outs() << "\t fpu_xmm14:\n";
8170 Print_xmm_reg(fpu.fpu_xmm14);
8171 outs() << "\t fpu_xmm15:\n";
8172 Print_xmm_reg(fpu.fpu_xmm15);
8173 outs() << "\t fpu_rsrv4:\n";
8174 for (uint32_t f = 0; f < 6; f++) {
8175 outs() << "\t ";
8176 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008177 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008178 outs() << "\n";
8179 }
8180 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8181 outs() << "\n";
8182}
8183
8184static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8185 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8186 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8187 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8188}
8189
8190static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8191 bool isLittleEndian, uint32_t cputype) {
8192 if (t.cmd == MachO::LC_THREAD)
8193 outs() << " cmd LC_THREAD\n";
8194 else if (t.cmd == MachO::LC_UNIXTHREAD)
8195 outs() << " cmd LC_UNIXTHREAD\n";
8196 else
8197 outs() << " cmd " << t.cmd << " (unknown)\n";
8198 outs() << " cmdsize " << t.cmdsize;
8199 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8200 outs() << " Incorrect size\n";
8201 else
8202 outs() << "\n";
8203
8204 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8205 const char *end = Ptr + t.cmdsize;
8206 uint32_t flavor, count, left;
8207 if (cputype == MachO::CPU_TYPE_X86_64) {
8208 while (begin < end) {
8209 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8210 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8211 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008212 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008213 flavor = 0;
8214 begin = end;
8215 }
8216 if (isLittleEndian != sys::IsLittleEndianHost)
8217 sys::swapByteOrder(flavor);
8218 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8219 memcpy((char *)&count, begin, sizeof(uint32_t));
8220 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008221 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008222 count = 0;
8223 begin = end;
8224 }
8225 if (isLittleEndian != sys::IsLittleEndianHost)
8226 sys::swapByteOrder(count);
8227 if (flavor == MachO::x86_THREAD_STATE64) {
8228 outs() << " flavor x86_THREAD_STATE64\n";
8229 if (count == MachO::x86_THREAD_STATE64_COUNT)
8230 outs() << " count x86_THREAD_STATE64_COUNT\n";
8231 else
8232 outs() << " count " << count
8233 << " (not x86_THREAD_STATE64_COUNT)\n";
8234 MachO::x86_thread_state64_t cpu64;
8235 left = end - begin;
8236 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8237 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8238 begin += sizeof(MachO::x86_thread_state64_t);
8239 } else {
8240 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8241 memcpy(&cpu64, begin, left);
8242 begin += left;
8243 }
8244 if (isLittleEndian != sys::IsLittleEndianHost)
8245 swapStruct(cpu64);
8246 Print_x86_thread_state64_t(cpu64);
8247 } else if (flavor == MachO::x86_THREAD_STATE) {
8248 outs() << " flavor x86_THREAD_STATE\n";
8249 if (count == MachO::x86_THREAD_STATE_COUNT)
8250 outs() << " count x86_THREAD_STATE_COUNT\n";
8251 else
8252 outs() << " count " << count
8253 << " (not x86_THREAD_STATE_COUNT)\n";
8254 struct MachO::x86_thread_state_t ts;
8255 left = end - begin;
8256 if (left >= sizeof(MachO::x86_thread_state_t)) {
8257 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8258 begin += sizeof(MachO::x86_thread_state_t);
8259 } else {
8260 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8261 memcpy(&ts, begin, left);
8262 begin += left;
8263 }
8264 if (isLittleEndian != sys::IsLittleEndianHost)
8265 swapStruct(ts);
8266 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8267 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8268 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8269 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8270 else
8271 outs() << "tsh.count " << ts.tsh.count
8272 << " (not x86_THREAD_STATE64_COUNT\n";
8273 Print_x86_thread_state64_t(ts.uts.ts64);
8274 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008275 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8276 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008277 }
8278 } else if (flavor == MachO::x86_FLOAT_STATE) {
8279 outs() << " flavor x86_FLOAT_STATE\n";
8280 if (count == MachO::x86_FLOAT_STATE_COUNT)
8281 outs() << " count x86_FLOAT_STATE_COUNT\n";
8282 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008283 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008284 struct MachO::x86_float_state_t fs;
8285 left = end - begin;
8286 if (left >= sizeof(MachO::x86_float_state_t)) {
8287 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8288 begin += sizeof(MachO::x86_float_state_t);
8289 } else {
8290 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8291 memcpy(&fs, begin, left);
8292 begin += left;
8293 }
8294 if (isLittleEndian != sys::IsLittleEndianHost)
8295 swapStruct(fs);
8296 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8297 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008298 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008299 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8300 else
8301 outs() << "fsh.count " << fs.fsh.count
8302 << " (not x86_FLOAT_STATE64_COUNT\n";
8303 Print_x86_float_state_t(fs.ufs.fs64);
8304 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008305 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8306 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008307 }
8308 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8309 outs() << " flavor x86_EXCEPTION_STATE\n";
8310 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8311 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8312 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008313 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008314 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8315 struct MachO::x86_exception_state_t es;
8316 left = end - begin;
8317 if (left >= sizeof(MachO::x86_exception_state_t)) {
8318 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8319 begin += sizeof(MachO::x86_exception_state_t);
8320 } else {
8321 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8322 memcpy(&es, begin, left);
8323 begin += left;
8324 }
8325 if (isLittleEndian != sys::IsLittleEndianHost)
8326 swapStruct(es);
8327 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8328 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008329 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008330 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8331 else
8332 outs() << "\t esh.count " << es.esh.count
8333 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8334 Print_x86_exception_state_t(es.ues.es64);
8335 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008336 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8337 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008338 }
8339 } else {
8340 outs() << " flavor " << flavor << " (unknown)\n";
8341 outs() << " count " << count << "\n";
8342 outs() << " state (unknown)\n";
8343 begin += count * sizeof(uint32_t);
8344 }
8345 }
8346 } else {
8347 while (begin < end) {
8348 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8349 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8350 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008351 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008352 flavor = 0;
8353 begin = end;
8354 }
8355 if (isLittleEndian != sys::IsLittleEndianHost)
8356 sys::swapByteOrder(flavor);
8357 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8358 memcpy((char *)&count, begin, sizeof(uint32_t));
8359 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008360 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008361 count = 0;
8362 begin = end;
8363 }
8364 if (isLittleEndian != sys::IsLittleEndianHost)
8365 sys::swapByteOrder(count);
8366 outs() << " flavor " << flavor << "\n";
8367 outs() << " count " << count << "\n";
8368 outs() << " state (Unknown cputype/cpusubtype)\n";
8369 begin += count * sizeof(uint32_t);
8370 }
8371 }
8372}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008373
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008374static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8375 if (dl.cmd == MachO::LC_ID_DYLIB)
8376 outs() << " cmd LC_ID_DYLIB\n";
8377 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8378 outs() << " cmd LC_LOAD_DYLIB\n";
8379 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8380 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8381 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8382 outs() << " cmd LC_REEXPORT_DYLIB\n";
8383 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8384 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8385 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8386 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8387 else
8388 outs() << " cmd " << dl.cmd << " (unknown)\n";
8389 outs() << " cmdsize " << dl.cmdsize;
8390 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8391 outs() << " Incorrect size\n";
8392 else
8393 outs() << "\n";
8394 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008395 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008396 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8397 } else {
8398 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8399 }
8400 outs() << " time stamp " << dl.dylib.timestamp << " ";
8401 time_t t = dl.dylib.timestamp;
8402 outs() << ctime(&t);
8403 outs() << " current version ";
8404 if (dl.dylib.current_version == 0xffffffff)
8405 outs() << "n/a\n";
8406 else
8407 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8408 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8409 << (dl.dylib.current_version & 0xff) << "\n";
8410 outs() << "compatibility version ";
8411 if (dl.dylib.compatibility_version == 0xffffffff)
8412 outs() << "n/a\n";
8413 else
8414 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8415 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8416 << (dl.dylib.compatibility_version & 0xff) << "\n";
8417}
8418
8419static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8420 uint32_t object_size) {
8421 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00008422 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008423 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8424 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8425 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8426 outs() << " cmd LC_FUNCTION_STARTS\n";
8427 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8428 outs() << " cmd LC_DATA_IN_CODE\n";
8429 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8430 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8431 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8432 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8433 else
8434 outs() << " cmd " << ld.cmd << " (?)\n";
8435 outs() << " cmdsize " << ld.cmdsize;
8436 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8437 outs() << " Incorrect size\n";
8438 else
8439 outs() << "\n";
8440 outs() << " dataoff " << ld.dataoff;
8441 if (ld.dataoff > object_size)
8442 outs() << " (past end of file)\n";
8443 else
8444 outs() << "\n";
8445 outs() << " datasize " << ld.datasize;
8446 uint64_t big_size = ld.dataoff;
8447 big_size += ld.datasize;
8448 if (big_size > object_size)
8449 outs() << " (past end of file)\n";
8450 else
8451 outs() << "\n";
8452}
8453
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008454static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8455 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008456 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008457 unsigned Index = 0;
8458 for (const auto &Command : Obj->load_commands()) {
8459 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008460 if (Command.C.cmd == MachO::LC_SEGMENT) {
8461 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8462 const char *sg_segname = SLC.segname;
8463 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8464 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8465 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8466 verbose);
8467 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008468 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008469 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8470 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8471 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8472 }
8473 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8474 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8475 const char *sg_segname = SLC_64.segname;
8476 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8477 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8478 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8479 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8480 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8481 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8482 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8483 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8484 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8485 sg_segname, filetype, Buf.size(), verbose);
8486 }
8487 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8488 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008489 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008490 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8491 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8492 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008493 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8494 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008495 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8496 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8497 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8498 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8499 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8500 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8501 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8502 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8503 PrintDyldLoadCommand(Dyld, Command.Ptr);
8504 } else if (Command.C.cmd == MachO::LC_UUID) {
8505 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8506 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008507 } else if (Command.C.cmd == MachO::LC_RPATH) {
8508 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8509 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008510 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008511 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8512 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8513 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008514 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8515 PrintVersionMinLoadCommand(Vd);
8516 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8517 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8518 PrintSourceVersionCommand(Sd);
8519 } else if (Command.C.cmd == MachO::LC_MAIN) {
8520 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8521 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008522 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008523 MachO::encryption_info_command Ei =
8524 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008525 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008526 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008527 MachO::encryption_info_command_64 Ei =
8528 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008529 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008530 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008531 MachO::linker_option_command Lo =
8532 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008533 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008534 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8535 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8536 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008537 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8538 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8539 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008540 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8541 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8542 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008543 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8544 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8545 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008546 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8547 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8548 PrintRoutinesCommand(Rc);
8549 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8550 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8551 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008552 } else if (Command.C.cmd == MachO::LC_THREAD ||
8553 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8554 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8555 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008556 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8557 Command.C.cmd == MachO::LC_ID_DYLIB ||
8558 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8559 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8560 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8561 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008562 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8563 PrintDylibCommand(Dl, Command.Ptr);
8564 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8565 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8566 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8567 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8568 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8569 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8570 MachO::linkedit_data_command Ld =
8571 Obj->getLinkeditDataLoadCommand(Command);
8572 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008573 } else {
8574 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8575 << ")\n";
8576 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8577 // TODO: get and print the raw bytes of the load command.
8578 }
8579 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008580 }
8581}
8582
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008583static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008584 if (Obj->is64Bit()) {
8585 MachO::mach_header_64 H_64;
8586 H_64 = Obj->getHeader64();
8587 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8588 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8589 } else {
8590 MachO::mach_header H;
8591 H = Obj->getHeader();
8592 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8593 H.sizeofcmds, H.flags, verbose);
8594 }
8595}
8596
8597void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8598 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008599 PrintMachHeader(file, !NonVerbose);
8600}
8601
8602void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
8603 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008604 uint32_t filetype = 0;
8605 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008606 if (file->is64Bit()) {
8607 MachO::mach_header_64 H_64;
8608 H_64 = file->getHeader64();
8609 filetype = H_64.filetype;
8610 cputype = H_64.cputype;
8611 } else {
8612 MachO::mach_header H;
8613 H = file->getHeader();
8614 filetype = H.filetype;
8615 cputype = H.cputype;
8616 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008617 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008618}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008619
8620//===----------------------------------------------------------------------===//
8621// export trie dumping
8622//===----------------------------------------------------------------------===//
8623
8624void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008625 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8626 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008627 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8628 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8629 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8630 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8631 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8632 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8633 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8634 if (ReExport)
8635 outs() << "[re-export] ";
8636 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008637 outs() << format("0x%08llX ",
8638 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008639 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008640 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008641 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008642 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008643 if (WeakDef) {
8644 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008645 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008646 }
8647 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008648 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008649 outs() << ", ";
8650 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008651 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008652 }
8653 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008654 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008655 outs() << ", ";
8656 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008657 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008658 }
8659 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008660 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008661 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008662 outs() << format("resolver=0x%08llX", Entry.other());
8663 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008664 }
8665 outs() << "]";
8666 }
8667 if (ReExport) {
8668 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008669 int Ordinal = Entry.other() - 1;
8670 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8671 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008672 outs() << " (from " << DylibName << ")";
8673 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008674 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008675 }
8676 outs() << "\n";
8677 }
8678}
Nick Kledzikac431442014-09-12 21:34:15 +00008679
Nick Kledzikac431442014-09-12 21:34:15 +00008680//===----------------------------------------------------------------------===//
8681// rebase table dumping
8682//===----------------------------------------------------------------------===//
8683
8684namespace {
8685class SegInfo {
8686public:
8687 SegInfo(const object::MachOObjectFile *Obj);
8688
8689 StringRef segmentName(uint32_t SegIndex);
8690 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8691 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008692 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008693
8694private:
8695 struct SectionInfo {
8696 uint64_t Address;
8697 uint64_t Size;
8698 StringRef SectionName;
8699 StringRef SegmentName;
8700 uint64_t OffsetInSegment;
8701 uint64_t SegmentStartAddress;
8702 uint32_t SegmentIndex;
8703 };
8704 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8705 SmallVector<SectionInfo, 32> Sections;
8706};
8707}
8708
8709SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8710 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008711 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008712 StringRef CurSegName;
8713 uint64_t CurSegAddress;
8714 for (const SectionRef &Section : Obj->sections()) {
8715 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008716 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008717 Info.Address = Section.getAddress();
8718 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008719 Info.SegmentName =
8720 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8721 if (!Info.SegmentName.equals(CurSegName)) {
8722 ++CurSegIndex;
8723 CurSegName = Info.SegmentName;
8724 CurSegAddress = Info.Address;
8725 }
8726 Info.SegmentIndex = CurSegIndex - 1;
8727 Info.OffsetInSegment = Info.Address - CurSegAddress;
8728 Info.SegmentStartAddress = CurSegAddress;
8729 Sections.push_back(Info);
8730 }
8731}
8732
8733StringRef SegInfo::segmentName(uint32_t SegIndex) {
8734 for (const SectionInfo &SI : Sections) {
8735 if (SI.SegmentIndex == SegIndex)
8736 return SI.SegmentName;
8737 }
8738 llvm_unreachable("invalid segIndex");
8739}
8740
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008741bool SegInfo::isValidSegIndexAndOffset(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 true;
8751 }
8752 return false;
8753}
8754
Nick Kledzikac431442014-09-12 21:34:15 +00008755const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8756 uint64_t OffsetInSeg) {
8757 for (const SectionInfo &SI : Sections) {
8758 if (SI.SegmentIndex != SegIndex)
8759 continue;
8760 if (SI.OffsetInSegment > OffsetInSeg)
8761 continue;
8762 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8763 continue;
8764 return SI;
8765 }
8766 llvm_unreachable("segIndex and offset not in any section");
8767}
8768
8769StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8770 return findSection(SegIndex, OffsetInSeg).SectionName;
8771}
8772
8773uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8774 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8775 return SI.SegmentStartAddress + OffsetInSeg;
8776}
8777
8778void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8779 // Build table of sections so names can used in final output.
8780 SegInfo sectionTable(Obj);
8781
8782 outs() << "segment section address type\n";
8783 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8784 uint32_t SegIndex = Entry.segmentIndex();
8785 uint64_t OffsetInSeg = Entry.segmentOffset();
8786 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8787 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8788 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8789
8790 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008791 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8792 SegmentName.str().c_str(), SectionName.str().c_str(),
8793 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008794 }
8795}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008796
8797static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8798 StringRef DylibName;
8799 switch (Ordinal) {
8800 case MachO::BIND_SPECIAL_DYLIB_SELF:
8801 return "this-image";
8802 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8803 return "main-executable";
8804 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8805 return "flat-namespace";
8806 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008807 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008808 std::error_code EC =
8809 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008810 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008811 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008812 return DylibName;
8813 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008814 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008815 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008816}
8817
8818//===----------------------------------------------------------------------===//
8819// bind table dumping
8820//===----------------------------------------------------------------------===//
8821
8822void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8823 // Build table of sections so names can used in final output.
8824 SegInfo sectionTable(Obj);
8825
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008826 outs() << "segment section address type "
8827 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008828 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8829 uint32_t SegIndex = Entry.segmentIndex();
8830 uint64_t OffsetInSeg = Entry.segmentOffset();
8831 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8832 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8833 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8834
8835 // Table lines look like:
8836 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008837 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008838 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008839 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008840 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008841 << left_justify(SectionName, 18) << " "
8842 << format_hex(Address, 10, true) << " "
8843 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008844 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008845 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008846 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008847 }
8848}
8849
8850//===----------------------------------------------------------------------===//
8851// lazy bind table dumping
8852//===----------------------------------------------------------------------===//
8853
8854void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8855 // Build table of sections so names can used in final output.
8856 SegInfo sectionTable(Obj);
8857
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008858 outs() << "segment section address "
8859 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008860 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8861 uint32_t SegIndex = Entry.segmentIndex();
8862 uint64_t OffsetInSeg = Entry.segmentOffset();
8863 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8864 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8865 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8866
8867 // Table lines look like:
8868 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008869 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008870 << left_justify(SectionName, 18) << " "
8871 << format_hex(Address, 10, true) << " "
8872 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008873 << Entry.symbolName() << "\n";
8874 }
8875}
8876
Nick Kledzik56ebef42014-09-16 01:41:51 +00008877//===----------------------------------------------------------------------===//
8878// weak bind table dumping
8879//===----------------------------------------------------------------------===//
8880
8881void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8882 // Build table of sections so names can used in final output.
8883 SegInfo sectionTable(Obj);
8884
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008885 outs() << "segment section address "
8886 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008887 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8888 // Strong symbols don't have a location to update.
8889 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008890 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008891 << Entry.symbolName() << "\n";
8892 continue;
8893 }
8894 uint32_t SegIndex = Entry.segmentIndex();
8895 uint64_t OffsetInSeg = Entry.segmentOffset();
8896 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8897 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8898 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8899
8900 // Table lines look like:
8901 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008902 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008903 << left_justify(SectionName, 18) << " "
8904 << format_hex(Address, 10, true) << " "
8905 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008906 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8907 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008908 }
8909}
8910
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008911// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8912// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8913// information for that address. If the address is found its binding symbol
8914// name is returned. If not nullptr is returned.
8915static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8916 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008917 if (info->bindtable == nullptr) {
8918 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008919 SegInfo sectionTable(info->O);
8920 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8921 uint32_t SegIndex = Entry.segmentIndex();
8922 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008923 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8924 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008925 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8926 const char *SymbolName = nullptr;
8927 StringRef name = Entry.symbolName();
8928 if (!name.empty())
8929 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008930 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008931 }
8932 }
Kevin Enderby078be602014-10-23 19:53:12 +00008933 for (bind_table_iterator BI = info->bindtable->begin(),
8934 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008935 BI != BE; ++BI) {
8936 uint64_t Address = BI->first;
8937 if (ReferenceValue == Address) {
8938 const char *SymbolName = BI->second;
8939 return SymbolName;
8940 }
8941 }
8942 return nullptr;
8943}