blob: 991ccee47a576afe57a1b2b59950dfafb7be3fd3 [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"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000045#include "llvm/Support/ToolOutputFile.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000046#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include <algorithm>
48#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000049#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000050
51#if HAVE_CXXABI_H
52#include <cxxabi.h>
53#endif
54
Kevin Enderby9873e2c2016-05-23 21:34:12 +000055#ifdef HAVE_LIBXAR
56extern "C" {
57#include <xar/xar.h>
58}
59#endif
60
Benjamin Kramer43a772e2011-09-19 17:56:04 +000061using namespace llvm;
62using namespace object;
63
64static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065 UseDbg("g",
66 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<std::string> DSYMFile("dsym",
69 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000070
Kevin Enderbyb28ed012014-10-29 21:28:24 +000071static cl::opt<bool> FullLeadingAddr("full-leading-addr",
72 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000073
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000074static cl::opt<bool> NoLeadingAddr("no-leading-addr",
75 cl::desc("Print no leading address"));
76
Kevin Enderby13023a12015-01-15 23:19:11 +000077cl::opt<bool> llvm::UniversalHeaders("universal-headers",
78 cl::desc("Print Mach-O universal headers "
79 "(requires -macho)"));
80
Kevin Enderby131d1772015-01-09 19:22:37 +000081cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000082 llvm::ArchiveHeaders("archive-headers",
83 cl::desc("Print archive headers for Mach-O archives "
84 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000085
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000086cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000087 ArchiveMemberOffsets("archive-member-offsets",
88 cl::desc("Print the offset to each archive member for "
89 "Mach-O archives (requires -macho and "
90 "-archive-headers)"));
91
92cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000093 llvm::IndirectSymbols("indirect-symbols",
94 cl::desc("Print indirect symbol table for Mach-O "
95 "objects (requires -macho)"));
96
Kevin Enderby69fe98d2015-01-23 18:52:17 +000097cl::opt<bool>
98 llvm::DataInCode("data-in-code",
99 cl::desc("Print the data in code table for Mach-O objects "
100 "(requires -macho)"));
101
Kevin Enderby9a509442015-01-27 21:28:24 +0000102cl::opt<bool>
103 llvm::LinkOptHints("link-opt-hints",
104 cl::desc("Print the linker optimization hints for "
105 "Mach-O objects (requires -macho)"));
106
Kevin Enderbycd66be52015-03-11 22:06:32 +0000107cl::opt<bool>
108 llvm::InfoPlist("info-plist",
109 cl::desc("Print the info plist section as strings for "
110 "Mach-O objects (requires -macho)"));
111
Kevin Enderbyf0640752015-03-13 17:56:32 +0000112cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000113 llvm::DylibsUsed("dylibs-used",
114 cl::desc("Print the shared libraries used for linked "
115 "Mach-O files (requires -macho)"));
116
117cl::opt<bool>
118 llvm::DylibId("dylib-id",
119 cl::desc("Print the shared library's id for the dylib Mach-O "
120 "file (requires -macho)"));
121
122cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000123 llvm::NonVerbose("non-verbose",
124 cl::desc("Print the info for Mach-O objects in "
125 "non-verbose or numeric form (requires -macho)"));
126
Kevin Enderby0fc11822015-04-01 20:57:01 +0000127cl::opt<bool>
128 llvm::ObjcMetaData("objc-meta-data",
129 cl::desc("Print the Objective-C runtime meta data for "
130 "Mach-O files (requires -macho)"));
131
Kevin Enderby6a221752015-03-17 17:10:57 +0000132cl::opt<std::string> llvm::DisSymName(
133 "dis-symname",
134 cl::desc("disassemble just this symbol's instructions (requires -macho"));
135
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000136static cl::opt<bool> NoSymbolicOperands(
137 "no-symbolic-operands",
138 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
139
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000140static cl::list<std::string>
141 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
142 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000143
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000144bool ArchAll = false;
145
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000146static std::string ThumbTripleName;
147
148static const Target *GetTarget(const MachOObjectFile *MachOObj,
149 const char **McpuDefault,
150 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000151 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000152 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000153 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000154 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000155 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000156 }
157
158 if (TT.getArch() == Triple::arm) {
159 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
160 // that support ARM are also capable of Thumb mode.
161 llvm::Triple ThumbTriple = TT;
162 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
163 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000164 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000165 }
166
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000167 // Get the target specific parser.
168 std::string Error;
169 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000171 return TheTarget;
172
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000173 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
174 if (*ThumbTarget)
175 return TheTarget;
176
177 errs() << "llvm-objdump: error: unable to get target for '";
178 if (!TheTarget)
179 errs() << TripleName;
180 else
181 errs() << ThumbTripleName;
182 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000183 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000184}
185
Owen Andersond9243c42011-10-17 21:37:35 +0000186struct SymbolSorter {
187 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000188 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
189 if (!ATypeOrErr) {
190 std::string Buf;
191 raw_string_ostream OS(Buf);
192 logAllUnhandledErrors(ATypeOrErr.takeError(), OS, "");
193 OS.flush();
194 report_fatal_error(Buf);
195 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000196 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000197 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
198 if (!BTypeOrErr) {
199 std::string Buf;
200 raw_string_ostream OS(Buf);
201 logAllUnhandledErrors(BTypeOrErr.takeError(), OS, "");
202 OS.flush();
203 report_fatal_error(Buf);
204 }
Kevin Enderby74f58d42016-03-23 21:45:21 +0000205 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000206 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
207 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000208 return AAddr < BAddr;
209 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000210};
211
Kevin Enderby273ae012013-06-06 17:20:50 +0000212// Types for the storted data in code table that is built before disassembly
213// and the predicate function to sort them.
214typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
215typedef std::vector<DiceTableEntry> DiceTable;
216typedef DiceTable::iterator dice_table_iterator;
217
Kevin Enderby930fdc72014-11-06 19:00:13 +0000218// This is used to search for a data in code table entry for the PC being
219// disassembled. The j parameter has the PC in j.first. A single data in code
220// table entry can cover many bytes for each of its Kind's. So if the offset,
221// aka the i.first value, of the data in code table entry plus its Length
222// covers the PC being searched for this will return true. If not it will
223// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000224static bool compareDiceTableEntries(const DiceTableEntry &i,
225 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 uint16_t Length;
227 i.second.getLength(Length);
228
229 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000230}
231
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000232static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000233 unsigned short Kind) {
234 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000235
236 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000238 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000239 if (Length >= 4) {
240 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000241 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000242 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000243 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000244 Size = 4;
245 } else if (Length >= 2) {
246 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000247 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000248 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000249 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 Size = 2;
251 } else {
252 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000253 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000254 Value = bytes[0];
255 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000256 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000257 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000258 if (Kind == MachO::DICE_KIND_DATA)
259 outs() << "\t@ KIND_DATA\n";
260 else
261 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000262 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000263 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000264 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000265 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000266 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
268 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000269 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000270 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000271 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000272 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000273 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000274 outs() << "\t.short " << format("%5u", Value & 0xffff)
275 << "\t@ KIND_JUMP_TABLE16\n";
276 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000277 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000278 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000279 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
280 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000281 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000282 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000283 outs() << "\t.long " << Value;
284 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
285 outs() << "\t@ KIND_JUMP_TABLE32\n";
286 else
287 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
288 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000289 break;
290 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000291 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000292}
293
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000294static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000295 std::vector<SectionRef> &Sections,
296 std::vector<SymbolRef> &Symbols,
297 SmallVectorImpl<uint64_t> &FoundFns,
298 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000299 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000300 Expected<StringRef> SymName = Symbol.getName();
301 if (!SymName) {
302 std::string Buf;
303 raw_string_ostream OS(Buf);
304 logAllUnhandledErrors(SymName.takeError(), OS, "");
305 OS.flush();
306 report_fatal_error(Buf);
307 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000308 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000309 Symbols.push_back(Symbol);
310 }
Owen Andersond9243c42011-10-17 21:37:35 +0000311
Alexey Samsonov48803e52014-03-13 14:37:36 +0000312 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000313 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000314 Section.getName(SectName);
315 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000316 }
317
Kevin Enderby273ae012013-06-06 17:20:50 +0000318 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000319 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000320 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000321 // We found a function starts segment, parse the addresses for later
322 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000323 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000324 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000325
Charles Davis8bdfafd2013-09-01 04:28:48 +0000326 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000327 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
328 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000329 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000330 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000331 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000332 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000333 }
334 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000335 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000336}
337
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000338static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
339 uint32_t n, uint32_t count,
340 uint32_t stride, uint64_t addr) {
341 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
342 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
343 if (n > nindirectsyms)
344 outs() << " (entries start past the end of the indirect symbol "
345 "table) (reserved1 field greater than the table size)";
346 else if (n + count > nindirectsyms)
347 outs() << " (entries extends past the end of the indirect symbol "
348 "table)";
349 outs() << "\n";
350 uint32_t cputype = O->getHeader().cputype;
351 if (cputype & MachO::CPU_ARCH_ABI64)
352 outs() << "address index";
353 else
354 outs() << "address index";
355 if (verbose)
356 outs() << " name\n";
357 else
358 outs() << "\n";
359 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
360 if (cputype & MachO::CPU_ARCH_ABI64)
361 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
362 else
Tim Northover43978372016-04-26 18:29:16 +0000363 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000364 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
365 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
366 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
367 outs() << "LOCAL\n";
368 continue;
369 }
370 if (indirect_symbol ==
371 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
372 outs() << "LOCAL ABSOLUTE\n";
373 continue;
374 }
375 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
376 outs() << "ABSOLUTE\n";
377 continue;
378 }
379 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000380 if (verbose) {
381 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
382 if (indirect_symbol < Symtab.nsyms) {
383 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
384 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000385 Expected<StringRef> SymName = Symbol.getName();
386 if (!SymName) {
387 std::string Buf;
388 raw_string_ostream OS(Buf);
389 logAllUnhandledErrors(SymName.takeError(), OS, "");
390 OS.flush();
391 report_fatal_error(Buf);
392 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000393 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000394 } else {
395 outs() << "?";
396 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000397 }
398 outs() << "\n";
399 }
400}
401
402static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000403 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000404 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
405 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
406 for (unsigned J = 0; J < Seg.nsects; ++J) {
407 MachO::section_64 Sec = O->getSection64(Load, J);
408 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
409 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
410 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
411 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
412 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
413 section_type == MachO::S_SYMBOL_STUBS) {
414 uint32_t stride;
415 if (section_type == MachO::S_SYMBOL_STUBS)
416 stride = Sec.reserved2;
417 else
418 stride = 8;
419 if (stride == 0) {
420 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
421 << Sec.sectname << ") "
422 << "(size of stubs in reserved2 field is zero)\n";
423 continue;
424 }
425 uint32_t count = Sec.size / stride;
426 outs() << "Indirect symbols for (" << Sec.segname << ","
427 << Sec.sectname << ") " << count << " entries";
428 uint32_t n = Sec.reserved1;
429 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
430 }
431 }
432 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
433 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
434 for (unsigned J = 0; J < Seg.nsects; ++J) {
435 MachO::section Sec = O->getSection(Load, J);
436 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
437 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
438 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
439 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
440 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
441 section_type == MachO::S_SYMBOL_STUBS) {
442 uint32_t stride;
443 if (section_type == MachO::S_SYMBOL_STUBS)
444 stride = Sec.reserved2;
445 else
446 stride = 4;
447 if (stride == 0) {
448 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
449 << Sec.sectname << ") "
450 << "(size of stubs in reserved2 field is zero)\n";
451 continue;
452 }
453 uint32_t count = Sec.size / stride;
454 outs() << "Indirect symbols for (" << Sec.segname << ","
455 << Sec.sectname << ") " << count << " entries";
456 uint32_t n = Sec.reserved1;
457 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
458 }
459 }
460 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000461 }
462}
463
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000464static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
465 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
466 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
467 outs() << "Data in code table (" << nentries << " entries)\n";
468 outs() << "offset length kind\n";
469 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
470 ++DI) {
471 uint32_t Offset;
472 DI->getOffset(Offset);
473 outs() << format("0x%08" PRIx32, Offset) << " ";
474 uint16_t Length;
475 DI->getLength(Length);
476 outs() << format("%6u", Length) << " ";
477 uint16_t Kind;
478 DI->getKind(Kind);
479 if (verbose) {
480 switch (Kind) {
481 case MachO::DICE_KIND_DATA:
482 outs() << "DATA";
483 break;
484 case MachO::DICE_KIND_JUMP_TABLE8:
485 outs() << "JUMP_TABLE8";
486 break;
487 case MachO::DICE_KIND_JUMP_TABLE16:
488 outs() << "JUMP_TABLE16";
489 break;
490 case MachO::DICE_KIND_JUMP_TABLE32:
491 outs() << "JUMP_TABLE32";
492 break;
493 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
494 outs() << "ABS_JUMP_TABLE32";
495 break;
496 default:
497 outs() << format("0x%04" PRIx32, Kind);
498 break;
499 }
500 } else
501 outs() << format("0x%04" PRIx32, Kind);
502 outs() << "\n";
503 }
504}
505
Kevin Enderby9a509442015-01-27 21:28:24 +0000506static void PrintLinkOptHints(MachOObjectFile *O) {
507 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
508 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
509 uint32_t nloh = LohLC.datasize;
510 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
511 for (uint32_t i = 0; i < nloh;) {
512 unsigned n;
513 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
514 i += n;
515 outs() << " identifier " << identifier << " ";
516 if (i >= nloh)
517 return;
518 switch (identifier) {
519 case 1:
520 outs() << "AdrpAdrp\n";
521 break;
522 case 2:
523 outs() << "AdrpLdr\n";
524 break;
525 case 3:
526 outs() << "AdrpAddLdr\n";
527 break;
528 case 4:
529 outs() << "AdrpLdrGotLdr\n";
530 break;
531 case 5:
532 outs() << "AdrpAddStr\n";
533 break;
534 case 6:
535 outs() << "AdrpLdrGotStr\n";
536 break;
537 case 7:
538 outs() << "AdrpAdd\n";
539 break;
540 case 8:
541 outs() << "AdrpLdrGot\n";
542 break;
543 default:
544 outs() << "Unknown identifier value\n";
545 break;
546 }
547 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
548 i += n;
549 outs() << " narguments " << narguments << "\n";
550 if (i >= nloh)
551 return;
552
553 for (uint32_t j = 0; j < narguments; j++) {
554 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
555 i += n;
556 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
557 if (i >= nloh)
558 return;
559 }
560 }
561}
562
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000563static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000564 unsigned Index = 0;
565 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000566 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
567 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
568 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
569 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
570 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
571 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
572 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
573 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
574 if (dl.dylib.name < dl.cmdsize) {
575 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
576 if (JustId)
577 outs() << p << "\n";
578 else {
579 outs() << "\t" << p;
580 outs() << " (compatibility version "
581 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
582 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
583 << (dl.dylib.compatibility_version & 0xff) << ",";
584 outs() << " current version "
585 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
586 << ((dl.dylib.current_version >> 8) & 0xff) << "."
587 << (dl.dylib.current_version & 0xff) << ")\n";
588 }
589 } else {
590 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
591 if (Load.C.cmd == MachO::LC_ID_DYLIB)
592 outs() << "LC_ID_DYLIB ";
593 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
594 outs() << "LC_LOAD_DYLIB ";
595 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
596 outs() << "LC_LOAD_WEAK_DYLIB ";
597 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
598 outs() << "LC_LAZY_LOAD_DYLIB ";
599 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
600 outs() << "LC_REEXPORT_DYLIB ";
601 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
602 outs() << "LC_LOAD_UPWARD_DYLIB ";
603 else
604 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000605 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000606 }
607 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000608 }
609}
610
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000611typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
612
613static void CreateSymbolAddressMap(MachOObjectFile *O,
614 SymbolAddressMap *AddrMap) {
615 // Create a map of symbol addresses to symbol names.
616 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000617 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
618 if (!STOrErr) {
619 std::string Buf;
620 raw_string_ostream OS(Buf);
621 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
622 OS.flush();
623 report_fatal_error(Buf);
624 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000625 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000626 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
627 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000628 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000629 Expected<StringRef> SymNameOrErr = Symbol.getName();
630 if (!SymNameOrErr) {
631 std::string Buf;
632 raw_string_ostream OS(Buf);
633 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
634 OS.flush();
635 report_fatal_error(Buf);
636 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000637 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000638 if (!SymName.startswith(".objc"))
639 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000640 }
641 }
642}
643
644// GuessSymbolName is passed the address of what might be a symbol and a
645// pointer to the SymbolAddressMap. It returns the name of a symbol
646// with that address or nullptr if no symbol is found with that address.
647static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
648 const char *SymbolName = nullptr;
649 // A DenseMap can't lookup up some values.
650 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
651 StringRef name = AddrMap->lookup(value);
652 if (!name.empty())
653 SymbolName = name.data();
654 }
655 return SymbolName;
656}
657
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000658static void DumpCstringChar(const char c) {
659 char p[2];
660 p[0] = c;
661 p[1] = '\0';
662 outs().write_escaped(p);
663}
664
Kevin Enderby10ba0412015-02-04 21:38:42 +0000665static void DumpCstringSection(MachOObjectFile *O, const char *sect,
666 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000667 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000668 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000669 if (print_addresses) {
670 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000671 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000672 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000673 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000674 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000675 for (; i < sect_size && sect[i] != '\0'; i++)
676 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000677 if (i < sect_size && sect[i] == '\0')
678 outs() << "\n";
679 }
680}
681
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000682static void DumpLiteral4(uint32_t l, float f) {
683 outs() << format("0x%08" PRIx32, l);
684 if ((l & 0x7f800000) != 0x7f800000)
685 outs() << format(" (%.16e)\n", f);
686 else {
687 if (l == 0x7f800000)
688 outs() << " (+Infinity)\n";
689 else if (l == 0xff800000)
690 outs() << " (-Infinity)\n";
691 else if ((l & 0x00400000) == 0x00400000)
692 outs() << " (non-signaling Not-a-Number)\n";
693 else
694 outs() << " (signaling Not-a-Number)\n";
695 }
696}
697
698static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
699 uint32_t sect_size, uint64_t sect_addr,
700 bool print_addresses) {
701 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
702 if (print_addresses) {
703 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000704 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000705 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000706 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000707 }
708 float f;
709 memcpy(&f, sect + i, sizeof(float));
710 if (O->isLittleEndian() != sys::IsLittleEndianHost)
711 sys::swapByteOrder(f);
712 uint32_t l;
713 memcpy(&l, sect + i, sizeof(uint32_t));
714 if (O->isLittleEndian() != sys::IsLittleEndianHost)
715 sys::swapByteOrder(l);
716 DumpLiteral4(l, f);
717 }
718}
719
720static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
721 double d) {
722 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
723 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000724 Hi = (O->isLittleEndian()) ? l1 : l0;
725 Lo = (O->isLittleEndian()) ? l0 : l1;
726
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000727 // Hi is the high word, so this is equivalent to if(isfinite(d))
728 if ((Hi & 0x7ff00000) != 0x7ff00000)
729 outs() << format(" (%.16e)\n", d);
730 else {
731 if (Hi == 0x7ff00000 && Lo == 0)
732 outs() << " (+Infinity)\n";
733 else if (Hi == 0xfff00000 && Lo == 0)
734 outs() << " (-Infinity)\n";
735 else if ((Hi & 0x00080000) == 0x00080000)
736 outs() << " (non-signaling Not-a-Number)\n";
737 else
738 outs() << " (signaling Not-a-Number)\n";
739 }
740}
741
742static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
743 uint32_t sect_size, uint64_t sect_addr,
744 bool print_addresses) {
745 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
746 if (print_addresses) {
747 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000748 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000749 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000750 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000751 }
752 double d;
753 memcpy(&d, sect + i, sizeof(double));
754 if (O->isLittleEndian() != sys::IsLittleEndianHost)
755 sys::swapByteOrder(d);
756 uint32_t l0, l1;
757 memcpy(&l0, sect + i, sizeof(uint32_t));
758 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
759 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
760 sys::swapByteOrder(l0);
761 sys::swapByteOrder(l1);
762 }
763 DumpLiteral8(O, l0, l1, d);
764 }
765}
766
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000767static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
768 outs() << format("0x%08" PRIx32, l0) << " ";
769 outs() << format("0x%08" PRIx32, l1) << " ";
770 outs() << format("0x%08" PRIx32, l2) << " ";
771 outs() << format("0x%08" PRIx32, l3) << "\n";
772}
773
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000774static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
775 uint32_t sect_size, uint64_t sect_addr,
776 bool print_addresses) {
777 for (uint32_t i = 0; i < sect_size; i += 16) {
778 if (print_addresses) {
779 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000780 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000781 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000782 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000783 }
784 uint32_t l0, l1, l2, l3;
785 memcpy(&l0, sect + i, sizeof(uint32_t));
786 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
787 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
788 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
789 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
790 sys::swapByteOrder(l0);
791 sys::swapByteOrder(l1);
792 sys::swapByteOrder(l2);
793 sys::swapByteOrder(l3);
794 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000795 DumpLiteral16(l0, l1, l2, l3);
796 }
797}
798
799static void DumpLiteralPointerSection(MachOObjectFile *O,
800 const SectionRef &Section,
801 const char *sect, uint32_t sect_size,
802 uint64_t sect_addr,
803 bool print_addresses) {
804 // Collect the literal sections in this Mach-O file.
805 std::vector<SectionRef> LiteralSections;
806 for (const SectionRef &Section : O->sections()) {
807 DataRefImpl Ref = Section.getRawDataRefImpl();
808 uint32_t section_type;
809 if (O->is64Bit()) {
810 const MachO::section_64 Sec = O->getSection64(Ref);
811 section_type = Sec.flags & MachO::SECTION_TYPE;
812 } else {
813 const MachO::section Sec = O->getSection(Ref);
814 section_type = Sec.flags & MachO::SECTION_TYPE;
815 }
816 if (section_type == MachO::S_CSTRING_LITERALS ||
817 section_type == MachO::S_4BYTE_LITERALS ||
818 section_type == MachO::S_8BYTE_LITERALS ||
819 section_type == MachO::S_16BYTE_LITERALS)
820 LiteralSections.push_back(Section);
821 }
822
823 // Set the size of the literal pointer.
824 uint32_t lp_size = O->is64Bit() ? 8 : 4;
825
Eric Christopher572e03a2015-06-19 01:53:21 +0000826 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000827 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
828 for (const RelocationRef &Reloc : Section.relocations()) {
829 DataRefImpl Rel;
830 MachO::any_relocation_info RE;
831 bool isExtern = false;
832 Rel = Reloc.getRawDataRefImpl();
833 RE = O->getRelocation(Rel);
834 isExtern = O->getPlainRelocationExternal(RE);
835 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000836 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000837 symbol_iterator RelocSym = Reloc.getSymbol();
838 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
839 }
840 }
841 array_pod_sort(Relocs.begin(), Relocs.end());
842
843 // Dump each literal pointer.
844 for (uint32_t i = 0; i < sect_size; i += lp_size) {
845 if (print_addresses) {
846 if (O->is64Bit())
847 outs() << format("%016" PRIx64, sect_addr + i) << " ";
848 else
849 outs() << format("%08" PRIx64, sect_addr + i) << " ";
850 }
851 uint64_t lp;
852 if (O->is64Bit()) {
853 memcpy(&lp, sect + i, sizeof(uint64_t));
854 if (O->isLittleEndian() != sys::IsLittleEndianHost)
855 sys::swapByteOrder(lp);
856 } else {
857 uint32_t li;
858 memcpy(&li, sect + i, sizeof(uint32_t));
859 if (O->isLittleEndian() != sys::IsLittleEndianHost)
860 sys::swapByteOrder(li);
861 lp = li;
862 }
863
864 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000865 auto Reloc = std::find_if(
866 Relocs.begin(), Relocs.end(),
867 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
868 if (Reloc != Relocs.end()) {
869 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000870 Expected<StringRef> SymName = RelocSym->getName();
871 if (!SymName) {
872 std::string Buf;
873 raw_string_ostream OS(Buf);
874 logAllUnhandledErrors(SymName.takeError(), OS, "");
875 OS.flush();
876 report_fatal_error(Buf);
877 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000878 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000879 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000880 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000881
882 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000883 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
884 [&](const SectionRef &R) {
885 return lp >= R.getAddress() &&
886 lp < R.getAddress() + R.getSize();
887 });
888 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000889 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000890 continue;
891 }
892
893 uint64_t SectAddress = Sect->getAddress();
894 uint64_t SectSize = Sect->getSize();
895
896 StringRef SectName;
897 Sect->getName(SectName);
898 DataRefImpl Ref = Sect->getRawDataRefImpl();
899 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
900 outs() << SegmentName << ":" << SectName << ":";
901
902 uint32_t section_type;
903 if (O->is64Bit()) {
904 const MachO::section_64 Sec = O->getSection64(Ref);
905 section_type = Sec.flags & MachO::SECTION_TYPE;
906 } else {
907 const MachO::section Sec = O->getSection(Ref);
908 section_type = Sec.flags & MachO::SECTION_TYPE;
909 }
910
911 StringRef BytesStr;
912 Sect->getContents(BytesStr);
913 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
914
915 switch (section_type) {
916 case MachO::S_CSTRING_LITERALS:
917 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
918 i++) {
919 DumpCstringChar(Contents[i]);
920 }
921 outs() << "\n";
922 break;
923 case MachO::S_4BYTE_LITERALS:
924 float f;
925 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
926 uint32_t l;
927 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
928 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
929 sys::swapByteOrder(f);
930 sys::swapByteOrder(l);
931 }
932 DumpLiteral4(l, f);
933 break;
934 case MachO::S_8BYTE_LITERALS: {
935 double d;
936 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
937 uint32_t l0, l1;
938 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
939 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
940 sizeof(uint32_t));
941 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
942 sys::swapByteOrder(f);
943 sys::swapByteOrder(l0);
944 sys::swapByteOrder(l1);
945 }
946 DumpLiteral8(O, l0, l1, d);
947 break;
948 }
949 case MachO::S_16BYTE_LITERALS: {
950 uint32_t l0, l1, l2, l3;
951 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
952 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
953 sizeof(uint32_t));
954 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
955 sizeof(uint32_t));
956 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
957 sizeof(uint32_t));
958 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
959 sys::swapByteOrder(l0);
960 sys::swapByteOrder(l1);
961 sys::swapByteOrder(l2);
962 sys::swapByteOrder(l3);
963 }
964 DumpLiteral16(l0, l1, l2, l3);
965 break;
966 }
967 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000968 }
969}
970
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000971static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
972 uint32_t sect_size, uint64_t sect_addr,
973 SymbolAddressMap *AddrMap,
974 bool verbose) {
975 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000976 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000977 for (uint32_t i = 0; i < sect_size; i += stride) {
978 const char *SymbolName = nullptr;
979 if (O->is64Bit()) {
980 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
981 uint64_t pointer_value;
982 memcpy(&pointer_value, sect + i, stride);
983 if (O->isLittleEndian() != sys::IsLittleEndianHost)
984 sys::swapByteOrder(pointer_value);
985 outs() << format("0x%016" PRIx64, pointer_value);
986 if (verbose)
987 SymbolName = GuessSymbolName(pointer_value, AddrMap);
988 } else {
989 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
990 uint32_t pointer_value;
991 memcpy(&pointer_value, sect + i, stride);
992 if (O->isLittleEndian() != sys::IsLittleEndianHost)
993 sys::swapByteOrder(pointer_value);
994 outs() << format("0x%08" PRIx32, pointer_value);
995 if (verbose)
996 SymbolName = GuessSymbolName(pointer_value, AddrMap);
997 }
998 if (SymbolName)
999 outs() << " " << SymbolName;
1000 outs() << "\n";
1001 }
1002}
1003
1004static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1005 uint32_t size, uint64_t addr) {
1006 uint32_t cputype = O->getHeader().cputype;
1007 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1008 uint32_t j;
1009 for (uint32_t i = 0; i < size; i += j, addr += j) {
1010 if (O->is64Bit())
1011 outs() << format("%016" PRIx64, addr) << "\t";
1012 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001013 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001014 for (j = 0; j < 16 && i + j < size; j++) {
1015 uint8_t byte_word = *(sect + i + j);
1016 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1017 }
1018 outs() << "\n";
1019 }
1020 } else {
1021 uint32_t j;
1022 for (uint32_t i = 0; i < size; i += j, addr += j) {
1023 if (O->is64Bit())
1024 outs() << format("%016" PRIx64, addr) << "\t";
1025 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001026 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001027 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1028 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001029 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001030 uint32_t long_word;
1031 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1032 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1033 sys::swapByteOrder(long_word);
1034 outs() << format("%08" PRIx32, long_word) << " ";
1035 } else {
1036 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001037 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001038 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1039 }
1040 }
1041 }
1042 outs() << "\n";
1043 }
1044 }
1045}
1046
Kevin Enderby95df54c2015-02-04 01:01:38 +00001047static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1048 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001049static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1050 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001051#ifdef HAVE_LIBXAR
1052static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1053 uint32_t size, bool verbose,
1054 bool PrintXarHeader, bool PrintXarFileHeaders,
1055 std::string XarMemberName);
1056#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001057
1058static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1059 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001060 SymbolAddressMap AddrMap;
1061 if (verbose)
1062 CreateSymbolAddressMap(O, &AddrMap);
1063
Colin LeMahieufcc32762015-07-29 19:08:10 +00001064 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1065 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001066 std::pair<StringRef, StringRef> DumpSegSectName;
1067 DumpSegSectName = DumpSection.split(',');
1068 StringRef DumpSegName, DumpSectName;
1069 if (DumpSegSectName.second.size()) {
1070 DumpSegName = DumpSegSectName.first;
1071 DumpSectName = DumpSegSectName.second;
1072 } else {
1073 DumpSegName = "";
1074 DumpSectName = DumpSegSectName.first;
1075 }
1076 for (const SectionRef &Section : O->sections()) {
1077 StringRef SectName;
1078 Section.getName(SectName);
1079 DataRefImpl Ref = Section.getRawDataRefImpl();
1080 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1081 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1082 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001083
Kevin Enderby95df54c2015-02-04 01:01:38 +00001084 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001085 if (O->is64Bit()) {
1086 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001087 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001088
1089 } else {
1090 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001091 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001092 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001093 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001094
1095 StringRef BytesStr;
1096 Section.getContents(BytesStr);
1097 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1098 uint32_t sect_size = BytesStr.size();
1099 uint64_t sect_addr = Section.getAddress();
1100
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001101 outs() << "Contents of (" << SegName << "," << SectName
1102 << ") section\n";
1103
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001104 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001105 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1106 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1107 DisassembleMachO(Filename, O, SegName, SectName);
1108 continue;
1109 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001110 if (SegName == "__TEXT" && SectName == "__info_plist") {
1111 outs() << sect;
1112 continue;
1113 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001114 if (SegName == "__OBJC" && SectName == "__protocol") {
1115 DumpProtocolSection(O, sect, sect_size, sect_addr);
1116 continue;
1117 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001118#ifdef HAVE_LIBXAR
1119 if (SegName == "__LLVM" && SectName == "__bundle") {
1120 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1121 ArchiveHeaders, "");
1122 continue;
1123 }
1124#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001125 switch (section_type) {
1126 case MachO::S_REGULAR:
1127 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1128 break;
1129 case MachO::S_ZEROFILL:
1130 outs() << "zerofill section and has no contents in the file\n";
1131 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001132 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001133 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001134 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001135 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001136 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001137 break;
1138 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001139 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001140 break;
1141 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001142 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1143 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001144 case MachO::S_LITERAL_POINTERS:
1145 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001146 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001147 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001148 case MachO::S_MOD_INIT_FUNC_POINTERS:
1149 case MachO::S_MOD_TERM_FUNC_POINTERS:
1150 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1151 verbose);
1152 break;
1153 default:
1154 outs() << "Unknown section type ("
1155 << format("0x%08" PRIx32, section_type) << ")\n";
1156 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1157 break;
1158 }
1159 } else {
1160 if (section_type == MachO::S_ZEROFILL)
1161 outs() << "zerofill section and has no contents in the file\n";
1162 else
1163 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1164 }
1165 }
1166 }
1167 }
1168}
1169
Kevin Enderbycd66be52015-03-11 22:06:32 +00001170static void DumpInfoPlistSectionContents(StringRef Filename,
1171 MachOObjectFile *O) {
1172 for (const SectionRef &Section : O->sections()) {
1173 StringRef SectName;
1174 Section.getName(SectName);
1175 DataRefImpl Ref = Section.getRawDataRefImpl();
1176 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1177 if (SegName == "__TEXT" && SectName == "__info_plist") {
1178 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1179 StringRef BytesStr;
1180 Section.getContents(BytesStr);
1181 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1182 outs() << sect;
1183 return;
1184 }
1185 }
1186}
1187
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001188// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1189// and if it is and there is a list of architecture flags is specified then
1190// check to make sure this Mach-O file is one of those architectures or all
1191// architectures were specified. If not then an error is generated and this
1192// routine returns false. Else it returns true.
1193static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1194 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1195 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1196 bool ArchFound = false;
1197 MachO::mach_header H;
1198 MachO::mach_header_64 H_64;
1199 Triple T;
1200 if (MachO->is64Bit()) {
1201 H_64 = MachO->MachOObjectFile::getHeader64();
Tim Northover9e8eb412016-04-22 23:21:13 +00001202 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001203 } else {
1204 H = MachO->MachOObjectFile::getHeader();
Tim Northover9e8eb412016-04-22 23:21:13 +00001205 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001206 }
1207 unsigned i;
1208 for (i = 0; i < ArchFlags.size(); ++i) {
1209 if (ArchFlags[i] == T.getArchName())
1210 ArchFound = true;
1211 break;
1212 }
1213 if (!ArchFound) {
1214 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1215 << "architecture: " + ArchFlags[i] + "\n";
1216 return false;
1217 }
1218 }
1219 return true;
1220}
1221
Kevin Enderby0fc11822015-04-01 20:57:01 +00001222static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1223
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001224// ProcessMachO() is passed a single opened Mach-O file, which may be an
1225// archive member and or in a slice of a universal file. It prints the
1226// the file name and header info and then processes it according to the
1227// command line options.
1228static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1229 StringRef ArchiveMemberName = StringRef(),
1230 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001231 // If we are doing some processing here on the Mach-O file print the header
1232 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001233 // UniversalHeaders or ArchiveHeaders.
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001234 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001235 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001236 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001237 outs() << Filename;
1238 if (!ArchiveMemberName.empty())
1239 outs() << '(' << ArchiveMemberName << ')';
1240 if (!ArchitectureName.empty())
1241 outs() << " (architecture " << ArchitectureName << ")";
1242 outs() << ":\n";
1243 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001244
1245 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001246 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001247 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001248 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001249 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001250 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001251 if (LinkOptHints)
1252 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001253 if (Relocations)
1254 PrintRelocations(MachOOF);
1255 if (SectionHeaders)
1256 PrintSectionHeaders(MachOOF);
1257 if (SectionContents)
1258 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001259 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001260 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001261 if (InfoPlist)
1262 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001263 if (DylibsUsed)
1264 PrintDylibs(MachOOF, false);
1265 if (DylibId)
1266 PrintDylibs(MachOOF, true);
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001267 if (SymbolTable) {
1268 StringRef ArchiveName = ArchiveMemberName == StringRef() ? "" : Filename;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001269 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001270 }
Kevin Enderby98da6132015-01-20 21:47:46 +00001271 if (UnwindInfo)
1272 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001273 if (PrivateHeaders) {
1274 printMachOFileHeader(MachOOF);
1275 printMachOLoadCommands(MachOOF);
1276 }
1277 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001278 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001279 if (ObjcMetaData)
1280 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001281 if (ExportsTrie)
1282 printExportsTrie(MachOOF);
1283 if (Rebase)
1284 printRebaseTable(MachOOF);
1285 if (Bind)
1286 printBindTable(MachOOF);
1287 if (LazyBind)
1288 printLazyBindTable(MachOOF);
1289 if (WeakBind)
1290 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001291
1292 if (DwarfDumpType != DIDT_Null) {
1293 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1294 // Dump the complete DWARF structure.
1295 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1296 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001297}
1298
Kevin Enderby131d1772015-01-09 19:22:37 +00001299// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1300static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1301 outs() << " cputype (" << cputype << ")\n";
1302 outs() << " cpusubtype (" << cpusubtype << ")\n";
1303}
1304
1305// printCPUType() helps print_fat_headers by printing the cputype and
1306// pusubtype (symbolically for the one's it knows about).
1307static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1308 switch (cputype) {
1309 case MachO::CPU_TYPE_I386:
1310 switch (cpusubtype) {
1311 case MachO::CPU_SUBTYPE_I386_ALL:
1312 outs() << " cputype CPU_TYPE_I386\n";
1313 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1314 break;
1315 default:
1316 printUnknownCPUType(cputype, cpusubtype);
1317 break;
1318 }
1319 break;
1320 case MachO::CPU_TYPE_X86_64:
1321 switch (cpusubtype) {
1322 case MachO::CPU_SUBTYPE_X86_64_ALL:
1323 outs() << " cputype CPU_TYPE_X86_64\n";
1324 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1325 break;
1326 case MachO::CPU_SUBTYPE_X86_64_H:
1327 outs() << " cputype CPU_TYPE_X86_64\n";
1328 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1329 break;
1330 default:
1331 printUnknownCPUType(cputype, cpusubtype);
1332 break;
1333 }
1334 break;
1335 case MachO::CPU_TYPE_ARM:
1336 switch (cpusubtype) {
1337 case MachO::CPU_SUBTYPE_ARM_ALL:
1338 outs() << " cputype CPU_TYPE_ARM\n";
1339 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1340 break;
1341 case MachO::CPU_SUBTYPE_ARM_V4T:
1342 outs() << " cputype CPU_TYPE_ARM\n";
1343 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1344 break;
1345 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1346 outs() << " cputype CPU_TYPE_ARM\n";
1347 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1348 break;
1349 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1350 outs() << " cputype CPU_TYPE_ARM\n";
1351 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1352 break;
1353 case MachO::CPU_SUBTYPE_ARM_V6:
1354 outs() << " cputype CPU_TYPE_ARM\n";
1355 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1356 break;
1357 case MachO::CPU_SUBTYPE_ARM_V6M:
1358 outs() << " cputype CPU_TYPE_ARM\n";
1359 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1360 break;
1361 case MachO::CPU_SUBTYPE_ARM_V7:
1362 outs() << " cputype CPU_TYPE_ARM\n";
1363 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1364 break;
1365 case MachO::CPU_SUBTYPE_ARM_V7EM:
1366 outs() << " cputype CPU_TYPE_ARM\n";
1367 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1368 break;
1369 case MachO::CPU_SUBTYPE_ARM_V7K:
1370 outs() << " cputype CPU_TYPE_ARM\n";
1371 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1372 break;
1373 case MachO::CPU_SUBTYPE_ARM_V7M:
1374 outs() << " cputype CPU_TYPE_ARM\n";
1375 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1376 break;
1377 case MachO::CPU_SUBTYPE_ARM_V7S:
1378 outs() << " cputype CPU_TYPE_ARM\n";
1379 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1380 break;
1381 default:
1382 printUnknownCPUType(cputype, cpusubtype);
1383 break;
1384 }
1385 break;
1386 case MachO::CPU_TYPE_ARM64:
1387 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1388 case MachO::CPU_SUBTYPE_ARM64_ALL:
1389 outs() << " cputype CPU_TYPE_ARM64\n";
1390 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1391 break;
1392 default:
1393 printUnknownCPUType(cputype, cpusubtype);
1394 break;
1395 }
1396 break;
1397 default:
1398 printUnknownCPUType(cputype, cpusubtype);
1399 break;
1400 }
1401}
1402
1403static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1404 bool verbose) {
1405 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001406 if (verbose) {
1407 if (UB->getMagic() == MachO::FAT_MAGIC)
1408 outs() << "fat_magic FAT_MAGIC\n";
1409 else // UB->getMagic() == MachO::FAT_MAGIC_64
1410 outs() << "fat_magic FAT_MAGIC_64\n";
1411 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001412 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1413
1414 uint32_t nfat_arch = UB->getNumberOfObjects();
1415 StringRef Buf = UB->getData();
1416 uint64_t size = Buf.size();
1417 uint64_t big_size = sizeof(struct MachO::fat_header) +
1418 nfat_arch * sizeof(struct MachO::fat_arch);
1419 outs() << "nfat_arch " << UB->getNumberOfObjects();
1420 if (nfat_arch == 0)
1421 outs() << " (malformed, contains zero architecture types)\n";
1422 else if (big_size > size)
1423 outs() << " (malformed, architectures past end of file)\n";
1424 else
1425 outs() << "\n";
1426
1427 for (uint32_t i = 0; i < nfat_arch; ++i) {
1428 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1429 uint32_t cputype = OFA.getCPUType();
1430 uint32_t cpusubtype = OFA.getCPUSubType();
1431 outs() << "architecture ";
1432 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1433 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1434 uint32_t other_cputype = other_OFA.getCPUType();
1435 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001436 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001437 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001438 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001439 outs() << "(illegal duplicate architecture) ";
1440 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001441 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001442 }
1443 if (verbose) {
1444 outs() << OFA.getArchTypeName() << "\n";
1445 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1446 } else {
1447 outs() << i << "\n";
1448 outs() << " cputype " << cputype << "\n";
1449 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1450 << "\n";
1451 }
1452 if (verbose &&
1453 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1454 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1455 else
1456 outs() << " capabilities "
1457 << format("0x%" PRIx32,
1458 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1459 outs() << " offset " << OFA.getOffset();
1460 if (OFA.getOffset() > size)
1461 outs() << " (past end of file)";
1462 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1463 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1464 outs() << "\n";
1465 outs() << " size " << OFA.getSize();
1466 big_size = OFA.getOffset() + OFA.getSize();
1467 if (big_size > size)
1468 outs() << " (past end of file)";
1469 outs() << "\n";
1470 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1471 << ")\n";
1472 }
1473}
1474
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001475static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001476 bool print_offset) {
1477 if (print_offset)
1478 outs() << C.getChildOffset() << "\t";
1479 sys::fs::perms Mode = C.getAccessMode();
1480 if (verbose) {
1481 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1482 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1483 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001484 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1485 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1486 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1487 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1488 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1489 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1490 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1491 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1492 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001493 } else {
1494 outs() << format("0%o ", Mode);
1495 }
1496
1497 unsigned UID = C.getUID();
1498 outs() << format("%3d/", UID);
1499 unsigned GID = C.getGID();
1500 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001501 ErrorOr<uint64_t> Size = C.getRawSize();
1502 if (std::error_code EC = Size.getError())
1503 report_fatal_error(EC.message());
1504 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001505
1506 StringRef RawLastModified = C.getRawLastModified();
1507 if (verbose) {
1508 unsigned Seconds;
1509 if (RawLastModified.getAsInteger(10, Seconds))
1510 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1511 else {
1512 // Since cime(3) returns a 26 character string of the form:
1513 // "Sun Sep 16 01:03:52 1973\n\0"
1514 // just print 24 characters.
1515 time_t t = Seconds;
1516 outs() << format("%.24s ", ctime(&t));
1517 }
1518 } else {
1519 outs() << RawLastModified << " ";
1520 }
1521
1522 if (verbose) {
1523 ErrorOr<StringRef> NameOrErr = C.getName();
1524 if (NameOrErr.getError()) {
1525 StringRef RawName = C.getRawName();
1526 outs() << RawName << "\n";
1527 } else {
1528 StringRef Name = NameOrErr.get();
1529 outs() << Name << "\n";
1530 }
1531 } else {
1532 StringRef RawName = C.getRawName();
1533 outs() << RawName << "\n";
1534 }
1535}
1536
1537static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Lang Hamesfc209622016-07-14 02:24:01 +00001538 Error Err;
1539 for (const auto &C : A->children(Err, false))
Kevin Enderby13023a12015-01-15 23:19:11 +00001540 printArchiveChild(C, verbose, print_offset);
Lang Hamesfc209622016-07-14 02:24:01 +00001541 if (Err)
1542 report_fatal_error(std::move(Err));
Kevin Enderby13023a12015-01-15 23:19:11 +00001543}
1544
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001545// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1546// -arch flags selecting just those slices as specified by them and also parses
1547// archive files. Then for each individual Mach-O file ProcessMachO() is
1548// called to process the file based on the command line options.
1549void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001550 // Check for -arch all and verifiy the -arch flags are valid.
1551 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1552 if (ArchFlags[i] == "all") {
1553 ArchAll = true;
1554 } else {
1555 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1556 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1557 "'for the -arch option\n";
1558 return;
1559 }
1560 }
1561 }
1562
1563 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001564 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1565 if (!BinaryOrErr)
1566 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001567 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001568
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001569 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1570 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001571 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001572 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Lang Hamesfc209622016-07-14 02:24:01 +00001573 Error Err;
1574 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001575 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1576 if (!ChildOrErr) {
1577 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1578 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001579 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001580 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001581 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1582 if (!checkMachOAndArchFlags(O, Filename))
1583 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001584 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001585 }
1586 }
Lang Hamesfc209622016-07-14 02:24:01 +00001587 if (Err)
1588 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001589 return;
1590 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001591 if (UniversalHeaders) {
1592 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001593 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001594 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001595 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1596 // If we have a list of architecture flags specified dump only those.
1597 if (!ArchAll && ArchFlags.size() != 0) {
1598 // Look for a slice in the universal binary that matches each ArchFlag.
1599 bool ArchFound;
1600 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1601 ArchFound = false;
1602 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1603 E = UB->end_objects();
1604 I != E; ++I) {
1605 if (ArchFlags[i] == I->getArchTypeName()) {
1606 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001607 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001608 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001609 std::string ArchitectureName = "";
1610 if (ArchFlags.size() > 1)
1611 ArchitectureName = I->getArchTypeName();
1612 if (ObjOrErr) {
1613 ObjectFile &O = *ObjOrErr.get();
1614 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001615 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001616 } else if (auto E = isNotObjectErrorInvalidFileType(
1617 ObjOrErr.takeError())) {
1618 report_error(Filename, StringRef(), std::move(E),
1619 ArchitectureName);
1620 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001621 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001622 I->getAsArchive()) {
1623 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001624 outs() << "Archive : " << Filename;
1625 if (!ArchitectureName.empty())
1626 outs() << " (architecture " << ArchitectureName << ")";
1627 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001628 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001629 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Lang Hamesfc209622016-07-14 02:24:01 +00001630 Error Err;
1631 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001632 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1633 if (!ChildOrErr) {
1634 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001635 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001636 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001637 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001638 if (MachOObjectFile *O =
1639 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001640 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001641 }
Lang Hamesfc209622016-07-14 02:24:01 +00001642 if (Err)
1643 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001644 } else {
1645 consumeError(AOrErr.takeError());
1646 error("Mach-O universal file: " + Filename + " for " +
1647 "architecture " + StringRef(I->getArchTypeName()) +
1648 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001649 }
1650 }
1651 }
1652 if (!ArchFound) {
1653 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1654 << "architecture: " + ArchFlags[i] + "\n";
1655 return;
1656 }
1657 }
1658 return;
1659 }
1660 // No architecture flags were specified so if this contains a slice that
1661 // matches the host architecture dump only that.
1662 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001663 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1664 E = UB->end_objects();
1665 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001666 if (MachOObjectFile::getHostArch().getArchName() ==
1667 I->getArchTypeName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001668 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001669 std::string ArchiveName;
1670 ArchiveName.clear();
1671 if (ObjOrErr) {
1672 ObjectFile &O = *ObjOrErr.get();
1673 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001674 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001675 } else if (auto E = isNotObjectErrorInvalidFileType(
1676 ObjOrErr.takeError())) {
1677 report_error(Filename, std::move(E));
1678 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001679 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001680 I->getAsArchive()) {
1681 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001682 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001683 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001684 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Lang Hamesfc209622016-07-14 02:24:01 +00001685 Error Err;
1686 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001687 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1688 if (!ChildOrErr) {
1689 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1690 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001691 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001692 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001693 if (MachOObjectFile *O =
1694 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001695 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001696 }
Lang Hamesfc209622016-07-14 02:24:01 +00001697 if (Err)
1698 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001699 } else {
1700 consumeError(AOrErr.takeError());
1701 error("Mach-O universal file: " + Filename + " for architecture " +
1702 StringRef(I->getArchTypeName()) +
1703 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001704 }
1705 return;
1706 }
1707 }
1708 }
1709 // Either all architectures have been specified or none have been specified
1710 // and this does not contain the host architecture so dump all the slices.
1711 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1712 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1713 E = UB->end_objects();
1714 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001715 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001716 std::string ArchitectureName = "";
1717 if (moreThanOneArch)
1718 ArchitectureName = I->getArchTypeName();
1719 if (ObjOrErr) {
1720 ObjectFile &Obj = *ObjOrErr.get();
1721 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001722 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001723 } else if (auto E = isNotObjectErrorInvalidFileType(
1724 ObjOrErr.takeError())) {
1725 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1726 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001727 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1728 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001729 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001730 outs() << "Archive : " << Filename;
1731 if (!ArchitectureName.empty())
1732 outs() << " (architecture " << ArchitectureName << ")";
1733 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001734 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001735 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Lang Hamesfc209622016-07-14 02:24:01 +00001736 Error Err;
1737 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001738 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1739 if (!ChildOrErr) {
1740 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001741 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001742 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001743 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001744 if (MachOObjectFile *O =
1745 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1746 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001747 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1748 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001749 }
1750 }
Lang Hamesfc209622016-07-14 02:24:01 +00001751 if (Err)
1752 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001753 } else {
1754 consumeError(AOrErr.takeError());
1755 error("Mach-O universal file: " + Filename + " for architecture " +
1756 StringRef(I->getArchTypeName()) +
1757 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001758 }
1759 }
1760 return;
1761 }
1762 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1763 if (!checkMachOAndArchFlags(O, Filename))
1764 return;
1765 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001766 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001767 } else
1768 errs() << "llvm-objdump: '" << Filename << "': "
1769 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001770 return;
1771 }
1772 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001773}
1774
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001775typedef std::pair<uint64_t, const char *> BindInfoEntry;
1776typedef std::vector<BindInfoEntry> BindTable;
1777typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001778
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001779// The block of info used by the Symbolizer call backs.
1780struct DisassembleInfo {
1781 bool verbose;
1782 MachOObjectFile *O;
1783 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001784 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001785 std::vector<SectionRef> *Sections;
1786 const char *class_name;
1787 const char *selector_name;
1788 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001789 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001790 uint64_t adrp_addr;
1791 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001792 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001793 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001794};
1795
1796// SymbolizerGetOpInfo() is the operand information call back function.
1797// This is called to get the symbolic information for operand(s) of an
1798// instruction when it is being done. This routine does this from
1799// the relocation information, symbol table, etc. That block of information
1800// is a pointer to the struct DisassembleInfo that was passed when the
1801// disassembler context was created and passed to back to here when
1802// called back by the disassembler for instruction operands that could have
1803// relocation information. The address of the instruction containing operand is
1804// at the Pc parameter. The immediate value the operand has is passed in
1805// op_info->Value and is at Offset past the start of the instruction and has a
1806// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1807// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1808// names and addends of the symbolic expression to add for the operand. The
1809// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1810// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001811static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1812 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001813 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1814 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001815 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001816
1817 // Make sure all fields returned are zero if we don't set them.
1818 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1819 op_info->Value = value;
1820
1821 // If the TagType is not the value 1 which it code knows about or if no
1822 // verbose symbolic information is wanted then just return 0, indicating no
1823 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001824 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001825 return 0;
1826
1827 unsigned int Arch = info->O->getArch();
1828 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001829 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1830 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001831 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1832 // TODO:
1833 // Search the external relocation entries of a fully linked image
1834 // (if any) for an entry that matches this segment offset.
1835 // uint32_t seg_offset = (Pc + Offset);
1836 return 0;
1837 }
1838 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1839 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001840 uint32_t sect_addr = info->S.getAddress();
1841 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1842 bool reloc_found = false;
1843 DataRefImpl Rel;
1844 MachO::any_relocation_info RE;
1845 bool isExtern = false;
1846 SymbolRef Symbol;
1847 bool r_scattered = false;
1848 uint32_t r_value, pair_r_value, r_type;
1849 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001850 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001851 if (RelocOffset == sect_offset) {
1852 Rel = Reloc.getRawDataRefImpl();
1853 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001854 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001855 r_scattered = info->O->isRelocationScattered(RE);
1856 if (r_scattered) {
1857 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001858 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1859 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1860 DataRefImpl RelNext = Rel;
1861 info->O->moveRelocationNext(RelNext);
1862 MachO::any_relocation_info RENext;
1863 RENext = info->O->getRelocation(RelNext);
1864 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001865 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001866 else
1867 return 0;
1868 }
1869 } else {
1870 isExtern = info->O->getPlainRelocationExternal(RE);
1871 if (isExtern) {
1872 symbol_iterator RelocSym = Reloc.getSymbol();
1873 Symbol = *RelocSym;
1874 }
1875 }
1876 reloc_found = true;
1877 break;
1878 }
1879 }
1880 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001881 Expected<StringRef> SymName = Symbol.getName();
1882 if (!SymName) {
1883 std::string Buf;
1884 raw_string_ostream OS(Buf);
1885 logAllUnhandledErrors(SymName.takeError(), OS, "");
1886 OS.flush();
1887 report_fatal_error(Buf);
1888 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001889 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001890 op_info->AddSymbol.Present = 1;
1891 op_info->AddSymbol.Name = name;
1892 // For i386 extern relocation entries the value in the instruction is
1893 // the offset from the symbol, and value is already set in op_info->Value.
1894 return 1;
1895 }
1896 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1897 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001898 const char *add = GuessSymbolName(r_value, info->AddrMap);
1899 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001900 uint32_t offset = value - (r_value - pair_r_value);
1901 op_info->AddSymbol.Present = 1;
1902 if (add != nullptr)
1903 op_info->AddSymbol.Name = add;
1904 else
1905 op_info->AddSymbol.Value = r_value;
1906 op_info->SubtractSymbol.Present = 1;
1907 if (sub != nullptr)
1908 op_info->SubtractSymbol.Name = sub;
1909 else
1910 op_info->SubtractSymbol.Value = pair_r_value;
1911 op_info->Value = offset;
1912 return 1;
1913 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001914 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001915 }
1916 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001917 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1918 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001919 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1920 // TODO:
1921 // Search the external relocation entries of a fully linked image
1922 // (if any) for an entry that matches this segment offset.
1923 // uint64_t seg_offset = (Pc + Offset);
1924 return 0;
1925 }
1926 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1927 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001928 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001929 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1930 bool reloc_found = false;
1931 DataRefImpl Rel;
1932 MachO::any_relocation_info RE;
1933 bool isExtern = false;
1934 SymbolRef Symbol;
1935 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001936 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001937 if (RelocOffset == sect_offset) {
1938 Rel = Reloc.getRawDataRefImpl();
1939 RE = info->O->getRelocation(Rel);
1940 // NOTE: Scattered relocations don't exist on x86_64.
1941 isExtern = info->O->getPlainRelocationExternal(RE);
1942 if (isExtern) {
1943 symbol_iterator RelocSym = Reloc.getSymbol();
1944 Symbol = *RelocSym;
1945 }
1946 reloc_found = true;
1947 break;
1948 }
1949 }
1950 if (reloc_found && isExtern) {
1951 // The Value passed in will be adjusted by the Pc if the instruction
1952 // adds the Pc. But for x86_64 external relocation entries the Value
1953 // is the offset from the external symbol.
1954 if (info->O->getAnyRelocationPCRel(RE))
1955 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001956 Expected<StringRef> SymName = Symbol.getName();
1957 if (!SymName) {
1958 std::string Buf;
1959 raw_string_ostream OS(Buf);
1960 logAllUnhandledErrors(SymName.takeError(), OS, "");
1961 OS.flush();
1962 report_fatal_error(Buf);
1963 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001964 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001965 unsigned Type = info->O->getAnyRelocationType(RE);
1966 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1967 DataRefImpl RelNext = Rel;
1968 info->O->moveRelocationNext(RelNext);
1969 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1970 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1971 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1972 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1973 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1974 op_info->SubtractSymbol.Present = 1;
1975 op_info->SubtractSymbol.Name = name;
1976 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1977 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001978 Expected<StringRef> SymNameNext = Symbol.getName();
1979 if (!SymNameNext) {
1980 std::string Buf;
1981 raw_string_ostream OS(Buf);
1982 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1983 OS.flush();
1984 report_fatal_error(Buf);
1985 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001986 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001987 }
1988 }
1989 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1990 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1991 op_info->AddSymbol.Present = 1;
1992 op_info->AddSymbol.Name = name;
1993 return 1;
1994 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001995 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001996 }
1997 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001998 if (Offset != 0 || (Size != 4 && Size != 2))
1999 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002000 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2001 // TODO:
2002 // Search the external relocation entries of a fully linked image
2003 // (if any) for an entry that matches this segment offset.
2004 // uint32_t seg_offset = (Pc + Offset);
2005 return 0;
2006 }
2007 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2008 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002009 uint32_t sect_addr = info->S.getAddress();
2010 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002011 DataRefImpl Rel;
2012 MachO::any_relocation_info RE;
2013 bool isExtern = false;
2014 SymbolRef Symbol;
2015 bool r_scattered = false;
2016 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002017 auto Reloc =
2018 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2019 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002020 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002021 return RelocOffset == sect_offset;
2022 });
2023
2024 if (Reloc == info->S.relocations().end())
2025 return 0;
2026
2027 Rel = Reloc->getRawDataRefImpl();
2028 RE = info->O->getRelocation(Rel);
2029 r_length = info->O->getAnyRelocationLength(RE);
2030 r_scattered = info->O->isRelocationScattered(RE);
2031 if (r_scattered) {
2032 r_value = info->O->getScatteredRelocationValue(RE);
2033 r_type = info->O->getScatteredRelocationType(RE);
2034 } else {
2035 r_type = info->O->getAnyRelocationType(RE);
2036 isExtern = info->O->getPlainRelocationExternal(RE);
2037 if (isExtern) {
2038 symbol_iterator RelocSym = Reloc->getSymbol();
2039 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002040 }
2041 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002042 if (r_type == MachO::ARM_RELOC_HALF ||
2043 r_type == MachO::ARM_RELOC_SECTDIFF ||
2044 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2045 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2046 DataRefImpl RelNext = Rel;
2047 info->O->moveRelocationNext(RelNext);
2048 MachO::any_relocation_info RENext;
2049 RENext = info->O->getRelocation(RelNext);
2050 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2051 if (info->O->isRelocationScattered(RENext))
2052 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2053 }
2054
2055 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002056 Expected<StringRef> SymName = Symbol.getName();
2057 if (!SymName) {
2058 std::string Buf;
2059 raw_string_ostream OS(Buf);
2060 logAllUnhandledErrors(SymName.takeError(), OS, "");
2061 OS.flush();
2062 report_fatal_error(Buf);
2063 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002064 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002065 op_info->AddSymbol.Present = 1;
2066 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002067 switch (r_type) {
2068 case MachO::ARM_RELOC_HALF:
2069 if ((r_length & 0x1) == 1) {
2070 op_info->Value = value << 16 | other_half;
2071 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2072 } else {
2073 op_info->Value = other_half << 16 | value;
2074 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002075 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002076 break;
2077 default:
2078 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002079 }
2080 return 1;
2081 }
2082 // If we have a branch that is not an external relocation entry then
2083 // return 0 so the code in tryAddingSymbolicOperand() can use the
2084 // SymbolLookUp call back with the branch target address to look up the
2085 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002086 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2087 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002088 return 0;
2089
2090 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002091 if (r_type == MachO::ARM_RELOC_HALF ||
2092 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2093 if ((r_length & 0x1) == 1)
2094 value = value << 16 | other_half;
2095 else
2096 value = other_half << 16 | value;
2097 }
2098 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2099 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2100 offset = value - r_value;
2101 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002102 }
2103
David Blaikie33dd45d02015-03-23 18:39:02 +00002104 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002105 if ((r_length & 0x1) == 1)
2106 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2107 else
2108 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002109 const char *add = GuessSymbolName(r_value, info->AddrMap);
2110 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002111 int32_t offset = value - (r_value - pair_r_value);
2112 op_info->AddSymbol.Present = 1;
2113 if (add != nullptr)
2114 op_info->AddSymbol.Name = add;
2115 else
2116 op_info->AddSymbol.Value = r_value;
2117 op_info->SubtractSymbol.Present = 1;
2118 if (sub != nullptr)
2119 op_info->SubtractSymbol.Name = sub;
2120 else
2121 op_info->SubtractSymbol.Value = pair_r_value;
2122 op_info->Value = offset;
2123 return 1;
2124 }
2125
Kevin Enderby930fdc72014-11-06 19:00:13 +00002126 op_info->AddSymbol.Present = 1;
2127 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002128 if (r_type == MachO::ARM_RELOC_HALF) {
2129 if ((r_length & 0x1) == 1)
2130 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2131 else
2132 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002133 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002134 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002135 if (add != nullptr) {
2136 op_info->AddSymbol.Name = add;
2137 return 1;
2138 }
2139 op_info->AddSymbol.Value = value;
2140 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002141 }
2142 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002143 if (Offset != 0 || Size != 4)
2144 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002145 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2146 // TODO:
2147 // Search the external relocation entries of a fully linked image
2148 // (if any) for an entry that matches this segment offset.
2149 // uint64_t seg_offset = (Pc + Offset);
2150 return 0;
2151 }
2152 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2153 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002154 uint64_t sect_addr = info->S.getAddress();
2155 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002156 auto Reloc =
2157 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2158 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002159 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002160 return RelocOffset == sect_offset;
2161 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002162
David Blaikie33dd45d02015-03-23 18:39:02 +00002163 if (Reloc == info->S.relocations().end())
2164 return 0;
2165
2166 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2167 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2168 uint32_t r_type = info->O->getAnyRelocationType(RE);
2169 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2170 DataRefImpl RelNext = Rel;
2171 info->O->moveRelocationNext(RelNext);
2172 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2173 if (value == 0) {
2174 value = info->O->getPlainRelocationSymbolNum(RENext);
2175 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002176 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002177 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002178 // NOTE: Scattered relocations don't exist on arm64.
2179 if (!info->O->getPlainRelocationExternal(RE))
2180 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002181 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2182 if (!SymName) {
2183 std::string Buf;
2184 raw_string_ostream OS(Buf);
2185 logAllUnhandledErrors(SymName.takeError(), OS, "");
2186 OS.flush();
2187 report_fatal_error(Buf);
2188 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002189 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002190 op_info->AddSymbol.Present = 1;
2191 op_info->AddSymbol.Name = name;
2192
2193 switch (r_type) {
2194 case MachO::ARM64_RELOC_PAGE21:
2195 /* @page */
2196 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2197 break;
2198 case MachO::ARM64_RELOC_PAGEOFF12:
2199 /* @pageoff */
2200 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2201 break;
2202 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2203 /* @gotpage */
2204 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2205 break;
2206 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2207 /* @gotpageoff */
2208 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2209 break;
2210 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2211 /* @tvlppage is not implemented in llvm-mc */
2212 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2213 break;
2214 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2215 /* @tvlppageoff is not implemented in llvm-mc */
2216 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2217 break;
2218 default:
2219 case MachO::ARM64_RELOC_BRANCH26:
2220 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2221 break;
2222 }
2223 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002224 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002225 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002226}
2227
Kevin Enderbybf246f52014-09-24 23:08:22 +00002228// GuessCstringPointer is passed the address of what might be a pointer to a
2229// literal string in a cstring section. If that address is in a cstring section
2230// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002231static const char *GuessCstringPointer(uint64_t ReferenceValue,
2232 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002233 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002234 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2235 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2236 for (unsigned J = 0; J < Seg.nsects; ++J) {
2237 MachO::section_64 Sec = info->O->getSection64(Load, J);
2238 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2239 if (section_type == MachO::S_CSTRING_LITERALS &&
2240 ReferenceValue >= Sec.addr &&
2241 ReferenceValue < Sec.addr + Sec.size) {
2242 uint64_t sect_offset = ReferenceValue - Sec.addr;
2243 uint64_t object_offset = Sec.offset + sect_offset;
2244 StringRef MachOContents = info->O->getData();
2245 uint64_t object_size = MachOContents.size();
2246 const char *object_addr = (const char *)MachOContents.data();
2247 if (object_offset < object_size) {
2248 const char *name = object_addr + object_offset;
2249 return name;
2250 } else {
2251 return nullptr;
2252 }
2253 }
2254 }
2255 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2256 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2257 for (unsigned J = 0; J < Seg.nsects; ++J) {
2258 MachO::section Sec = info->O->getSection(Load, J);
2259 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2260 if (section_type == MachO::S_CSTRING_LITERALS &&
2261 ReferenceValue >= Sec.addr &&
2262 ReferenceValue < Sec.addr + Sec.size) {
2263 uint64_t sect_offset = ReferenceValue - Sec.addr;
2264 uint64_t object_offset = Sec.offset + sect_offset;
2265 StringRef MachOContents = info->O->getData();
2266 uint64_t object_size = MachOContents.size();
2267 const char *object_addr = (const char *)MachOContents.data();
2268 if (object_offset < object_size) {
2269 const char *name = object_addr + object_offset;
2270 return name;
2271 } else {
2272 return nullptr;
2273 }
2274 }
2275 }
2276 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002277 }
2278 return nullptr;
2279}
2280
Kevin Enderby85974882014-09-26 22:20:44 +00002281// GuessIndirectSymbol returns the name of the indirect symbol for the
2282// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2283// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2284// symbol name being referenced by the stub or pointer.
2285static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2286 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002287 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2288 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002289 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002290 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2291 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2292 for (unsigned J = 0; J < Seg.nsects; ++J) {
2293 MachO::section_64 Sec = info->O->getSection64(Load, J);
2294 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2295 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2296 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2297 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2298 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2299 section_type == MachO::S_SYMBOL_STUBS) &&
2300 ReferenceValue >= Sec.addr &&
2301 ReferenceValue < Sec.addr + Sec.size) {
2302 uint32_t stride;
2303 if (section_type == MachO::S_SYMBOL_STUBS)
2304 stride = Sec.reserved2;
2305 else
2306 stride = 8;
2307 if (stride == 0)
2308 return nullptr;
2309 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2310 if (index < Dysymtab.nindirectsyms) {
2311 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002312 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002313 if (indirect_symbol < Symtab.nsyms) {
2314 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2315 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002316 Expected<StringRef> SymName = Symbol.getName();
2317 if (!SymName) {
2318 std::string Buf;
2319 raw_string_ostream OS(Buf);
2320 logAllUnhandledErrors(SymName.takeError(), OS, "");
2321 OS.flush();
2322 report_fatal_error(Buf);
2323 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002324 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002325 return name;
2326 }
2327 }
2328 }
2329 }
2330 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2331 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2332 for (unsigned J = 0; J < Seg.nsects; ++J) {
2333 MachO::section Sec = info->O->getSection(Load, J);
2334 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2335 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2336 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2337 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2338 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2339 section_type == MachO::S_SYMBOL_STUBS) &&
2340 ReferenceValue >= Sec.addr &&
2341 ReferenceValue < Sec.addr + Sec.size) {
2342 uint32_t stride;
2343 if (section_type == MachO::S_SYMBOL_STUBS)
2344 stride = Sec.reserved2;
2345 else
2346 stride = 4;
2347 if (stride == 0)
2348 return nullptr;
2349 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2350 if (index < Dysymtab.nindirectsyms) {
2351 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002352 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002353 if (indirect_symbol < Symtab.nsyms) {
2354 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2355 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002356 Expected<StringRef> SymName = Symbol.getName();
2357 if (!SymName) {
2358 std::string Buf;
2359 raw_string_ostream OS(Buf);
2360 logAllUnhandledErrors(SymName.takeError(), OS, "");
2361 OS.flush();
2362 report_fatal_error(Buf);
2363 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002364 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002365 return name;
2366 }
2367 }
2368 }
2369 }
2370 }
Kevin Enderby85974882014-09-26 22:20:44 +00002371 }
2372 return nullptr;
2373}
2374
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002375// method_reference() is called passing it the ReferenceName that might be
2376// a reference it to an Objective-C method call. If so then it allocates and
2377// assembles a method call string with the values last seen and saved in
2378// the DisassembleInfo's class_name and selector_name fields. This is saved
2379// into the method field of the info and any previous string is free'ed.
2380// Then the class_name field in the info is set to nullptr. The method call
2381// string is set into ReferenceName and ReferenceType is set to
2382// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2383// then both ReferenceType and ReferenceName are left unchanged.
2384static void method_reference(struct DisassembleInfo *info,
2385 uint64_t *ReferenceType,
2386 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002387 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002388 if (*ReferenceName != nullptr) {
2389 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002390 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002391 if (info->method != nullptr)
2392 free(info->method);
2393 if (info->class_name != nullptr) {
2394 info->method = (char *)malloc(5 + strlen(info->class_name) +
2395 strlen(info->selector_name));
2396 if (info->method != nullptr) {
2397 strcpy(info->method, "+[");
2398 strcat(info->method, info->class_name);
2399 strcat(info->method, " ");
2400 strcat(info->method, info->selector_name);
2401 strcat(info->method, "]");
2402 *ReferenceName = info->method;
2403 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2404 }
2405 } else {
2406 info->method = (char *)malloc(9 + strlen(info->selector_name));
2407 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002408 if (Arch == Triple::x86_64)
2409 strcpy(info->method, "-[%rdi ");
2410 else if (Arch == Triple::aarch64)
2411 strcpy(info->method, "-[x0 ");
2412 else
2413 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002414 strcat(info->method, info->selector_name);
2415 strcat(info->method, "]");
2416 *ReferenceName = info->method;
2417 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2418 }
2419 }
2420 info->class_name = nullptr;
2421 }
2422 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002423 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002424 if (info->method != nullptr)
2425 free(info->method);
2426 info->method = (char *)malloc(17 + strlen(info->selector_name));
2427 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002428 if (Arch == Triple::x86_64)
2429 strcpy(info->method, "-[[%rdi super] ");
2430 else if (Arch == Triple::aarch64)
2431 strcpy(info->method, "-[[x0 super] ");
2432 else
2433 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002434 strcat(info->method, info->selector_name);
2435 strcat(info->method, "]");
2436 *ReferenceName = info->method;
2437 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2438 }
2439 info->class_name = nullptr;
2440 }
2441 }
2442 }
2443}
2444
2445// GuessPointerPointer() is passed the address of what might be a pointer to
2446// a reference to an Objective-C class, selector, message ref or cfstring.
2447// If so the value of the pointer is returned and one of the booleans are set
2448// to true. If not zero is returned and all the booleans are set to false.
2449static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2450 struct DisassembleInfo *info,
2451 bool &classref, bool &selref, bool &msgref,
2452 bool &cfstring) {
2453 classref = false;
2454 selref = false;
2455 msgref = false;
2456 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002457 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002458 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2459 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2460 for (unsigned J = 0; J < Seg.nsects; ++J) {
2461 MachO::section_64 Sec = info->O->getSection64(Load, J);
2462 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2463 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2464 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2465 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2466 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2467 ReferenceValue >= Sec.addr &&
2468 ReferenceValue < Sec.addr + Sec.size) {
2469 uint64_t sect_offset = ReferenceValue - Sec.addr;
2470 uint64_t object_offset = Sec.offset + sect_offset;
2471 StringRef MachOContents = info->O->getData();
2472 uint64_t object_size = MachOContents.size();
2473 const char *object_addr = (const char *)MachOContents.data();
2474 if (object_offset < object_size) {
2475 uint64_t pointer_value;
2476 memcpy(&pointer_value, object_addr + object_offset,
2477 sizeof(uint64_t));
2478 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2479 sys::swapByteOrder(pointer_value);
2480 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2481 selref = true;
2482 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2483 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2484 classref = true;
2485 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2486 ReferenceValue + 8 < Sec.addr + Sec.size) {
2487 msgref = true;
2488 memcpy(&pointer_value, object_addr + object_offset + 8,
2489 sizeof(uint64_t));
2490 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2491 sys::swapByteOrder(pointer_value);
2492 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2493 cfstring = true;
2494 return pointer_value;
2495 } else {
2496 return 0;
2497 }
2498 }
2499 }
2500 }
2501 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002502 }
2503 return 0;
2504}
2505
2506// get_pointer_64 returns a pointer to the bytes in the object file at the
2507// Address from a section in the Mach-O file. And indirectly returns the
2508// offset into the section, number of bytes left in the section past the offset
2509// and which section is was being referenced. If the Address is not in a
2510// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002511static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2512 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002513 DisassembleInfo *info,
2514 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002515 offset = 0;
2516 left = 0;
2517 S = SectionRef();
2518 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2519 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2520 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002521 if (SectSize == 0)
2522 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002523 if (objc_only) {
2524 StringRef SectName;
2525 ((*(info->Sections))[SectIdx]).getName(SectName);
2526 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2527 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2528 if (SegName != "__OBJC" && SectName != "__cstring")
2529 continue;
2530 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002531 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2532 S = (*(info->Sections))[SectIdx];
2533 offset = Address - SectAddress;
2534 left = SectSize - offset;
2535 StringRef SectContents;
2536 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2537 return SectContents.data() + offset;
2538 }
2539 }
2540 return nullptr;
2541}
2542
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002543static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2544 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002545 DisassembleInfo *info,
2546 bool objc_only = false) {
2547 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002548}
2549
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002550// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2551// the symbol indirectly through n_value. Based on the relocation information
2552// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002553// If no relocation information is found and a non-zero ReferenceValue for the
2554// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002555static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2556 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002557 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002558 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002559 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002560 return nullptr;
2561
2562 // See if there is an external relocation entry at the sect_offset.
2563 bool reloc_found = false;
2564 DataRefImpl Rel;
2565 MachO::any_relocation_info RE;
2566 bool isExtern = false;
2567 SymbolRef Symbol;
2568 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002569 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002570 if (RelocOffset == sect_offset) {
2571 Rel = Reloc.getRawDataRefImpl();
2572 RE = info->O->getRelocation(Rel);
2573 if (info->O->isRelocationScattered(RE))
2574 continue;
2575 isExtern = info->O->getPlainRelocationExternal(RE);
2576 if (isExtern) {
2577 symbol_iterator RelocSym = Reloc.getSymbol();
2578 Symbol = *RelocSym;
2579 }
2580 reloc_found = true;
2581 break;
2582 }
2583 }
2584 // If there is an external relocation entry for a symbol in this section
2585 // at this section_offset then use that symbol's value for the n_value
2586 // and return its name.
2587 const char *SymbolName = nullptr;
2588 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002589 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002590 Expected<StringRef> NameOrError = Symbol.getName();
2591 if (!NameOrError) {
2592 std::string Buf;
2593 raw_string_ostream OS(Buf);
2594 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2595 OS.flush();
2596 report_fatal_error(Buf);
2597 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002598 StringRef Name = *NameOrError;
2599 if (!Name.empty()) {
2600 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002601 return SymbolName;
2602 }
2603 }
2604
2605 // TODO: For fully linked images, look through the external relocation
2606 // entries off the dynamic symtab command. For these the r_offset is from the
2607 // start of the first writeable segment in the Mach-O file. So the offset
2608 // to this section from that segment is passed to this routine by the caller,
2609 // as the database_offset. Which is the difference of the section's starting
2610 // address and the first writable segment.
2611 //
2612 // NOTE: need add passing the database_offset to this routine.
2613
Kevin Enderby0fc11822015-04-01 20:57:01 +00002614 // We did not find an external relocation entry so look up the ReferenceValue
2615 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002616 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002617
2618 return SymbolName;
2619}
2620
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002621static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2622 DisassembleInfo *info,
2623 uint32_t ReferenceValue) {
2624 uint64_t n_value64;
2625 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2626}
2627
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002628// These are structs in the Objective-C meta data and read to produce the
2629// comments for disassembly. While these are part of the ABI they are no
2630// public defintions. So the are here not in include/llvm/Support/MachO.h .
2631
2632// The cfstring object in a 64-bit Mach-O file.
2633struct cfstring64_t {
2634 uint64_t isa; // class64_t * (64-bit pointer)
2635 uint64_t flags; // flag bits
2636 uint64_t characters; // char * (64-bit pointer)
2637 uint64_t length; // number of non-NULL characters in above
2638};
2639
2640// The class object in a 64-bit Mach-O file.
2641struct class64_t {
2642 uint64_t isa; // class64_t * (64-bit pointer)
2643 uint64_t superclass; // class64_t * (64-bit pointer)
2644 uint64_t cache; // Cache (64-bit pointer)
2645 uint64_t vtable; // IMP * (64-bit pointer)
2646 uint64_t data; // class_ro64_t * (64-bit pointer)
2647};
2648
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002649struct class32_t {
2650 uint32_t isa; /* class32_t * (32-bit pointer) */
2651 uint32_t superclass; /* class32_t * (32-bit pointer) */
2652 uint32_t cache; /* Cache (32-bit pointer) */
2653 uint32_t vtable; /* IMP * (32-bit pointer) */
2654 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2655};
2656
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002657struct class_ro64_t {
2658 uint32_t flags;
2659 uint32_t instanceStart;
2660 uint32_t instanceSize;
2661 uint32_t reserved;
2662 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2663 uint64_t name; // const char * (64-bit pointer)
2664 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2665 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2666 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2667 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2668 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2669};
2670
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002671struct class_ro32_t {
2672 uint32_t flags;
2673 uint32_t instanceStart;
2674 uint32_t instanceSize;
2675 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2676 uint32_t name; /* const char * (32-bit pointer) */
2677 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2678 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2679 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2680 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2681 uint32_t baseProperties; /* const struct objc_property_list *
2682 (32-bit pointer) */
2683};
2684
2685/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002686#define RO_META (1 << 0)
2687#define RO_ROOT (1 << 1)
2688#define RO_HAS_CXX_STRUCTORS (1 << 2)
2689
2690struct method_list64_t {
2691 uint32_t entsize;
2692 uint32_t count;
2693 /* struct method64_t first; These structures follow inline */
2694};
2695
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002696struct method_list32_t {
2697 uint32_t entsize;
2698 uint32_t count;
2699 /* struct method32_t first; These structures follow inline */
2700};
2701
Kevin Enderby0fc11822015-04-01 20:57:01 +00002702struct method64_t {
2703 uint64_t name; /* SEL (64-bit pointer) */
2704 uint64_t types; /* const char * (64-bit pointer) */
2705 uint64_t imp; /* IMP (64-bit pointer) */
2706};
2707
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002708struct method32_t {
2709 uint32_t name; /* SEL (32-bit pointer) */
2710 uint32_t types; /* const char * (32-bit pointer) */
2711 uint32_t imp; /* IMP (32-bit pointer) */
2712};
2713
Kevin Enderby0fc11822015-04-01 20:57:01 +00002714struct protocol_list64_t {
2715 uint64_t count; /* uintptr_t (a 64-bit value) */
2716 /* struct protocol64_t * list[0]; These pointers follow inline */
2717};
2718
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002719struct protocol_list32_t {
2720 uint32_t count; /* uintptr_t (a 32-bit value) */
2721 /* struct protocol32_t * list[0]; These pointers follow inline */
2722};
2723
Kevin Enderby0fc11822015-04-01 20:57:01 +00002724struct protocol64_t {
2725 uint64_t isa; /* id * (64-bit pointer) */
2726 uint64_t name; /* const char * (64-bit pointer) */
2727 uint64_t protocols; /* struct protocol_list64_t *
2728 (64-bit pointer) */
2729 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2730 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2731 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2732 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2733 uint64_t instanceProperties; /* struct objc_property_list *
2734 (64-bit pointer) */
2735};
2736
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002737struct protocol32_t {
2738 uint32_t isa; /* id * (32-bit pointer) */
2739 uint32_t name; /* const char * (32-bit pointer) */
2740 uint32_t protocols; /* struct protocol_list_t *
2741 (32-bit pointer) */
2742 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2743 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2744 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2745 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2746 uint32_t instanceProperties; /* struct objc_property_list *
2747 (32-bit pointer) */
2748};
2749
Kevin Enderby0fc11822015-04-01 20:57:01 +00002750struct ivar_list64_t {
2751 uint32_t entsize;
2752 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002753 /* struct ivar64_t first; These structures follow inline */
2754};
2755
2756struct ivar_list32_t {
2757 uint32_t entsize;
2758 uint32_t count;
2759 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002760};
2761
2762struct ivar64_t {
2763 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2764 uint64_t name; /* const char * (64-bit pointer) */
2765 uint64_t type; /* const char * (64-bit pointer) */
2766 uint32_t alignment;
2767 uint32_t size;
2768};
2769
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002770struct ivar32_t {
2771 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2772 uint32_t name; /* const char * (32-bit pointer) */
2773 uint32_t type; /* const char * (32-bit pointer) */
2774 uint32_t alignment;
2775 uint32_t size;
2776};
2777
Kevin Enderby0fc11822015-04-01 20:57:01 +00002778struct objc_property_list64 {
2779 uint32_t entsize;
2780 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002781 /* struct objc_property64 first; These structures follow inline */
2782};
2783
2784struct objc_property_list32 {
2785 uint32_t entsize;
2786 uint32_t count;
2787 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002788};
2789
2790struct objc_property64 {
2791 uint64_t name; /* const char * (64-bit pointer) */
2792 uint64_t attributes; /* const char * (64-bit pointer) */
2793};
2794
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002795struct objc_property32 {
2796 uint32_t name; /* const char * (32-bit pointer) */
2797 uint32_t attributes; /* const char * (32-bit pointer) */
2798};
2799
Kevin Enderby0fc11822015-04-01 20:57:01 +00002800struct category64_t {
2801 uint64_t name; /* const char * (64-bit pointer) */
2802 uint64_t cls; /* struct class_t * (64-bit pointer) */
2803 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2804 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2805 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2806 uint64_t instanceProperties; /* struct objc_property_list *
2807 (64-bit pointer) */
2808};
2809
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002810struct category32_t {
2811 uint32_t name; /* const char * (32-bit pointer) */
2812 uint32_t cls; /* struct class_t * (32-bit pointer) */
2813 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2814 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2815 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2816 uint32_t instanceProperties; /* struct objc_property_list *
2817 (32-bit pointer) */
2818};
2819
Kevin Enderby0fc11822015-04-01 20:57:01 +00002820struct objc_image_info64 {
2821 uint32_t version;
2822 uint32_t flags;
2823};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002824struct objc_image_info32 {
2825 uint32_t version;
2826 uint32_t flags;
2827};
Kevin Enderby846c0002015-04-16 17:19:59 +00002828struct imageInfo_t {
2829 uint32_t version;
2830 uint32_t flags;
2831};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002832/* masks for objc_image_info.flags */
2833#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2834#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2835
2836struct message_ref64 {
2837 uint64_t imp; /* IMP (64-bit pointer) */
2838 uint64_t sel; /* SEL (64-bit pointer) */
2839};
2840
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002841struct message_ref32 {
2842 uint32_t imp; /* IMP (32-bit pointer) */
2843 uint32_t sel; /* SEL (32-bit pointer) */
2844};
2845
Kevin Enderby846c0002015-04-16 17:19:59 +00002846// Objective-C 1 (32-bit only) meta data structs.
2847
2848struct objc_module_t {
2849 uint32_t version;
2850 uint32_t size;
2851 uint32_t name; /* char * (32-bit pointer) */
2852 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2853};
2854
2855struct objc_symtab_t {
2856 uint32_t sel_ref_cnt;
2857 uint32_t refs; /* SEL * (32-bit pointer) */
2858 uint16_t cls_def_cnt;
2859 uint16_t cat_def_cnt;
2860 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2861};
2862
2863struct objc_class_t {
2864 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2865 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2866 uint32_t name; /* const char * (32-bit pointer) */
2867 int32_t version;
2868 int32_t info;
2869 int32_t instance_size;
2870 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2871 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2872 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2873 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2874};
2875
2876#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2877// class is not a metaclass
2878#define CLS_CLASS 0x1
2879// class is a metaclass
2880#define CLS_META 0x2
2881
2882struct objc_category_t {
2883 uint32_t category_name; /* char * (32-bit pointer) */
2884 uint32_t class_name; /* char * (32-bit pointer) */
2885 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2886 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2887 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2888};
2889
2890struct objc_ivar_t {
2891 uint32_t ivar_name; /* char * (32-bit pointer) */
2892 uint32_t ivar_type; /* char * (32-bit pointer) */
2893 int32_t ivar_offset;
2894};
2895
2896struct objc_ivar_list_t {
2897 int32_t ivar_count;
2898 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2899};
2900
2901struct objc_method_list_t {
2902 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2903 int32_t method_count;
2904 // struct objc_method_t method_list[1]; /* variable length structure */
2905};
2906
2907struct objc_method_t {
2908 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2909 uint32_t method_types; /* char * (32-bit pointer) */
2910 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2911 (32-bit pointer) */
2912};
2913
2914struct objc_protocol_list_t {
2915 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2916 int32_t count;
2917 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2918 // (32-bit pointer) */
2919};
2920
2921struct objc_protocol_t {
2922 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2923 uint32_t protocol_name; /* char * (32-bit pointer) */
2924 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2925 uint32_t instance_methods; /* struct objc_method_description_list *
2926 (32-bit pointer) */
2927 uint32_t class_methods; /* struct objc_method_description_list *
2928 (32-bit pointer) */
2929};
2930
2931struct objc_method_description_list_t {
2932 int32_t count;
2933 // struct objc_method_description_t list[1];
2934};
2935
2936struct objc_method_description_t {
2937 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2938 uint32_t types; /* char * (32-bit pointer) */
2939};
2940
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002941inline void swapStruct(struct cfstring64_t &cfs) {
2942 sys::swapByteOrder(cfs.isa);
2943 sys::swapByteOrder(cfs.flags);
2944 sys::swapByteOrder(cfs.characters);
2945 sys::swapByteOrder(cfs.length);
2946}
2947
2948inline void swapStruct(struct class64_t &c) {
2949 sys::swapByteOrder(c.isa);
2950 sys::swapByteOrder(c.superclass);
2951 sys::swapByteOrder(c.cache);
2952 sys::swapByteOrder(c.vtable);
2953 sys::swapByteOrder(c.data);
2954}
2955
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002956inline void swapStruct(struct class32_t &c) {
2957 sys::swapByteOrder(c.isa);
2958 sys::swapByteOrder(c.superclass);
2959 sys::swapByteOrder(c.cache);
2960 sys::swapByteOrder(c.vtable);
2961 sys::swapByteOrder(c.data);
2962}
2963
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002964inline void swapStruct(struct class_ro64_t &cro) {
2965 sys::swapByteOrder(cro.flags);
2966 sys::swapByteOrder(cro.instanceStart);
2967 sys::swapByteOrder(cro.instanceSize);
2968 sys::swapByteOrder(cro.reserved);
2969 sys::swapByteOrder(cro.ivarLayout);
2970 sys::swapByteOrder(cro.name);
2971 sys::swapByteOrder(cro.baseMethods);
2972 sys::swapByteOrder(cro.baseProtocols);
2973 sys::swapByteOrder(cro.ivars);
2974 sys::swapByteOrder(cro.weakIvarLayout);
2975 sys::swapByteOrder(cro.baseProperties);
2976}
2977
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002978inline void swapStruct(struct class_ro32_t &cro) {
2979 sys::swapByteOrder(cro.flags);
2980 sys::swapByteOrder(cro.instanceStart);
2981 sys::swapByteOrder(cro.instanceSize);
2982 sys::swapByteOrder(cro.ivarLayout);
2983 sys::swapByteOrder(cro.name);
2984 sys::swapByteOrder(cro.baseMethods);
2985 sys::swapByteOrder(cro.baseProtocols);
2986 sys::swapByteOrder(cro.ivars);
2987 sys::swapByteOrder(cro.weakIvarLayout);
2988 sys::swapByteOrder(cro.baseProperties);
2989}
2990
Kevin Enderby0fc11822015-04-01 20:57:01 +00002991inline void swapStruct(struct method_list64_t &ml) {
2992 sys::swapByteOrder(ml.entsize);
2993 sys::swapByteOrder(ml.count);
2994}
2995
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002996inline void swapStruct(struct method_list32_t &ml) {
2997 sys::swapByteOrder(ml.entsize);
2998 sys::swapByteOrder(ml.count);
2999}
3000
Kevin Enderby0fc11822015-04-01 20:57:01 +00003001inline void swapStruct(struct method64_t &m) {
3002 sys::swapByteOrder(m.name);
3003 sys::swapByteOrder(m.types);
3004 sys::swapByteOrder(m.imp);
3005}
3006
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003007inline void swapStruct(struct method32_t &m) {
3008 sys::swapByteOrder(m.name);
3009 sys::swapByteOrder(m.types);
3010 sys::swapByteOrder(m.imp);
3011}
3012
Kevin Enderby0fc11822015-04-01 20:57:01 +00003013inline void swapStruct(struct protocol_list64_t &pl) {
3014 sys::swapByteOrder(pl.count);
3015}
3016
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003017inline void swapStruct(struct protocol_list32_t &pl) {
3018 sys::swapByteOrder(pl.count);
3019}
3020
Kevin Enderby0fc11822015-04-01 20:57:01 +00003021inline void swapStruct(struct protocol64_t &p) {
3022 sys::swapByteOrder(p.isa);
3023 sys::swapByteOrder(p.name);
3024 sys::swapByteOrder(p.protocols);
3025 sys::swapByteOrder(p.instanceMethods);
3026 sys::swapByteOrder(p.classMethods);
3027 sys::swapByteOrder(p.optionalInstanceMethods);
3028 sys::swapByteOrder(p.optionalClassMethods);
3029 sys::swapByteOrder(p.instanceProperties);
3030}
3031
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003032inline void swapStruct(struct protocol32_t &p) {
3033 sys::swapByteOrder(p.isa);
3034 sys::swapByteOrder(p.name);
3035 sys::swapByteOrder(p.protocols);
3036 sys::swapByteOrder(p.instanceMethods);
3037 sys::swapByteOrder(p.classMethods);
3038 sys::swapByteOrder(p.optionalInstanceMethods);
3039 sys::swapByteOrder(p.optionalClassMethods);
3040 sys::swapByteOrder(p.instanceProperties);
3041}
3042
Kevin Enderby0fc11822015-04-01 20:57:01 +00003043inline void swapStruct(struct ivar_list64_t &il) {
3044 sys::swapByteOrder(il.entsize);
3045 sys::swapByteOrder(il.count);
3046}
3047
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003048inline void swapStruct(struct ivar_list32_t &il) {
3049 sys::swapByteOrder(il.entsize);
3050 sys::swapByteOrder(il.count);
3051}
3052
Kevin Enderby0fc11822015-04-01 20:57:01 +00003053inline void swapStruct(struct ivar64_t &i) {
3054 sys::swapByteOrder(i.offset);
3055 sys::swapByteOrder(i.name);
3056 sys::swapByteOrder(i.type);
3057 sys::swapByteOrder(i.alignment);
3058 sys::swapByteOrder(i.size);
3059}
3060
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003061inline void swapStruct(struct ivar32_t &i) {
3062 sys::swapByteOrder(i.offset);
3063 sys::swapByteOrder(i.name);
3064 sys::swapByteOrder(i.type);
3065 sys::swapByteOrder(i.alignment);
3066 sys::swapByteOrder(i.size);
3067}
3068
Kevin Enderby0fc11822015-04-01 20:57:01 +00003069inline void swapStruct(struct objc_property_list64 &pl) {
3070 sys::swapByteOrder(pl.entsize);
3071 sys::swapByteOrder(pl.count);
3072}
3073
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003074inline void swapStruct(struct objc_property_list32 &pl) {
3075 sys::swapByteOrder(pl.entsize);
3076 sys::swapByteOrder(pl.count);
3077}
3078
Kevin Enderby0fc11822015-04-01 20:57:01 +00003079inline void swapStruct(struct objc_property64 &op) {
3080 sys::swapByteOrder(op.name);
3081 sys::swapByteOrder(op.attributes);
3082}
3083
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003084inline void swapStruct(struct objc_property32 &op) {
3085 sys::swapByteOrder(op.name);
3086 sys::swapByteOrder(op.attributes);
3087}
3088
Kevin Enderby0fc11822015-04-01 20:57:01 +00003089inline void swapStruct(struct category64_t &c) {
3090 sys::swapByteOrder(c.name);
3091 sys::swapByteOrder(c.cls);
3092 sys::swapByteOrder(c.instanceMethods);
3093 sys::swapByteOrder(c.classMethods);
3094 sys::swapByteOrder(c.protocols);
3095 sys::swapByteOrder(c.instanceProperties);
3096}
3097
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003098inline void swapStruct(struct category32_t &c) {
3099 sys::swapByteOrder(c.name);
3100 sys::swapByteOrder(c.cls);
3101 sys::swapByteOrder(c.instanceMethods);
3102 sys::swapByteOrder(c.classMethods);
3103 sys::swapByteOrder(c.protocols);
3104 sys::swapByteOrder(c.instanceProperties);
3105}
3106
Kevin Enderby0fc11822015-04-01 20:57:01 +00003107inline void swapStruct(struct objc_image_info64 &o) {
3108 sys::swapByteOrder(o.version);
3109 sys::swapByteOrder(o.flags);
3110}
3111
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003112inline void swapStruct(struct objc_image_info32 &o) {
3113 sys::swapByteOrder(o.version);
3114 sys::swapByteOrder(o.flags);
3115}
3116
Kevin Enderby846c0002015-04-16 17:19:59 +00003117inline void swapStruct(struct imageInfo_t &o) {
3118 sys::swapByteOrder(o.version);
3119 sys::swapByteOrder(o.flags);
3120}
3121
Kevin Enderby0fc11822015-04-01 20:57:01 +00003122inline void swapStruct(struct message_ref64 &mr) {
3123 sys::swapByteOrder(mr.imp);
3124 sys::swapByteOrder(mr.sel);
3125}
3126
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003127inline void swapStruct(struct message_ref32 &mr) {
3128 sys::swapByteOrder(mr.imp);
3129 sys::swapByteOrder(mr.sel);
3130}
3131
Kevin Enderby846c0002015-04-16 17:19:59 +00003132inline void swapStruct(struct objc_module_t &module) {
3133 sys::swapByteOrder(module.version);
3134 sys::swapByteOrder(module.size);
3135 sys::swapByteOrder(module.name);
3136 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003137}
Kevin Enderby846c0002015-04-16 17:19:59 +00003138
3139inline void swapStruct(struct objc_symtab_t &symtab) {
3140 sys::swapByteOrder(symtab.sel_ref_cnt);
3141 sys::swapByteOrder(symtab.refs);
3142 sys::swapByteOrder(symtab.cls_def_cnt);
3143 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003144}
Kevin Enderby846c0002015-04-16 17:19:59 +00003145
3146inline void swapStruct(struct objc_class_t &objc_class) {
3147 sys::swapByteOrder(objc_class.isa);
3148 sys::swapByteOrder(objc_class.super_class);
3149 sys::swapByteOrder(objc_class.name);
3150 sys::swapByteOrder(objc_class.version);
3151 sys::swapByteOrder(objc_class.info);
3152 sys::swapByteOrder(objc_class.instance_size);
3153 sys::swapByteOrder(objc_class.ivars);
3154 sys::swapByteOrder(objc_class.methodLists);
3155 sys::swapByteOrder(objc_class.cache);
3156 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003157}
Kevin Enderby846c0002015-04-16 17:19:59 +00003158
3159inline void swapStruct(struct objc_category_t &objc_category) {
3160 sys::swapByteOrder(objc_category.category_name);
3161 sys::swapByteOrder(objc_category.class_name);
3162 sys::swapByteOrder(objc_category.instance_methods);
3163 sys::swapByteOrder(objc_category.class_methods);
3164 sys::swapByteOrder(objc_category.protocols);
3165}
3166
3167inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3168 sys::swapByteOrder(objc_ivar_list.ivar_count);
3169}
3170
3171inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3172 sys::swapByteOrder(objc_ivar.ivar_name);
3173 sys::swapByteOrder(objc_ivar.ivar_type);
3174 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003175}
Kevin Enderby846c0002015-04-16 17:19:59 +00003176
3177inline void swapStruct(struct objc_method_list_t &method_list) {
3178 sys::swapByteOrder(method_list.obsolete);
3179 sys::swapByteOrder(method_list.method_count);
3180}
3181
3182inline void swapStruct(struct objc_method_t &method) {
3183 sys::swapByteOrder(method.method_name);
3184 sys::swapByteOrder(method.method_types);
3185 sys::swapByteOrder(method.method_imp);
3186}
3187
3188inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3189 sys::swapByteOrder(protocol_list.next);
3190 sys::swapByteOrder(protocol_list.count);
3191}
3192
3193inline void swapStruct(struct objc_protocol_t &protocol) {
3194 sys::swapByteOrder(protocol.isa);
3195 sys::swapByteOrder(protocol.protocol_name);
3196 sys::swapByteOrder(protocol.protocol_list);
3197 sys::swapByteOrder(protocol.instance_methods);
3198 sys::swapByteOrder(protocol.class_methods);
3199}
3200
3201inline void swapStruct(struct objc_method_description_list_t &mdl) {
3202 sys::swapByteOrder(mdl.count);
3203}
3204
3205inline void swapStruct(struct objc_method_description_t &md) {
3206 sys::swapByteOrder(md.name);
3207 sys::swapByteOrder(md.types);
3208}
3209
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003210static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3211 struct DisassembleInfo *info);
3212
3213// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3214// to an Objective-C class and returns the class name. It is also passed the
3215// address of the pointer, so when the pointer is zero as it can be in an .o
3216// file, that is used to look for an external relocation entry with a symbol
3217// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003218static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3219 uint64_t ReferenceValue,
3220 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003221 const char *r;
3222 uint32_t offset, left;
3223 SectionRef S;
3224
3225 // The pointer_value can be 0 in an object file and have a relocation
3226 // entry for the class symbol at the ReferenceValue (the address of the
3227 // pointer).
3228 if (pointer_value == 0) {
3229 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3230 if (r == nullptr || left < sizeof(uint64_t))
3231 return nullptr;
3232 uint64_t n_value;
3233 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3234 if (symbol_name == nullptr)
3235 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003236 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003237 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3238 return class_name + 2;
3239 else
3240 return nullptr;
3241 }
3242
3243 // The case were the pointer_value is non-zero and points to a class defined
3244 // in this Mach-O file.
3245 r = get_pointer_64(pointer_value, offset, left, S, info);
3246 if (r == nullptr || left < sizeof(struct class64_t))
3247 return nullptr;
3248 struct class64_t c;
3249 memcpy(&c, r, sizeof(struct class64_t));
3250 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3251 swapStruct(c);
3252 if (c.data == 0)
3253 return nullptr;
3254 r = get_pointer_64(c.data, offset, left, S, info);
3255 if (r == nullptr || left < sizeof(struct class_ro64_t))
3256 return nullptr;
3257 struct class_ro64_t cro;
3258 memcpy(&cro, r, sizeof(struct class_ro64_t));
3259 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3260 swapStruct(cro);
3261 if (cro.name == 0)
3262 return nullptr;
3263 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3264 return name;
3265}
3266
3267// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3268// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003269static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3270 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003271 const char *r, *name;
3272 uint32_t offset, left;
3273 SectionRef S;
3274 struct cfstring64_t cfs;
3275 uint64_t cfs_characters;
3276
3277 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3278 if (r == nullptr || left < sizeof(struct cfstring64_t))
3279 return nullptr;
3280 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3281 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3282 swapStruct(cfs);
3283 if (cfs.characters == 0) {
3284 uint64_t n_value;
3285 const char *symbol_name = get_symbol_64(
3286 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3287 if (symbol_name == nullptr)
3288 return nullptr;
3289 cfs_characters = n_value;
3290 } else
3291 cfs_characters = cfs.characters;
3292 name = get_pointer_64(cfs_characters, offset, left, S, info);
3293
3294 return name;
3295}
3296
3297// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3298// of a pointer to an Objective-C selector reference when the pointer value is
3299// zero as in a .o file and is likely to have a external relocation entry with
3300// who's symbol's n_value is the real pointer to the selector name. If that is
3301// the case the real pointer to the selector name is returned else 0 is
3302// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003303static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3304 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003305 uint32_t offset, left;
3306 SectionRef S;
3307
3308 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3309 if (r == nullptr || left < sizeof(uint64_t))
3310 return 0;
3311 uint64_t n_value;
3312 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3313 if (symbol_name == nullptr)
3314 return 0;
3315 return n_value;
3316}
3317
Kevin Enderby0fc11822015-04-01 20:57:01 +00003318static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3319 const char *sectname) {
3320 for (const SectionRef &Section : O->sections()) {
3321 StringRef SectName;
3322 Section.getName(SectName);
3323 DataRefImpl Ref = Section.getRawDataRefImpl();
3324 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3325 if (SegName == segname && SectName == sectname)
3326 return Section;
3327 }
3328 return SectionRef();
3329}
3330
3331static void
3332walk_pointer_list_64(const char *listname, const SectionRef S,
3333 MachOObjectFile *O, struct DisassembleInfo *info,
3334 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3335 if (S == SectionRef())
3336 return;
3337
3338 StringRef SectName;
3339 S.getName(SectName);
3340 DataRefImpl Ref = S.getRawDataRefImpl();
3341 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3342 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3343
3344 StringRef BytesStr;
3345 S.getContents(BytesStr);
3346 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3347
3348 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3349 uint32_t left = S.getSize() - i;
3350 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3351 uint64_t p = 0;
3352 memcpy(&p, Contents + i, size);
3353 if (i + sizeof(uint64_t) > S.getSize())
3354 outs() << listname << " list pointer extends past end of (" << SegName
3355 << "," << SectName << ") section\n";
3356 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3357
3358 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3359 sys::swapByteOrder(p);
3360
3361 uint64_t n_value = 0;
3362 const char *name = get_symbol_64(i, S, info, n_value, p);
3363 if (name == nullptr)
3364 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3365
3366 if (n_value != 0) {
3367 outs() << format("0x%" PRIx64, n_value);
3368 if (p != 0)
3369 outs() << " + " << format("0x%" PRIx64, p);
3370 } else
3371 outs() << format("0x%" PRIx64, p);
3372 if (name != nullptr)
3373 outs() << " " << name;
3374 outs() << "\n";
3375
3376 p += n_value;
3377 if (func)
3378 func(p, info);
3379 }
3380}
3381
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003382static void
3383walk_pointer_list_32(const char *listname, const SectionRef S,
3384 MachOObjectFile *O, struct DisassembleInfo *info,
3385 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3386 if (S == SectionRef())
3387 return;
3388
3389 StringRef SectName;
3390 S.getName(SectName);
3391 DataRefImpl Ref = S.getRawDataRefImpl();
3392 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3393 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3394
3395 StringRef BytesStr;
3396 S.getContents(BytesStr);
3397 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3398
3399 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3400 uint32_t left = S.getSize() - i;
3401 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3402 uint32_t p = 0;
3403 memcpy(&p, Contents + i, size);
3404 if (i + sizeof(uint32_t) > S.getSize())
3405 outs() << listname << " list pointer extends past end of (" << SegName
3406 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003407 uint32_t Address = S.getAddress() + i;
3408 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003409
3410 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3411 sys::swapByteOrder(p);
3412 outs() << format("0x%" PRIx32, p);
3413
3414 const char *name = get_symbol_32(i, S, info, p);
3415 if (name != nullptr)
3416 outs() << " " << name;
3417 outs() << "\n";
3418
3419 if (func)
3420 func(p, info);
3421 }
3422}
3423
3424static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003425 if (layout_map == nullptr)
3426 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003427 outs() << " layout map: ";
3428 do {
3429 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3430 left--;
3431 layout_map++;
3432 } while (*layout_map != '\0' && left != 0);
3433 outs() << "\n";
3434}
3435
Kevin Enderby0fc11822015-04-01 20:57:01 +00003436static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3437 uint32_t offset, left;
3438 SectionRef S;
3439 const char *layout_map;
3440
3441 if (p == 0)
3442 return;
3443 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003444 print_layout_map(layout_map, left);
3445}
3446
3447static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3448 uint32_t offset, left;
3449 SectionRef S;
3450 const char *layout_map;
3451
3452 if (p == 0)
3453 return;
3454 layout_map = get_pointer_32(p, offset, left, S, info);
3455 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003456}
3457
3458static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3459 const char *indent) {
3460 struct method_list64_t ml;
3461 struct method64_t m;
3462 const char *r;
3463 uint32_t offset, xoffset, left, i;
3464 SectionRef S, xS;
3465 const char *name, *sym_name;
3466 uint64_t n_value;
3467
3468 r = get_pointer_64(p, offset, left, S, info);
3469 if (r == nullptr)
3470 return;
3471 memset(&ml, '\0', sizeof(struct method_list64_t));
3472 if (left < sizeof(struct method_list64_t)) {
3473 memcpy(&ml, r, left);
3474 outs() << " (method_list_t entends past the end of the section)\n";
3475 } else
3476 memcpy(&ml, r, sizeof(struct method_list64_t));
3477 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3478 swapStruct(ml);
3479 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3480 outs() << indent << "\t\t count " << ml.count << "\n";
3481
3482 p += sizeof(struct method_list64_t);
3483 offset += sizeof(struct method_list64_t);
3484 for (i = 0; i < ml.count; i++) {
3485 r = get_pointer_64(p, offset, left, S, info);
3486 if (r == nullptr)
3487 return;
3488 memset(&m, '\0', sizeof(struct method64_t));
3489 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003490 memcpy(&m, r, left);
3491 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003492 } else
3493 memcpy(&m, r, sizeof(struct method64_t));
3494 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3495 swapStruct(m);
3496
3497 outs() << indent << "\t\t name ";
3498 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3499 info, n_value, m.name);
3500 if (n_value != 0) {
3501 if (info->verbose && sym_name != nullptr)
3502 outs() << sym_name;
3503 else
3504 outs() << format("0x%" PRIx64, n_value);
3505 if (m.name != 0)
3506 outs() << " + " << format("0x%" PRIx64, m.name);
3507 } else
3508 outs() << format("0x%" PRIx64, m.name);
3509 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3510 if (name != nullptr)
3511 outs() << format(" %.*s", left, name);
3512 outs() << "\n";
3513
3514 outs() << indent << "\t\t types ";
3515 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3516 info, n_value, m.types);
3517 if (n_value != 0) {
3518 if (info->verbose && sym_name != nullptr)
3519 outs() << sym_name;
3520 else
3521 outs() << format("0x%" PRIx64, n_value);
3522 if (m.types != 0)
3523 outs() << " + " << format("0x%" PRIx64, m.types);
3524 } else
3525 outs() << format("0x%" PRIx64, m.types);
3526 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3527 if (name != nullptr)
3528 outs() << format(" %.*s", left, name);
3529 outs() << "\n";
3530
3531 outs() << indent << "\t\t imp ";
3532 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3533 n_value, m.imp);
3534 if (info->verbose && name == nullptr) {
3535 if (n_value != 0) {
3536 outs() << format("0x%" PRIx64, n_value) << " ";
3537 if (m.imp != 0)
3538 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3539 } else
3540 outs() << format("0x%" PRIx64, m.imp) << " ";
3541 }
3542 if (name != nullptr)
3543 outs() << name;
3544 outs() << "\n";
3545
3546 p += sizeof(struct method64_t);
3547 offset += sizeof(struct method64_t);
3548 }
3549}
3550
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003551static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3552 const char *indent) {
3553 struct method_list32_t ml;
3554 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003555 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003556 uint32_t offset, xoffset, left, i;
3557 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003558
3559 r = get_pointer_32(p, offset, left, S, info);
3560 if (r == nullptr)
3561 return;
3562 memset(&ml, '\0', sizeof(struct method_list32_t));
3563 if (left < sizeof(struct method_list32_t)) {
3564 memcpy(&ml, r, left);
3565 outs() << " (method_list_t entends past the end of the section)\n";
3566 } else
3567 memcpy(&ml, r, sizeof(struct method_list32_t));
3568 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3569 swapStruct(ml);
3570 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3571 outs() << indent << "\t\t count " << ml.count << "\n";
3572
3573 p += sizeof(struct method_list32_t);
3574 offset += sizeof(struct method_list32_t);
3575 for (i = 0; i < ml.count; i++) {
3576 r = get_pointer_32(p, offset, left, S, info);
3577 if (r == nullptr)
3578 return;
3579 memset(&m, '\0', sizeof(struct method32_t));
3580 if (left < sizeof(struct method32_t)) {
3581 memcpy(&ml, r, left);
3582 outs() << indent << " (method_t entends past the end of the section)\n";
3583 } else
3584 memcpy(&m, r, sizeof(struct method32_t));
3585 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3586 swapStruct(m);
3587
3588 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3589 name = get_pointer_32(m.name, xoffset, left, xS, info);
3590 if (name != nullptr)
3591 outs() << format(" %.*s", left, name);
3592 outs() << "\n";
3593
3594 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3595 name = get_pointer_32(m.types, xoffset, left, xS, info);
3596 if (name != nullptr)
3597 outs() << format(" %.*s", left, name);
3598 outs() << "\n";
3599
3600 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3601 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3602 m.imp);
3603 if (name != nullptr)
3604 outs() << " " << name;
3605 outs() << "\n";
3606
3607 p += sizeof(struct method32_t);
3608 offset += sizeof(struct method32_t);
3609 }
3610}
3611
Kevin Enderby846c0002015-04-16 17:19:59 +00003612static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3613 uint32_t offset, left, xleft;
3614 SectionRef S;
3615 struct objc_method_list_t method_list;
3616 struct objc_method_t method;
3617 const char *r, *methods, *name, *SymbolName;
3618 int32_t i;
3619
3620 r = get_pointer_32(p, offset, left, S, info, true);
3621 if (r == nullptr)
3622 return true;
3623
3624 outs() << "\n";
3625 if (left > sizeof(struct objc_method_list_t)) {
3626 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3627 } else {
3628 outs() << "\t\t objc_method_list extends past end of the section\n";
3629 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3630 memcpy(&method_list, r, left);
3631 }
3632 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3633 swapStruct(method_list);
3634
3635 outs() << "\t\t obsolete "
3636 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3637 outs() << "\t\t method_count " << method_list.method_count << "\n";
3638
3639 methods = r + sizeof(struct objc_method_list_t);
3640 for (i = 0; i < method_list.method_count; i++) {
3641 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3642 outs() << "\t\t remaining method's extend past the of the section\n";
3643 break;
3644 }
3645 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3646 sizeof(struct objc_method_t));
3647 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3648 swapStruct(method);
3649
3650 outs() << "\t\t method_name "
3651 << format("0x%08" PRIx32, method.method_name);
3652 if (info->verbose) {
3653 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3654 if (name != nullptr)
3655 outs() << format(" %.*s", xleft, name);
3656 else
3657 outs() << " (not in an __OBJC section)";
3658 }
3659 outs() << "\n";
3660
3661 outs() << "\t\t method_types "
3662 << format("0x%08" PRIx32, method.method_types);
3663 if (info->verbose) {
3664 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3665 if (name != nullptr)
3666 outs() << format(" %.*s", xleft, name);
3667 else
3668 outs() << " (not in an __OBJC section)";
3669 }
3670 outs() << "\n";
3671
3672 outs() << "\t\t method_imp "
3673 << format("0x%08" PRIx32, method.method_imp) << " ";
3674 if (info->verbose) {
3675 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3676 if (SymbolName != nullptr)
3677 outs() << SymbolName;
3678 }
3679 outs() << "\n";
3680 }
3681 return false;
3682}
3683
Kevin Enderby0fc11822015-04-01 20:57:01 +00003684static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3685 struct protocol_list64_t pl;
3686 uint64_t q, n_value;
3687 struct protocol64_t pc;
3688 const char *r;
3689 uint32_t offset, xoffset, left, i;
3690 SectionRef S, xS;
3691 const char *name, *sym_name;
3692
3693 r = get_pointer_64(p, offset, left, S, info);
3694 if (r == nullptr)
3695 return;
3696 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3697 if (left < sizeof(struct protocol_list64_t)) {
3698 memcpy(&pl, r, left);
3699 outs() << " (protocol_list_t entends past the end of the section)\n";
3700 } else
3701 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3702 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3703 swapStruct(pl);
3704 outs() << " count " << pl.count << "\n";
3705
3706 p += sizeof(struct protocol_list64_t);
3707 offset += sizeof(struct protocol_list64_t);
3708 for (i = 0; i < pl.count; i++) {
3709 r = get_pointer_64(p, offset, left, S, info);
3710 if (r == nullptr)
3711 return;
3712 q = 0;
3713 if (left < sizeof(uint64_t)) {
3714 memcpy(&q, r, left);
3715 outs() << " (protocol_t * entends past the end of the section)\n";
3716 } else
3717 memcpy(&q, r, sizeof(uint64_t));
3718 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3719 sys::swapByteOrder(q);
3720
3721 outs() << "\t\t list[" << i << "] ";
3722 sym_name = get_symbol_64(offset, S, info, n_value, q);
3723 if (n_value != 0) {
3724 if (info->verbose && sym_name != nullptr)
3725 outs() << sym_name;
3726 else
3727 outs() << format("0x%" PRIx64, n_value);
3728 if (q != 0)
3729 outs() << " + " << format("0x%" PRIx64, q);
3730 } else
3731 outs() << format("0x%" PRIx64, q);
3732 outs() << " (struct protocol_t *)\n";
3733
3734 r = get_pointer_64(q + n_value, offset, left, S, info);
3735 if (r == nullptr)
3736 return;
3737 memset(&pc, '\0', sizeof(struct protocol64_t));
3738 if (left < sizeof(struct protocol64_t)) {
3739 memcpy(&pc, r, left);
3740 outs() << " (protocol_t entends past the end of the section)\n";
3741 } else
3742 memcpy(&pc, r, sizeof(struct protocol64_t));
3743 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3744 swapStruct(pc);
3745
3746 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3747
3748 outs() << "\t\t\t name ";
3749 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3750 info, n_value, pc.name);
3751 if (n_value != 0) {
3752 if (info->verbose && sym_name != nullptr)
3753 outs() << sym_name;
3754 else
3755 outs() << format("0x%" PRIx64, n_value);
3756 if (pc.name != 0)
3757 outs() << " + " << format("0x%" PRIx64, pc.name);
3758 } else
3759 outs() << format("0x%" PRIx64, pc.name);
3760 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3761 if (name != nullptr)
3762 outs() << format(" %.*s", left, name);
3763 outs() << "\n";
3764
3765 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3766
3767 outs() << "\t\t instanceMethods ";
3768 sym_name =
3769 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3770 S, info, n_value, pc.instanceMethods);
3771 if (n_value != 0) {
3772 if (info->verbose && sym_name != nullptr)
3773 outs() << sym_name;
3774 else
3775 outs() << format("0x%" PRIx64, n_value);
3776 if (pc.instanceMethods != 0)
3777 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3778 } else
3779 outs() << format("0x%" PRIx64, pc.instanceMethods);
3780 outs() << " (struct method_list_t *)\n";
3781 if (pc.instanceMethods + n_value != 0)
3782 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3783
3784 outs() << "\t\t classMethods ";
3785 sym_name =
3786 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3787 info, n_value, pc.classMethods);
3788 if (n_value != 0) {
3789 if (info->verbose && sym_name != nullptr)
3790 outs() << sym_name;
3791 else
3792 outs() << format("0x%" PRIx64, n_value);
3793 if (pc.classMethods != 0)
3794 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3795 } else
3796 outs() << format("0x%" PRIx64, pc.classMethods);
3797 outs() << " (struct method_list_t *)\n";
3798 if (pc.classMethods + n_value != 0)
3799 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3800
3801 outs() << "\t optionalInstanceMethods "
3802 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3803 outs() << "\t optionalClassMethods "
3804 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3805 outs() << "\t instanceProperties "
3806 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3807
3808 p += sizeof(uint64_t);
3809 offset += sizeof(uint64_t);
3810 }
3811}
3812
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003813static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3814 struct protocol_list32_t pl;
3815 uint32_t q;
3816 struct protocol32_t pc;
3817 const char *r;
3818 uint32_t offset, xoffset, left, i;
3819 SectionRef S, xS;
3820 const char *name;
3821
3822 r = get_pointer_32(p, offset, left, S, info);
3823 if (r == nullptr)
3824 return;
3825 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3826 if (left < sizeof(struct protocol_list32_t)) {
3827 memcpy(&pl, r, left);
3828 outs() << " (protocol_list_t entends past the end of the section)\n";
3829 } else
3830 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3831 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3832 swapStruct(pl);
3833 outs() << " count " << pl.count << "\n";
3834
3835 p += sizeof(struct protocol_list32_t);
3836 offset += sizeof(struct protocol_list32_t);
3837 for (i = 0; i < pl.count; i++) {
3838 r = get_pointer_32(p, offset, left, S, info);
3839 if (r == nullptr)
3840 return;
3841 q = 0;
3842 if (left < sizeof(uint32_t)) {
3843 memcpy(&q, r, left);
3844 outs() << " (protocol_t * entends past the end of the section)\n";
3845 } else
3846 memcpy(&q, r, sizeof(uint32_t));
3847 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3848 sys::swapByteOrder(q);
3849 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3850 << " (struct protocol_t *)\n";
3851 r = get_pointer_32(q, offset, left, S, info);
3852 if (r == nullptr)
3853 return;
3854 memset(&pc, '\0', sizeof(struct protocol32_t));
3855 if (left < sizeof(struct protocol32_t)) {
3856 memcpy(&pc, r, left);
3857 outs() << " (protocol_t entends past the end of the section)\n";
3858 } else
3859 memcpy(&pc, r, sizeof(struct protocol32_t));
3860 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3861 swapStruct(pc);
3862 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3863 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3864 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3865 if (name != nullptr)
3866 outs() << format(" %.*s", left, name);
3867 outs() << "\n";
3868 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3869 outs() << "\t\t instanceMethods "
3870 << format("0x%" PRIx32, pc.instanceMethods)
3871 << " (struct method_list_t *)\n";
3872 if (pc.instanceMethods != 0)
3873 print_method_list32_t(pc.instanceMethods, info, "\t");
3874 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3875 << " (struct method_list_t *)\n";
3876 if (pc.classMethods != 0)
3877 print_method_list32_t(pc.classMethods, info, "\t");
3878 outs() << "\t optionalInstanceMethods "
3879 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3880 outs() << "\t optionalClassMethods "
3881 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3882 outs() << "\t instanceProperties "
3883 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3884 p += sizeof(uint32_t);
3885 offset += sizeof(uint32_t);
3886 }
3887}
3888
Kevin Enderby846c0002015-04-16 17:19:59 +00003889static void print_indent(uint32_t indent) {
3890 for (uint32_t i = 0; i < indent;) {
3891 if (indent - i >= 8) {
3892 outs() << "\t";
3893 i += 8;
3894 } else {
3895 for (uint32_t j = i; j < indent; j++)
3896 outs() << " ";
3897 return;
3898 }
3899 }
3900}
3901
3902static bool print_method_description_list(uint32_t p, uint32_t indent,
3903 struct DisassembleInfo *info) {
3904 uint32_t offset, left, xleft;
3905 SectionRef S;
3906 struct objc_method_description_list_t mdl;
3907 struct objc_method_description_t md;
3908 const char *r, *list, *name;
3909 int32_t i;
3910
3911 r = get_pointer_32(p, offset, left, S, info, true);
3912 if (r == nullptr)
3913 return true;
3914
3915 outs() << "\n";
3916 if (left > sizeof(struct objc_method_description_list_t)) {
3917 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3918 } else {
3919 print_indent(indent);
3920 outs() << " objc_method_description_list extends past end of the section\n";
3921 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3922 memcpy(&mdl, r, left);
3923 }
3924 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3925 swapStruct(mdl);
3926
3927 print_indent(indent);
3928 outs() << " count " << mdl.count << "\n";
3929
3930 list = r + sizeof(struct objc_method_description_list_t);
3931 for (i = 0; i < mdl.count; i++) {
3932 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3933 print_indent(indent);
3934 outs() << " remaining list entries extend past the of the section\n";
3935 break;
3936 }
3937 print_indent(indent);
3938 outs() << " list[" << i << "]\n";
3939 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3940 sizeof(struct objc_method_description_t));
3941 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3942 swapStruct(md);
3943
3944 print_indent(indent);
3945 outs() << " name " << format("0x%08" PRIx32, md.name);
3946 if (info->verbose) {
3947 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3948 if (name != nullptr)
3949 outs() << format(" %.*s", xleft, name);
3950 else
3951 outs() << " (not in an __OBJC section)";
3952 }
3953 outs() << "\n";
3954
3955 print_indent(indent);
3956 outs() << " types " << format("0x%08" PRIx32, md.types);
3957 if (info->verbose) {
3958 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3959 if (name != nullptr)
3960 outs() << format(" %.*s", xleft, name);
3961 else
3962 outs() << " (not in an __OBJC section)";
3963 }
3964 outs() << "\n";
3965 }
3966 return false;
3967}
3968
3969static bool print_protocol_list(uint32_t p, uint32_t indent,
3970 struct DisassembleInfo *info);
3971
3972static bool print_protocol(uint32_t p, uint32_t indent,
3973 struct DisassembleInfo *info) {
3974 uint32_t offset, left;
3975 SectionRef S;
3976 struct objc_protocol_t protocol;
3977 const char *r, *name;
3978
3979 r = get_pointer_32(p, offset, left, S, info, true);
3980 if (r == nullptr)
3981 return true;
3982
3983 outs() << "\n";
3984 if (left >= sizeof(struct objc_protocol_t)) {
3985 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3986 } else {
3987 print_indent(indent);
3988 outs() << " Protocol extends past end of the section\n";
3989 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3990 memcpy(&protocol, r, left);
3991 }
3992 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3993 swapStruct(protocol);
3994
3995 print_indent(indent);
3996 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3997 << "\n";
3998
3999 print_indent(indent);
4000 outs() << " protocol_name "
4001 << format("0x%08" PRIx32, protocol.protocol_name);
4002 if (info->verbose) {
4003 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4004 if (name != nullptr)
4005 outs() << format(" %.*s", left, name);
4006 else
4007 outs() << " (not in an __OBJC section)";
4008 }
4009 outs() << "\n";
4010
4011 print_indent(indent);
4012 outs() << " protocol_list "
4013 << format("0x%08" PRIx32, protocol.protocol_list);
4014 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4015 outs() << " (not in an __OBJC section)\n";
4016
4017 print_indent(indent);
4018 outs() << " instance_methods "
4019 << format("0x%08" PRIx32, protocol.instance_methods);
4020 if (print_method_description_list(protocol.instance_methods, indent, info))
4021 outs() << " (not in an __OBJC section)\n";
4022
4023 print_indent(indent);
4024 outs() << " class_methods "
4025 << format("0x%08" PRIx32, protocol.class_methods);
4026 if (print_method_description_list(protocol.class_methods, indent, info))
4027 outs() << " (not in an __OBJC section)\n";
4028
4029 return false;
4030}
4031
4032static bool print_protocol_list(uint32_t p, uint32_t indent,
4033 struct DisassembleInfo *info) {
4034 uint32_t offset, left, l;
4035 SectionRef S;
4036 struct objc_protocol_list_t protocol_list;
4037 const char *r, *list;
4038 int32_t i;
4039
4040 r = get_pointer_32(p, offset, left, S, info, true);
4041 if (r == nullptr)
4042 return true;
4043
4044 outs() << "\n";
4045 if (left > sizeof(struct objc_protocol_list_t)) {
4046 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4047 } else {
4048 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4049 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4050 memcpy(&protocol_list, r, left);
4051 }
4052 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4053 swapStruct(protocol_list);
4054
4055 print_indent(indent);
4056 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4057 << "\n";
4058 print_indent(indent);
4059 outs() << " count " << protocol_list.count << "\n";
4060
4061 list = r + sizeof(struct objc_protocol_list_t);
4062 for (i = 0; i < protocol_list.count; i++) {
4063 if ((i + 1) * sizeof(uint32_t) > left) {
4064 outs() << "\t\t remaining list entries extend past the of the section\n";
4065 break;
4066 }
4067 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4068 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4069 sys::swapByteOrder(l);
4070
4071 print_indent(indent);
4072 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4073 if (print_protocol(l, indent, info))
4074 outs() << "(not in an __OBJC section)\n";
4075 }
4076 return false;
4077}
4078
Kevin Enderby0fc11822015-04-01 20:57:01 +00004079static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4080 struct ivar_list64_t il;
4081 struct ivar64_t i;
4082 const char *r;
4083 uint32_t offset, xoffset, left, j;
4084 SectionRef S, xS;
4085 const char *name, *sym_name, *ivar_offset_p;
4086 uint64_t ivar_offset, n_value;
4087
4088 r = get_pointer_64(p, offset, left, S, info);
4089 if (r == nullptr)
4090 return;
4091 memset(&il, '\0', sizeof(struct ivar_list64_t));
4092 if (left < sizeof(struct ivar_list64_t)) {
4093 memcpy(&il, r, left);
4094 outs() << " (ivar_list_t entends past the end of the section)\n";
4095 } else
4096 memcpy(&il, r, sizeof(struct ivar_list64_t));
4097 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4098 swapStruct(il);
4099 outs() << " entsize " << il.entsize << "\n";
4100 outs() << " count " << il.count << "\n";
4101
4102 p += sizeof(struct ivar_list64_t);
4103 offset += sizeof(struct ivar_list64_t);
4104 for (j = 0; j < il.count; j++) {
4105 r = get_pointer_64(p, offset, left, S, info);
4106 if (r == nullptr)
4107 return;
4108 memset(&i, '\0', sizeof(struct ivar64_t));
4109 if (left < sizeof(struct ivar64_t)) {
4110 memcpy(&i, r, left);
4111 outs() << " (ivar_t entends past the end of the section)\n";
4112 } else
4113 memcpy(&i, r, sizeof(struct ivar64_t));
4114 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4115 swapStruct(i);
4116
4117 outs() << "\t\t\t offset ";
4118 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4119 info, n_value, i.offset);
4120 if (n_value != 0) {
4121 if (info->verbose && sym_name != nullptr)
4122 outs() << sym_name;
4123 else
4124 outs() << format("0x%" PRIx64, n_value);
4125 if (i.offset != 0)
4126 outs() << " + " << format("0x%" PRIx64, i.offset);
4127 } else
4128 outs() << format("0x%" PRIx64, i.offset);
4129 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4130 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4131 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4132 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4133 sys::swapByteOrder(ivar_offset);
4134 outs() << " " << ivar_offset << "\n";
4135 } else
4136 outs() << "\n";
4137
4138 outs() << "\t\t\t name ";
4139 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4140 n_value, i.name);
4141 if (n_value != 0) {
4142 if (info->verbose && sym_name != nullptr)
4143 outs() << sym_name;
4144 else
4145 outs() << format("0x%" PRIx64, n_value);
4146 if (i.name != 0)
4147 outs() << " + " << format("0x%" PRIx64, i.name);
4148 } else
4149 outs() << format("0x%" PRIx64, i.name);
4150 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4151 if (name != nullptr)
4152 outs() << format(" %.*s", left, name);
4153 outs() << "\n";
4154
4155 outs() << "\t\t\t type ";
4156 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4157 n_value, i.name);
4158 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4159 if (n_value != 0) {
4160 if (info->verbose && sym_name != nullptr)
4161 outs() << sym_name;
4162 else
4163 outs() << format("0x%" PRIx64, n_value);
4164 if (i.type != 0)
4165 outs() << " + " << format("0x%" PRIx64, i.type);
4166 } else
4167 outs() << format("0x%" PRIx64, i.type);
4168 if (name != nullptr)
4169 outs() << format(" %.*s", left, name);
4170 outs() << "\n";
4171
4172 outs() << "\t\t\talignment " << i.alignment << "\n";
4173 outs() << "\t\t\t size " << i.size << "\n";
4174
4175 p += sizeof(struct ivar64_t);
4176 offset += sizeof(struct ivar64_t);
4177 }
4178}
4179
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004180static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4181 struct ivar_list32_t il;
4182 struct ivar32_t i;
4183 const char *r;
4184 uint32_t offset, xoffset, left, j;
4185 SectionRef S, xS;
4186 const char *name, *ivar_offset_p;
4187 uint32_t ivar_offset;
4188
4189 r = get_pointer_32(p, offset, left, S, info);
4190 if (r == nullptr)
4191 return;
4192 memset(&il, '\0', sizeof(struct ivar_list32_t));
4193 if (left < sizeof(struct ivar_list32_t)) {
4194 memcpy(&il, r, left);
4195 outs() << " (ivar_list_t entends past the end of the section)\n";
4196 } else
4197 memcpy(&il, r, sizeof(struct ivar_list32_t));
4198 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4199 swapStruct(il);
4200 outs() << " entsize " << il.entsize << "\n";
4201 outs() << " count " << il.count << "\n";
4202
4203 p += sizeof(struct ivar_list32_t);
4204 offset += sizeof(struct ivar_list32_t);
4205 for (j = 0; j < il.count; j++) {
4206 r = get_pointer_32(p, offset, left, S, info);
4207 if (r == nullptr)
4208 return;
4209 memset(&i, '\0', sizeof(struct ivar32_t));
4210 if (left < sizeof(struct ivar32_t)) {
4211 memcpy(&i, r, left);
4212 outs() << " (ivar_t entends past the end of the section)\n";
4213 } else
4214 memcpy(&i, r, sizeof(struct ivar32_t));
4215 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4216 swapStruct(i);
4217
4218 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4219 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4220 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4221 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4222 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4223 sys::swapByteOrder(ivar_offset);
4224 outs() << " " << ivar_offset << "\n";
4225 } else
4226 outs() << "\n";
4227
4228 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4229 name = get_pointer_32(i.name, xoffset, left, xS, info);
4230 if (name != nullptr)
4231 outs() << format(" %.*s", left, name);
4232 outs() << "\n";
4233
4234 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4235 name = get_pointer_32(i.type, xoffset, left, xS, info);
4236 if (name != nullptr)
4237 outs() << format(" %.*s", left, name);
4238 outs() << "\n";
4239
4240 outs() << "\t\t\talignment " << i.alignment << "\n";
4241 outs() << "\t\t\t size " << i.size << "\n";
4242
4243 p += sizeof(struct ivar32_t);
4244 offset += sizeof(struct ivar32_t);
4245 }
4246}
4247
Kevin Enderby0fc11822015-04-01 20:57:01 +00004248static void print_objc_property_list64(uint64_t p,
4249 struct DisassembleInfo *info) {
4250 struct objc_property_list64 opl;
4251 struct objc_property64 op;
4252 const char *r;
4253 uint32_t offset, xoffset, left, j;
4254 SectionRef S, xS;
4255 const char *name, *sym_name;
4256 uint64_t n_value;
4257
4258 r = get_pointer_64(p, offset, left, S, info);
4259 if (r == nullptr)
4260 return;
4261 memset(&opl, '\0', sizeof(struct objc_property_list64));
4262 if (left < sizeof(struct objc_property_list64)) {
4263 memcpy(&opl, r, left);
4264 outs() << " (objc_property_list entends past the end of the section)\n";
4265 } else
4266 memcpy(&opl, r, sizeof(struct objc_property_list64));
4267 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4268 swapStruct(opl);
4269 outs() << " entsize " << opl.entsize << "\n";
4270 outs() << " count " << opl.count << "\n";
4271
4272 p += sizeof(struct objc_property_list64);
4273 offset += sizeof(struct objc_property_list64);
4274 for (j = 0; j < opl.count; j++) {
4275 r = get_pointer_64(p, offset, left, S, info);
4276 if (r == nullptr)
4277 return;
4278 memset(&op, '\0', sizeof(struct objc_property64));
4279 if (left < sizeof(struct objc_property64)) {
4280 memcpy(&op, r, left);
4281 outs() << " (objc_property entends past the end of the section)\n";
4282 } else
4283 memcpy(&op, r, sizeof(struct objc_property64));
4284 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4285 swapStruct(op);
4286
4287 outs() << "\t\t\t name ";
4288 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4289 info, n_value, op.name);
4290 if (n_value != 0) {
4291 if (info->verbose && sym_name != nullptr)
4292 outs() << sym_name;
4293 else
4294 outs() << format("0x%" PRIx64, n_value);
4295 if (op.name != 0)
4296 outs() << " + " << format("0x%" PRIx64, op.name);
4297 } else
4298 outs() << format("0x%" PRIx64, op.name);
4299 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4300 if (name != nullptr)
4301 outs() << format(" %.*s", left, name);
4302 outs() << "\n";
4303
4304 outs() << "\t\t\tattributes ";
4305 sym_name =
4306 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4307 info, n_value, op.attributes);
4308 if (n_value != 0) {
4309 if (info->verbose && sym_name != nullptr)
4310 outs() << sym_name;
4311 else
4312 outs() << format("0x%" PRIx64, n_value);
4313 if (op.attributes != 0)
4314 outs() << " + " << format("0x%" PRIx64, op.attributes);
4315 } else
4316 outs() << format("0x%" PRIx64, op.attributes);
4317 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4318 if (name != nullptr)
4319 outs() << format(" %.*s", left, name);
4320 outs() << "\n";
4321
4322 p += sizeof(struct objc_property64);
4323 offset += sizeof(struct objc_property64);
4324 }
4325}
4326
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004327static void print_objc_property_list32(uint32_t p,
4328 struct DisassembleInfo *info) {
4329 struct objc_property_list32 opl;
4330 struct objc_property32 op;
4331 const char *r;
4332 uint32_t offset, xoffset, left, j;
4333 SectionRef S, xS;
4334 const char *name;
4335
4336 r = get_pointer_32(p, offset, left, S, info);
4337 if (r == nullptr)
4338 return;
4339 memset(&opl, '\0', sizeof(struct objc_property_list32));
4340 if (left < sizeof(struct objc_property_list32)) {
4341 memcpy(&opl, r, left);
4342 outs() << " (objc_property_list entends past the end of the section)\n";
4343 } else
4344 memcpy(&opl, r, sizeof(struct objc_property_list32));
4345 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4346 swapStruct(opl);
4347 outs() << " entsize " << opl.entsize << "\n";
4348 outs() << " count " << opl.count << "\n";
4349
4350 p += sizeof(struct objc_property_list32);
4351 offset += sizeof(struct objc_property_list32);
4352 for (j = 0; j < opl.count; j++) {
4353 r = get_pointer_32(p, offset, left, S, info);
4354 if (r == nullptr)
4355 return;
4356 memset(&op, '\0', sizeof(struct objc_property32));
4357 if (left < sizeof(struct objc_property32)) {
4358 memcpy(&op, r, left);
4359 outs() << " (objc_property entends past the end of the section)\n";
4360 } else
4361 memcpy(&op, r, sizeof(struct objc_property32));
4362 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4363 swapStruct(op);
4364
4365 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4366 name = get_pointer_32(op.name, xoffset, left, xS, info);
4367 if (name != nullptr)
4368 outs() << format(" %.*s", left, name);
4369 outs() << "\n";
4370
4371 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4372 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4373 if (name != nullptr)
4374 outs() << format(" %.*s", left, name);
4375 outs() << "\n";
4376
4377 p += sizeof(struct objc_property32);
4378 offset += sizeof(struct objc_property32);
4379 }
4380}
4381
Richard Smith81ff44d2015-10-09 22:09:56 +00004382static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004383 bool &is_meta_class) {
4384 struct class_ro64_t cro;
4385 const char *r;
4386 uint32_t offset, xoffset, left;
4387 SectionRef S, xS;
4388 const char *name, *sym_name;
4389 uint64_t n_value;
4390
4391 r = get_pointer_64(p, offset, left, S, info);
4392 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004393 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004394 memset(&cro, '\0', sizeof(struct class_ro64_t));
4395 if (left < sizeof(struct class_ro64_t)) {
4396 memcpy(&cro, r, left);
4397 outs() << " (class_ro_t entends past the end of the section)\n";
4398 } else
4399 memcpy(&cro, r, sizeof(struct class_ro64_t));
4400 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4401 swapStruct(cro);
4402 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4403 if (cro.flags & RO_META)
4404 outs() << " RO_META";
4405 if (cro.flags & RO_ROOT)
4406 outs() << " RO_ROOT";
4407 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4408 outs() << " RO_HAS_CXX_STRUCTORS";
4409 outs() << "\n";
4410 outs() << " instanceStart " << cro.instanceStart << "\n";
4411 outs() << " instanceSize " << cro.instanceSize << "\n";
4412 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4413 << "\n";
4414 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4415 << "\n";
4416 print_layout_map64(cro.ivarLayout, info);
4417
4418 outs() << " name ";
4419 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4420 info, n_value, cro.name);
4421 if (n_value != 0) {
4422 if (info->verbose && sym_name != nullptr)
4423 outs() << sym_name;
4424 else
4425 outs() << format("0x%" PRIx64, n_value);
4426 if (cro.name != 0)
4427 outs() << " + " << format("0x%" PRIx64, cro.name);
4428 } else
4429 outs() << format("0x%" PRIx64, cro.name);
4430 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4431 if (name != nullptr)
4432 outs() << format(" %.*s", left, name);
4433 outs() << "\n";
4434
4435 outs() << " baseMethods ";
4436 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4437 S, info, n_value, cro.baseMethods);
4438 if (n_value != 0) {
4439 if (info->verbose && sym_name != nullptr)
4440 outs() << sym_name;
4441 else
4442 outs() << format("0x%" PRIx64, n_value);
4443 if (cro.baseMethods != 0)
4444 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4445 } else
4446 outs() << format("0x%" PRIx64, cro.baseMethods);
4447 outs() << " (struct method_list_t *)\n";
4448 if (cro.baseMethods + n_value != 0)
4449 print_method_list64_t(cro.baseMethods + n_value, info, "");
4450
4451 outs() << " baseProtocols ";
4452 sym_name =
4453 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4454 info, n_value, cro.baseProtocols);
4455 if (n_value != 0) {
4456 if (info->verbose && sym_name != nullptr)
4457 outs() << sym_name;
4458 else
4459 outs() << format("0x%" PRIx64, n_value);
4460 if (cro.baseProtocols != 0)
4461 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4462 } else
4463 outs() << format("0x%" PRIx64, cro.baseProtocols);
4464 outs() << "\n";
4465 if (cro.baseProtocols + n_value != 0)
4466 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4467
4468 outs() << " ivars ";
4469 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004470 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004471 if (n_value != 0) {
4472 if (info->verbose && sym_name != nullptr)
4473 outs() << sym_name;
4474 else
4475 outs() << format("0x%" PRIx64, n_value);
4476 if (cro.ivars != 0)
4477 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4478 } else
4479 outs() << format("0x%" PRIx64, cro.ivars);
4480 outs() << "\n";
4481 if (cro.ivars + n_value != 0)
4482 print_ivar_list64_t(cro.ivars + n_value, info);
4483
4484 outs() << " weakIvarLayout ";
4485 sym_name =
4486 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4487 info, n_value, cro.weakIvarLayout);
4488 if (n_value != 0) {
4489 if (info->verbose && sym_name != nullptr)
4490 outs() << sym_name;
4491 else
4492 outs() << format("0x%" PRIx64, n_value);
4493 if (cro.weakIvarLayout != 0)
4494 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4495 } else
4496 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4497 outs() << "\n";
4498 print_layout_map64(cro.weakIvarLayout + n_value, info);
4499
4500 outs() << " baseProperties ";
4501 sym_name =
4502 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4503 info, n_value, cro.baseProperties);
4504 if (n_value != 0) {
4505 if (info->verbose && sym_name != nullptr)
4506 outs() << sym_name;
4507 else
4508 outs() << format("0x%" PRIx64, n_value);
4509 if (cro.baseProperties != 0)
4510 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4511 } else
4512 outs() << format("0x%" PRIx64, cro.baseProperties);
4513 outs() << "\n";
4514 if (cro.baseProperties + n_value != 0)
4515 print_objc_property_list64(cro.baseProperties + n_value, info);
4516
Rafael Espindolab9091322015-10-24 23:19:10 +00004517 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004518 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004519}
4520
Richard Smith81ff44d2015-10-09 22:09:56 +00004521static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004522 bool &is_meta_class) {
4523 struct class_ro32_t cro;
4524 const char *r;
4525 uint32_t offset, xoffset, left;
4526 SectionRef S, xS;
4527 const char *name;
4528
4529 r = get_pointer_32(p, offset, left, S, info);
4530 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004531 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004532 memset(&cro, '\0', sizeof(struct class_ro32_t));
4533 if (left < sizeof(struct class_ro32_t)) {
4534 memcpy(&cro, r, left);
4535 outs() << " (class_ro_t entends past the end of the section)\n";
4536 } else
4537 memcpy(&cro, r, sizeof(struct class_ro32_t));
4538 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4539 swapStruct(cro);
4540 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4541 if (cro.flags & RO_META)
4542 outs() << " RO_META";
4543 if (cro.flags & RO_ROOT)
4544 outs() << " RO_ROOT";
4545 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4546 outs() << " RO_HAS_CXX_STRUCTORS";
4547 outs() << "\n";
4548 outs() << " instanceStart " << cro.instanceStart << "\n";
4549 outs() << " instanceSize " << cro.instanceSize << "\n";
4550 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4551 << "\n";
4552 print_layout_map32(cro.ivarLayout, info);
4553
4554 outs() << " name " << format("0x%" PRIx32, cro.name);
4555 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4556 if (name != nullptr)
4557 outs() << format(" %.*s", left, name);
4558 outs() << "\n";
4559
4560 outs() << " baseMethods "
4561 << format("0x%" PRIx32, cro.baseMethods)
4562 << " (struct method_list_t *)\n";
4563 if (cro.baseMethods != 0)
4564 print_method_list32_t(cro.baseMethods, info, "");
4565
4566 outs() << " baseProtocols "
4567 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4568 if (cro.baseProtocols != 0)
4569 print_protocol_list32_t(cro.baseProtocols, info);
4570 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4571 << "\n";
4572 if (cro.ivars != 0)
4573 print_ivar_list32_t(cro.ivars, info);
4574 outs() << " weakIvarLayout "
4575 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4576 print_layout_map32(cro.weakIvarLayout, info);
4577 outs() << " baseProperties "
4578 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4579 if (cro.baseProperties != 0)
4580 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004581 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004582 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004583}
4584
Kevin Enderby0fc11822015-04-01 20:57:01 +00004585static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4586 struct class64_t c;
4587 const char *r;
4588 uint32_t offset, left;
4589 SectionRef S;
4590 const char *name;
4591 uint64_t isa_n_value, n_value;
4592
4593 r = get_pointer_64(p, offset, left, S, info);
4594 if (r == nullptr || left < sizeof(struct class64_t))
4595 return;
4596 memset(&c, '\0', sizeof(struct class64_t));
4597 if (left < sizeof(struct class64_t)) {
4598 memcpy(&c, r, left);
4599 outs() << " (class_t entends past the end of the section)\n";
4600 } else
4601 memcpy(&c, r, sizeof(struct class64_t));
4602 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4603 swapStruct(c);
4604
4605 outs() << " isa " << format("0x%" PRIx64, c.isa);
4606 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4607 isa_n_value, c.isa);
4608 if (name != nullptr)
4609 outs() << " " << name;
4610 outs() << "\n";
4611
4612 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4613 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4614 n_value, c.superclass);
4615 if (name != nullptr)
4616 outs() << " " << name;
4617 outs() << "\n";
4618
4619 outs() << " cache " << format("0x%" PRIx64, c.cache);
4620 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4621 n_value, c.cache);
4622 if (name != nullptr)
4623 outs() << " " << name;
4624 outs() << "\n";
4625
4626 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4627 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4628 n_value, c.vtable);
4629 if (name != nullptr)
4630 outs() << " " << name;
4631 outs() << "\n";
4632
4633 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4634 n_value, c.data);
4635 outs() << " data ";
4636 if (n_value != 0) {
4637 if (info->verbose && name != nullptr)
4638 outs() << name;
4639 else
4640 outs() << format("0x%" PRIx64, n_value);
4641 if (c.data != 0)
4642 outs() << " + " << format("0x%" PRIx64, c.data);
4643 } else
4644 outs() << format("0x%" PRIx64, c.data);
4645 outs() << " (struct class_ro_t *)";
4646
4647 // This is a Swift class if some of the low bits of the pointer are set.
4648 if ((c.data + n_value) & 0x7)
4649 outs() << " Swift class";
4650 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004651 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004652 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4653 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004654
Kevin Enderbyaac75382015-10-08 16:56:35 +00004655 if (!is_meta_class &&
4656 c.isa + isa_n_value != p &&
4657 c.isa + isa_n_value != 0 &&
4658 info->depth < 100) {
4659 info->depth++;
4660 outs() << "Meta Class\n";
4661 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004662 }
4663}
4664
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004665static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4666 struct class32_t c;
4667 const char *r;
4668 uint32_t offset, left;
4669 SectionRef S;
4670 const char *name;
4671
4672 r = get_pointer_32(p, offset, left, S, info);
4673 if (r == nullptr)
4674 return;
4675 memset(&c, '\0', sizeof(struct class32_t));
4676 if (left < sizeof(struct class32_t)) {
4677 memcpy(&c, r, left);
4678 outs() << " (class_t entends past the end of the section)\n";
4679 } else
4680 memcpy(&c, r, sizeof(struct class32_t));
4681 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4682 swapStruct(c);
4683
4684 outs() << " isa " << format("0x%" PRIx32, c.isa);
4685 name =
4686 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4687 if (name != nullptr)
4688 outs() << " " << name;
4689 outs() << "\n";
4690
4691 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4692 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4693 c.superclass);
4694 if (name != nullptr)
4695 outs() << " " << name;
4696 outs() << "\n";
4697
4698 outs() << " cache " << format("0x%" PRIx32, c.cache);
4699 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4700 c.cache);
4701 if (name != nullptr)
4702 outs() << " " << name;
4703 outs() << "\n";
4704
4705 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4706 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4707 c.vtable);
4708 if (name != nullptr)
4709 outs() << " " << name;
4710 outs() << "\n";
4711
4712 name =
4713 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4714 outs() << " data " << format("0x%" PRIx32, c.data)
4715 << " (struct class_ro_t *)";
4716
4717 // This is a Swift class if some of the low bits of the pointer are set.
4718 if (c.data & 0x3)
4719 outs() << " Swift class";
4720 outs() << "\n";
4721 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004722 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4723 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004724
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004725 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004726 outs() << "Meta Class\n";
4727 print_class32_t(c.isa, info);
4728 }
4729}
4730
Kevin Enderby846c0002015-04-16 17:19:59 +00004731static void print_objc_class_t(struct objc_class_t *objc_class,
4732 struct DisassembleInfo *info) {
4733 uint32_t offset, left, xleft;
4734 const char *name, *p, *ivar_list;
4735 SectionRef S;
4736 int32_t i;
4737 struct objc_ivar_list_t objc_ivar_list;
4738 struct objc_ivar_t ivar;
4739
4740 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4741 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4742 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4743 if (name != nullptr)
4744 outs() << format(" %.*s", left, name);
4745 else
4746 outs() << " (not in an __OBJC section)";
4747 }
4748 outs() << "\n";
4749
4750 outs() << "\t super_class "
4751 << format("0x%08" PRIx32, objc_class->super_class);
4752 if (info->verbose) {
4753 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4754 if (name != nullptr)
4755 outs() << format(" %.*s", left, name);
4756 else
4757 outs() << " (not in an __OBJC section)";
4758 }
4759 outs() << "\n";
4760
4761 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4762 if (info->verbose) {
4763 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4764 if (name != nullptr)
4765 outs() << format(" %.*s", left, name);
4766 else
4767 outs() << " (not in an __OBJC section)";
4768 }
4769 outs() << "\n";
4770
4771 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4772 << "\n";
4773
4774 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4775 if (info->verbose) {
4776 if (CLS_GETINFO(objc_class, CLS_CLASS))
4777 outs() << " CLS_CLASS";
4778 else if (CLS_GETINFO(objc_class, CLS_META))
4779 outs() << " CLS_META";
4780 }
4781 outs() << "\n";
4782
4783 outs() << "\t instance_size "
4784 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4785
4786 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4787 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4788 if (p != nullptr) {
4789 if (left > sizeof(struct objc_ivar_list_t)) {
4790 outs() << "\n";
4791 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4792 } else {
4793 outs() << " (entends past the end of the section)\n";
4794 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4795 memcpy(&objc_ivar_list, p, left);
4796 }
4797 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4798 swapStruct(objc_ivar_list);
4799 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4800 ivar_list = p + sizeof(struct objc_ivar_list_t);
4801 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4802 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4803 outs() << "\t\t remaining ivar's extend past the of the section\n";
4804 break;
4805 }
4806 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4807 sizeof(struct objc_ivar_t));
4808 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4809 swapStruct(ivar);
4810
4811 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4812 if (info->verbose) {
4813 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4814 if (name != nullptr)
4815 outs() << format(" %.*s", xleft, name);
4816 else
4817 outs() << " (not in an __OBJC section)";
4818 }
4819 outs() << "\n";
4820
4821 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4822 if (info->verbose) {
4823 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4824 if (name != nullptr)
4825 outs() << format(" %.*s", xleft, name);
4826 else
4827 outs() << " (not in an __OBJC section)";
4828 }
4829 outs() << "\n";
4830
4831 outs() << "\t\t ivar_offset "
4832 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4833 }
4834 } else {
4835 outs() << " (not in an __OBJC section)\n";
4836 }
4837
4838 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4839 if (print_method_list(objc_class->methodLists, info))
4840 outs() << " (not in an __OBJC section)\n";
4841
4842 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4843 << "\n";
4844
4845 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4846 if (print_protocol_list(objc_class->protocols, 16, info))
4847 outs() << " (not in an __OBJC section)\n";
4848}
4849
4850static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4851 struct DisassembleInfo *info) {
4852 uint32_t offset, left;
4853 const char *name;
4854 SectionRef S;
4855
4856 outs() << "\t category name "
4857 << format("0x%08" PRIx32, objc_category->category_name);
4858 if (info->verbose) {
4859 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4860 true);
4861 if (name != nullptr)
4862 outs() << format(" %.*s", left, name);
4863 else
4864 outs() << " (not in an __OBJC section)";
4865 }
4866 outs() << "\n";
4867
4868 outs() << "\t\t class name "
4869 << format("0x%08" PRIx32, objc_category->class_name);
4870 if (info->verbose) {
4871 name =
4872 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4873 if (name != nullptr)
4874 outs() << format(" %.*s", left, name);
4875 else
4876 outs() << " (not in an __OBJC section)";
4877 }
4878 outs() << "\n";
4879
4880 outs() << "\t instance methods "
4881 << format("0x%08" PRIx32, objc_category->instance_methods);
4882 if (print_method_list(objc_category->instance_methods, info))
4883 outs() << " (not in an __OBJC section)\n";
4884
4885 outs() << "\t class methods "
4886 << format("0x%08" PRIx32, objc_category->class_methods);
4887 if (print_method_list(objc_category->class_methods, info))
4888 outs() << " (not in an __OBJC section)\n";
4889}
4890
Kevin Enderby0fc11822015-04-01 20:57:01 +00004891static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4892 struct category64_t c;
4893 const char *r;
4894 uint32_t offset, xoffset, left;
4895 SectionRef S, xS;
4896 const char *name, *sym_name;
4897 uint64_t n_value;
4898
4899 r = get_pointer_64(p, offset, left, S, info);
4900 if (r == nullptr)
4901 return;
4902 memset(&c, '\0', sizeof(struct category64_t));
4903 if (left < sizeof(struct category64_t)) {
4904 memcpy(&c, r, left);
4905 outs() << " (category_t entends past the end of the section)\n";
4906 } else
4907 memcpy(&c, r, sizeof(struct category64_t));
4908 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4909 swapStruct(c);
4910
4911 outs() << " name ";
4912 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4913 info, n_value, c.name);
4914 if (n_value != 0) {
4915 if (info->verbose && sym_name != nullptr)
4916 outs() << sym_name;
4917 else
4918 outs() << format("0x%" PRIx64, n_value);
4919 if (c.name != 0)
4920 outs() << " + " << format("0x%" PRIx64, c.name);
4921 } else
4922 outs() << format("0x%" PRIx64, c.name);
4923 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4924 if (name != nullptr)
4925 outs() << format(" %.*s", left, name);
4926 outs() << "\n";
4927
4928 outs() << " cls ";
4929 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4930 n_value, c.cls);
4931 if (n_value != 0) {
4932 if (info->verbose && sym_name != nullptr)
4933 outs() << sym_name;
4934 else
4935 outs() << format("0x%" PRIx64, n_value);
4936 if (c.cls != 0)
4937 outs() << " + " << format("0x%" PRIx64, c.cls);
4938 } else
4939 outs() << format("0x%" PRIx64, c.cls);
4940 outs() << "\n";
4941 if (c.cls + n_value != 0)
4942 print_class64_t(c.cls + n_value, info);
4943
4944 outs() << " instanceMethods ";
4945 sym_name =
4946 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4947 info, n_value, c.instanceMethods);
4948 if (n_value != 0) {
4949 if (info->verbose && sym_name != nullptr)
4950 outs() << sym_name;
4951 else
4952 outs() << format("0x%" PRIx64, n_value);
4953 if (c.instanceMethods != 0)
4954 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4955 } else
4956 outs() << format("0x%" PRIx64, c.instanceMethods);
4957 outs() << "\n";
4958 if (c.instanceMethods + n_value != 0)
4959 print_method_list64_t(c.instanceMethods + n_value, info, "");
4960
4961 outs() << " classMethods ";
4962 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4963 S, info, n_value, c.classMethods);
4964 if (n_value != 0) {
4965 if (info->verbose && sym_name != nullptr)
4966 outs() << sym_name;
4967 else
4968 outs() << format("0x%" PRIx64, n_value);
4969 if (c.classMethods != 0)
4970 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4971 } else
4972 outs() << format("0x%" PRIx64, c.classMethods);
4973 outs() << "\n";
4974 if (c.classMethods + n_value != 0)
4975 print_method_list64_t(c.classMethods + n_value, info, "");
4976
4977 outs() << " protocols ";
4978 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4979 info, n_value, c.protocols);
4980 if (n_value != 0) {
4981 if (info->verbose && sym_name != nullptr)
4982 outs() << sym_name;
4983 else
4984 outs() << format("0x%" PRIx64, n_value);
4985 if (c.protocols != 0)
4986 outs() << " + " << format("0x%" PRIx64, c.protocols);
4987 } else
4988 outs() << format("0x%" PRIx64, c.protocols);
4989 outs() << "\n";
4990 if (c.protocols + n_value != 0)
4991 print_protocol_list64_t(c.protocols + n_value, info);
4992
4993 outs() << "instanceProperties ";
4994 sym_name =
4995 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4996 S, info, n_value, c.instanceProperties);
4997 if (n_value != 0) {
4998 if (info->verbose && sym_name != nullptr)
4999 outs() << sym_name;
5000 else
5001 outs() << format("0x%" PRIx64, n_value);
5002 if (c.instanceProperties != 0)
5003 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5004 } else
5005 outs() << format("0x%" PRIx64, c.instanceProperties);
5006 outs() << "\n";
5007 if (c.instanceProperties + n_value != 0)
5008 print_objc_property_list64(c.instanceProperties + n_value, info);
5009}
5010
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005011static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5012 struct category32_t c;
5013 const char *r;
5014 uint32_t offset, left;
5015 SectionRef S, xS;
5016 const char *name;
5017
5018 r = get_pointer_32(p, offset, left, S, info);
5019 if (r == nullptr)
5020 return;
5021 memset(&c, '\0', sizeof(struct category32_t));
5022 if (left < sizeof(struct category32_t)) {
5023 memcpy(&c, r, left);
5024 outs() << " (category_t entends past the end of the section)\n";
5025 } else
5026 memcpy(&c, r, sizeof(struct category32_t));
5027 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5028 swapStruct(c);
5029
5030 outs() << " name " << format("0x%" PRIx32, c.name);
5031 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5032 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005033 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005034 outs() << " " << name;
5035 outs() << "\n";
5036
5037 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5038 if (c.cls != 0)
5039 print_class32_t(c.cls, info);
5040 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5041 << "\n";
5042 if (c.instanceMethods != 0)
5043 print_method_list32_t(c.instanceMethods, info, "");
5044 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5045 << "\n";
5046 if (c.classMethods != 0)
5047 print_method_list32_t(c.classMethods, info, "");
5048 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5049 if (c.protocols != 0)
5050 print_protocol_list32_t(c.protocols, info);
5051 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5052 << "\n";
5053 if (c.instanceProperties != 0)
5054 print_objc_property_list32(c.instanceProperties, info);
5055}
5056
Kevin Enderby0fc11822015-04-01 20:57:01 +00005057static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5058 uint32_t i, left, offset, xoffset;
5059 uint64_t p, n_value;
5060 struct message_ref64 mr;
5061 const char *name, *sym_name;
5062 const char *r;
5063 SectionRef xS;
5064
5065 if (S == SectionRef())
5066 return;
5067
5068 StringRef SectName;
5069 S.getName(SectName);
5070 DataRefImpl Ref = S.getRawDataRefImpl();
5071 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5072 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5073 offset = 0;
5074 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5075 p = S.getAddress() + i;
5076 r = get_pointer_64(p, offset, left, S, info);
5077 if (r == nullptr)
5078 return;
5079 memset(&mr, '\0', sizeof(struct message_ref64));
5080 if (left < sizeof(struct message_ref64)) {
5081 memcpy(&mr, r, left);
5082 outs() << " (message_ref entends past the end of the section)\n";
5083 } else
5084 memcpy(&mr, r, sizeof(struct message_ref64));
5085 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5086 swapStruct(mr);
5087
5088 outs() << " imp ";
5089 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5090 n_value, mr.imp);
5091 if (n_value != 0) {
5092 outs() << format("0x%" PRIx64, n_value) << " ";
5093 if (mr.imp != 0)
5094 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5095 } else
5096 outs() << format("0x%" PRIx64, mr.imp) << " ";
5097 if (name != nullptr)
5098 outs() << " " << name;
5099 outs() << "\n";
5100
5101 outs() << " sel ";
5102 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5103 info, n_value, mr.sel);
5104 if (n_value != 0) {
5105 if (info->verbose && sym_name != nullptr)
5106 outs() << sym_name;
5107 else
5108 outs() << format("0x%" PRIx64, n_value);
5109 if (mr.sel != 0)
5110 outs() << " + " << format("0x%" PRIx64, mr.sel);
5111 } else
5112 outs() << format("0x%" PRIx64, mr.sel);
5113 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5114 if (name != nullptr)
5115 outs() << format(" %.*s", left, name);
5116 outs() << "\n";
5117
5118 offset += sizeof(struct message_ref64);
5119 }
5120}
5121
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005122static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5123 uint32_t i, left, offset, xoffset, p;
5124 struct message_ref32 mr;
5125 const char *name, *r;
5126 SectionRef xS;
5127
5128 if (S == SectionRef())
5129 return;
5130
5131 StringRef SectName;
5132 S.getName(SectName);
5133 DataRefImpl Ref = S.getRawDataRefImpl();
5134 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5135 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5136 offset = 0;
5137 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5138 p = S.getAddress() + i;
5139 r = get_pointer_32(p, offset, left, S, info);
5140 if (r == nullptr)
5141 return;
5142 memset(&mr, '\0', sizeof(struct message_ref32));
5143 if (left < sizeof(struct message_ref32)) {
5144 memcpy(&mr, r, left);
5145 outs() << " (message_ref entends past the end of the section)\n";
5146 } else
5147 memcpy(&mr, r, sizeof(struct message_ref32));
5148 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5149 swapStruct(mr);
5150
5151 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5152 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5153 mr.imp);
5154 if (name != nullptr)
5155 outs() << " " << name;
5156 outs() << "\n";
5157
5158 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5159 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5160 if (name != nullptr)
5161 outs() << " " << name;
5162 outs() << "\n";
5163
5164 offset += sizeof(struct message_ref32);
5165 }
5166}
5167
Kevin Enderby0fc11822015-04-01 20:57:01 +00005168static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5169 uint32_t left, offset, swift_version;
5170 uint64_t p;
5171 struct objc_image_info64 o;
5172 const char *r;
5173
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005174 if (S == SectionRef())
5175 return;
5176
Kevin Enderby0fc11822015-04-01 20:57:01 +00005177 StringRef SectName;
5178 S.getName(SectName);
5179 DataRefImpl Ref = S.getRawDataRefImpl();
5180 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5181 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5182 p = S.getAddress();
5183 r = get_pointer_64(p, offset, left, S, info);
5184 if (r == nullptr)
5185 return;
5186 memset(&o, '\0', sizeof(struct objc_image_info64));
5187 if (left < sizeof(struct objc_image_info64)) {
5188 memcpy(&o, r, left);
5189 outs() << " (objc_image_info entends past the end of the section)\n";
5190 } else
5191 memcpy(&o, r, sizeof(struct objc_image_info64));
5192 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5193 swapStruct(o);
5194 outs() << " version " << o.version << "\n";
5195 outs() << " flags " << format("0x%" PRIx32, o.flags);
5196 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5197 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5198 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5199 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5200 swift_version = (o.flags >> 8) & 0xff;
5201 if (swift_version != 0) {
5202 if (swift_version == 1)
5203 outs() << " Swift 1.0";
5204 else if (swift_version == 2)
5205 outs() << " Swift 1.1";
5206 else
5207 outs() << " unknown future Swift version (" << swift_version << ")";
5208 }
5209 outs() << "\n";
5210}
5211
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005212static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5213 uint32_t left, offset, swift_version, p;
5214 struct objc_image_info32 o;
5215 const char *r;
5216
Kevin Enderby19be2512016-04-21 19:49:29 +00005217 if (S == SectionRef())
5218 return;
5219
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005220 StringRef SectName;
5221 S.getName(SectName);
5222 DataRefImpl Ref = S.getRawDataRefImpl();
5223 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5224 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5225 p = S.getAddress();
5226 r = get_pointer_32(p, offset, left, S, info);
5227 if (r == nullptr)
5228 return;
5229 memset(&o, '\0', sizeof(struct objc_image_info32));
5230 if (left < sizeof(struct objc_image_info32)) {
5231 memcpy(&o, r, left);
5232 outs() << " (objc_image_info entends past the end of the section)\n";
5233 } else
5234 memcpy(&o, r, sizeof(struct objc_image_info32));
5235 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5236 swapStruct(o);
5237 outs() << " version " << o.version << "\n";
5238 outs() << " flags " << format("0x%" PRIx32, o.flags);
5239 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5240 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5241 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5242 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5243 swift_version = (o.flags >> 8) & 0xff;
5244 if (swift_version != 0) {
5245 if (swift_version == 1)
5246 outs() << " Swift 1.0";
5247 else if (swift_version == 2)
5248 outs() << " Swift 1.1";
5249 else
5250 outs() << " unknown future Swift version (" << swift_version << ")";
5251 }
5252 outs() << "\n";
5253}
5254
Kevin Enderby846c0002015-04-16 17:19:59 +00005255static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5256 uint32_t left, offset, p;
5257 struct imageInfo_t o;
5258 const char *r;
5259
5260 StringRef SectName;
5261 S.getName(SectName);
5262 DataRefImpl Ref = S.getRawDataRefImpl();
5263 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5264 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5265 p = S.getAddress();
5266 r = get_pointer_32(p, offset, left, S, info);
5267 if (r == nullptr)
5268 return;
5269 memset(&o, '\0', sizeof(struct imageInfo_t));
5270 if (left < sizeof(struct imageInfo_t)) {
5271 memcpy(&o, r, left);
5272 outs() << " (imageInfo entends past the end of the section)\n";
5273 } else
5274 memcpy(&o, r, sizeof(struct imageInfo_t));
5275 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5276 swapStruct(o);
5277 outs() << " version " << o.version << "\n";
5278 outs() << " flags " << format("0x%" PRIx32, o.flags);
5279 if (o.flags & 0x1)
5280 outs() << " F&C";
5281 if (o.flags & 0x2)
5282 outs() << " GC";
5283 if (o.flags & 0x4)
5284 outs() << " GC-only";
5285 else
5286 outs() << " RR";
5287 outs() << "\n";
5288}
5289
Kevin Enderby0fc11822015-04-01 20:57:01 +00005290static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5291 SymbolAddressMap AddrMap;
5292 if (verbose)
5293 CreateSymbolAddressMap(O, &AddrMap);
5294
5295 std::vector<SectionRef> Sections;
5296 for (const SectionRef &Section : O->sections()) {
5297 StringRef SectName;
5298 Section.getName(SectName);
5299 Sections.push_back(Section);
5300 }
5301
5302 struct DisassembleInfo info;
5303 // Set up the block of info used by the Symbolizer call backs.
5304 info.verbose = verbose;
5305 info.O = O;
5306 info.AddrMap = &AddrMap;
5307 info.Sections = &Sections;
5308 info.class_name = nullptr;
5309 info.selector_name = nullptr;
5310 info.method = nullptr;
5311 info.demangled_name = nullptr;
5312 info.bindtable = nullptr;
5313 info.adrp_addr = 0;
5314 info.adrp_inst = 0;
5315
Kevin Enderbyaac75382015-10-08 16:56:35 +00005316 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005317 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5318 if (CL == SectionRef())
5319 CL = get_section(O, "__DATA", "__objc_classlist");
5320 info.S = CL;
5321 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005322
Davide Italiano62507042015-12-11 22:27:59 +00005323 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5324 if (CR == SectionRef())
5325 CR = get_section(O, "__DATA", "__objc_classrefs");
5326 info.S = CR;
5327 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005328
Davide Italiano62507042015-12-11 22:27:59 +00005329 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5330 if (SR == SectionRef())
5331 SR = get_section(O, "__DATA", "__objc_superrefs");
5332 info.S = SR;
5333 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005334
Davide Italiano62507042015-12-11 22:27:59 +00005335 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5336 if (CA == SectionRef())
5337 CA = get_section(O, "__DATA", "__objc_catlist");
5338 info.S = CA;
5339 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005340
Davide Italiano62507042015-12-11 22:27:59 +00005341 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5342 if (PL == SectionRef())
5343 PL = get_section(O, "__DATA", "__objc_protolist");
5344 info.S = PL;
5345 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005346
Davide Italiano62507042015-12-11 22:27:59 +00005347 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5348 if (MR == SectionRef())
5349 MR = get_section(O, "__DATA", "__objc_msgrefs");
5350 info.S = MR;
5351 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005352
Davide Italiano62507042015-12-11 22:27:59 +00005353 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5354 if (II == SectionRef())
5355 II = get_section(O, "__DATA", "__objc_imageinfo");
5356 info.S = II;
5357 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005358
5359 if (info.bindtable != nullptr)
5360 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005361}
5362
5363static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005364 SymbolAddressMap AddrMap;
5365 if (verbose)
5366 CreateSymbolAddressMap(O, &AddrMap);
5367
5368 std::vector<SectionRef> Sections;
5369 for (const SectionRef &Section : O->sections()) {
5370 StringRef SectName;
5371 Section.getName(SectName);
5372 Sections.push_back(Section);
5373 }
5374
5375 struct DisassembleInfo info;
5376 // Set up the block of info used by the Symbolizer call backs.
5377 info.verbose = verbose;
5378 info.O = O;
5379 info.AddrMap = &AddrMap;
5380 info.Sections = &Sections;
5381 info.class_name = nullptr;
5382 info.selector_name = nullptr;
5383 info.method = nullptr;
5384 info.demangled_name = nullptr;
5385 info.bindtable = nullptr;
5386 info.adrp_addr = 0;
5387 info.adrp_inst = 0;
5388
5389 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5390 if (CL != SectionRef()) {
5391 info.S = CL;
5392 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5393 } else {
5394 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5395 info.S = CL;
5396 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5397 }
5398
5399 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5400 if (CR != SectionRef()) {
5401 info.S = CR;
5402 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5403 } else {
5404 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5405 info.S = CR;
5406 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5407 }
5408
5409 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5410 if (SR != SectionRef()) {
5411 info.S = SR;
5412 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5413 } else {
5414 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5415 info.S = SR;
5416 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5417 }
5418
5419 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5420 if (CA != SectionRef()) {
5421 info.S = CA;
5422 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5423 } else {
5424 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5425 info.S = CA;
5426 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5427 }
5428
5429 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5430 if (PL != SectionRef()) {
5431 info.S = PL;
5432 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5433 } else {
5434 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5435 info.S = PL;
5436 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5437 }
5438
5439 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5440 if (MR != SectionRef()) {
5441 info.S = MR;
5442 print_message_refs32(MR, &info);
5443 } else {
5444 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5445 info.S = MR;
5446 print_message_refs32(MR, &info);
5447 }
5448
5449 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5450 if (II != SectionRef()) {
5451 info.S = II;
5452 print_image_info32(II, &info);
5453 } else {
5454 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5455 info.S = II;
5456 print_image_info32(II, &info);
5457 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005458}
5459
5460static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005461 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5462 const char *r, *name, *defs;
5463 struct objc_module_t module;
5464 SectionRef S, xS;
5465 struct objc_symtab_t symtab;
5466 struct objc_class_t objc_class;
5467 struct objc_category_t objc_category;
5468
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005469 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005470 S = get_section(O, "__OBJC", "__module_info");
5471 if (S == SectionRef())
5472 return false;
5473
5474 SymbolAddressMap AddrMap;
5475 if (verbose)
5476 CreateSymbolAddressMap(O, &AddrMap);
5477
5478 std::vector<SectionRef> Sections;
5479 for (const SectionRef &Section : O->sections()) {
5480 StringRef SectName;
5481 Section.getName(SectName);
5482 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005483 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005484
5485 struct DisassembleInfo info;
5486 // Set up the block of info used by the Symbolizer call backs.
5487 info.verbose = verbose;
5488 info.O = O;
5489 info.AddrMap = &AddrMap;
5490 info.Sections = &Sections;
5491 info.class_name = nullptr;
5492 info.selector_name = nullptr;
5493 info.method = nullptr;
5494 info.demangled_name = nullptr;
5495 info.bindtable = nullptr;
5496 info.adrp_addr = 0;
5497 info.adrp_inst = 0;
5498
5499 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5500 p = S.getAddress() + i;
5501 r = get_pointer_32(p, offset, left, S, &info, true);
5502 if (r == nullptr)
5503 return true;
5504 memset(&module, '\0', sizeof(struct objc_module_t));
5505 if (left < sizeof(struct objc_module_t)) {
5506 memcpy(&module, r, left);
5507 outs() << " (module extends past end of __module_info section)\n";
5508 } else
5509 memcpy(&module, r, sizeof(struct objc_module_t));
5510 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5511 swapStruct(module);
5512
5513 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5514 outs() << " version " << module.version << "\n";
5515 outs() << " size " << module.size << "\n";
5516 outs() << " name ";
5517 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5518 if (name != nullptr)
5519 outs() << format("%.*s", left, name);
5520 else
5521 outs() << format("0x%08" PRIx32, module.name)
5522 << "(not in an __OBJC section)";
5523 outs() << "\n";
5524
5525 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5526 if (module.symtab == 0 || r == nullptr) {
5527 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5528 << " (not in an __OBJC section)\n";
5529 continue;
5530 }
5531 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5532 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5533 defs_left = 0;
5534 defs = nullptr;
5535 if (left < sizeof(struct objc_symtab_t)) {
5536 memcpy(&symtab, r, left);
5537 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5538 } else {
5539 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5540 if (left > sizeof(struct objc_symtab_t)) {
5541 defs_left = left - sizeof(struct objc_symtab_t);
5542 defs = r + sizeof(struct objc_symtab_t);
5543 }
5544 }
5545 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5546 swapStruct(symtab);
5547
5548 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5549 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5550 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5551 if (r == nullptr)
5552 outs() << " (not in an __OBJC section)";
5553 outs() << "\n";
5554 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5555 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5556 if (symtab.cls_def_cnt > 0)
5557 outs() << "\tClass Definitions\n";
5558 for (j = 0; j < symtab.cls_def_cnt; j++) {
5559 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5560 outs() << "\t(remaining class defs entries entends past the end of the "
5561 << "section)\n";
5562 break;
5563 }
5564 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5565 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5566 sys::swapByteOrder(def);
5567
5568 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5569 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5570 if (r != nullptr) {
5571 if (left > sizeof(struct objc_class_t)) {
5572 outs() << "\n";
5573 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5574 } else {
5575 outs() << " (entends past the end of the section)\n";
5576 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5577 memcpy(&objc_class, r, left);
5578 }
5579 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5580 swapStruct(objc_class);
5581 print_objc_class_t(&objc_class, &info);
5582 } else {
5583 outs() << "(not in an __OBJC section)\n";
5584 }
5585
5586 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5587 outs() << "\tMeta Class";
5588 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5589 if (r != nullptr) {
5590 if (left > sizeof(struct objc_class_t)) {
5591 outs() << "\n";
5592 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5593 } else {
5594 outs() << " (entends past the end of the section)\n";
5595 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5596 memcpy(&objc_class, r, left);
5597 }
5598 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5599 swapStruct(objc_class);
5600 print_objc_class_t(&objc_class, &info);
5601 } else {
5602 outs() << "(not in an __OBJC section)\n";
5603 }
5604 }
5605 }
5606 if (symtab.cat_def_cnt > 0)
5607 outs() << "\tCategory Definitions\n";
5608 for (j = 0; j < symtab.cat_def_cnt; j++) {
5609 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5610 outs() << "\t(remaining category defs entries entends past the end of "
5611 << "the section)\n";
5612 break;
5613 }
5614 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5615 sizeof(uint32_t));
5616 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5617 sys::swapByteOrder(def);
5618
5619 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5620 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5621 << format("0x%08" PRIx32, def);
5622 if (r != nullptr) {
5623 if (left > sizeof(struct objc_category_t)) {
5624 outs() << "\n";
5625 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5626 } else {
5627 outs() << " (entends past the end of the section)\n";
5628 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5629 memcpy(&objc_category, r, left);
5630 }
5631 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5632 swapStruct(objc_category);
5633 print_objc_objc_category_t(&objc_category, &info);
5634 } else {
5635 outs() << "(not in an __OBJC section)\n";
5636 }
5637 }
5638 }
5639 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5640 if (II != SectionRef())
5641 print_image_info(II, &info);
5642
5643 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005644}
5645
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005646static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5647 uint32_t size, uint32_t addr) {
5648 SymbolAddressMap AddrMap;
5649 CreateSymbolAddressMap(O, &AddrMap);
5650
5651 std::vector<SectionRef> Sections;
5652 for (const SectionRef &Section : O->sections()) {
5653 StringRef SectName;
5654 Section.getName(SectName);
5655 Sections.push_back(Section);
5656 }
5657
5658 struct DisassembleInfo info;
5659 // Set up the block of info used by the Symbolizer call backs.
5660 info.verbose = true;
5661 info.O = O;
5662 info.AddrMap = &AddrMap;
5663 info.Sections = &Sections;
5664 info.class_name = nullptr;
5665 info.selector_name = nullptr;
5666 info.method = nullptr;
5667 info.demangled_name = nullptr;
5668 info.bindtable = nullptr;
5669 info.adrp_addr = 0;
5670 info.adrp_inst = 0;
5671
5672 const char *p;
5673 struct objc_protocol_t protocol;
5674 uint32_t left, paddr;
5675 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5676 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5677 left = size - (p - sect);
5678 if (left < sizeof(struct objc_protocol_t)) {
5679 outs() << "Protocol extends past end of __protocol section\n";
5680 memcpy(&protocol, p, left);
5681 } else
5682 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5683 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5684 swapStruct(protocol);
5685 paddr = addr + (p - sect);
5686 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5687 if (print_protocol(paddr, 0, &info))
5688 outs() << "(not in an __OBJC section)\n";
5689 }
5690}
5691
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005692#ifdef HAVE_LIBXAR
5693inline void swapStruct(struct xar_header &xar) {
5694 sys::swapByteOrder(xar.magic);
5695 sys::swapByteOrder(xar.size);
5696 sys::swapByteOrder(xar.version);
5697 sys::swapByteOrder(xar.toc_length_compressed);
5698 sys::swapByteOrder(xar.toc_length_uncompressed);
5699 sys::swapByteOrder(xar.cksum_alg);
5700}
5701
5702static void PrintModeVerbose(uint32_t mode) {
5703 switch(mode & S_IFMT){
5704 case S_IFDIR:
5705 outs() << "d";
5706 break;
5707 case S_IFCHR:
5708 outs() << "c";
5709 break;
5710 case S_IFBLK:
5711 outs() << "b";
5712 break;
5713 case S_IFREG:
5714 outs() << "-";
5715 break;
5716 case S_IFLNK:
5717 outs() << "l";
5718 break;
5719 case S_IFSOCK:
5720 outs() << "s";
5721 break;
5722 default:
5723 outs() << "?";
5724 break;
5725 }
5726
5727 /* owner permissions */
5728 if(mode & S_IREAD)
5729 outs() << "r";
5730 else
5731 outs() << "-";
5732 if(mode & S_IWRITE)
5733 outs() << "w";
5734 else
5735 outs() << "-";
5736 if(mode & S_ISUID)
5737 outs() << "s";
5738 else if(mode & S_IEXEC)
5739 outs() << "x";
5740 else
5741 outs() << "-";
5742
5743 /* group permissions */
5744 if(mode & (S_IREAD >> 3))
5745 outs() << "r";
5746 else
5747 outs() << "-";
5748 if(mode & (S_IWRITE >> 3))
5749 outs() << "w";
5750 else
5751 outs() << "-";
5752 if(mode & S_ISGID)
5753 outs() << "s";
5754 else if(mode & (S_IEXEC >> 3))
5755 outs() << "x";
5756 else
5757 outs() << "-";
5758
5759 /* other permissions */
5760 if(mode & (S_IREAD >> 6))
5761 outs() << "r";
5762 else
5763 outs() << "-";
5764 if(mode & (S_IWRITE >> 6))
5765 outs() << "w";
5766 else
5767 outs() << "-";
5768 if(mode & S_ISVTX)
5769 outs() << "t";
5770 else if(mode & (S_IEXEC >> 6))
5771 outs() << "x";
5772 else
5773 outs() << "-";
5774}
5775
5776static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5777 xar_iter_t xi;
5778 xar_file_t xf;
5779 xar_iter_t xp;
5780 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5781 char *endp;
5782 uint32_t mode_value;
5783
5784 xi = xar_iter_new();
5785 if (!xi) {
5786 errs() << "Can't obtain an xar iterator for xar archive "
5787 << XarFilename << "\n";
5788 return;
5789 }
5790
5791 // Go through the xar's files.
5792 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5793 xp = xar_iter_new();
5794 if(!xp){
5795 errs() << "Can't obtain an xar iterator for xar archive "
5796 << XarFilename << "\n";
5797 return;
5798 }
5799 type = nullptr;
5800 mode = nullptr;
5801 user = nullptr;
5802 group = nullptr;
5803 size = nullptr;
5804 mtime = nullptr;
5805 name = nullptr;
5806 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5807 const char *val = nullptr;
5808 xar_prop_get(xf, key, &val);
5809#if 0 // Useful for debugging.
5810 outs() << "key: " << key << " value: " << val << "\n";
5811#endif
5812 if(strcmp(key, "type") == 0)
5813 type = val;
5814 if(strcmp(key, "mode") == 0)
5815 mode = val;
5816 if(strcmp(key, "user") == 0)
5817 user = val;
5818 if(strcmp(key, "group") == 0)
5819 group = val;
5820 if(strcmp(key, "data/size") == 0)
5821 size = val;
5822 if(strcmp(key, "mtime") == 0)
5823 mtime = val;
5824 if(strcmp(key, "name") == 0)
5825 name = val;
5826 }
5827 if(mode != nullptr){
5828 mode_value = strtoul(mode, &endp, 8);
5829 if(*endp != '\0')
5830 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5831 if(strcmp(type, "file") == 0)
5832 mode_value |= S_IFREG;
5833 PrintModeVerbose(mode_value);
5834 outs() << " ";
5835 }
5836 if(user != nullptr)
5837 outs() << format("%10s/", user);
5838 if(group != nullptr)
5839 outs() << format("%-10s ", group);
5840 if(size != nullptr)
5841 outs() << format("%7s ", size);
5842 if(mtime != nullptr){
5843 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5844 outs() << *m;
5845 if(*m == 'T')
5846 m++;
5847 outs() << " ";
5848 for( ; *m != 'Z' && *m != '\0'; m++)
5849 outs() << *m;
5850 outs() << " ";
5851 }
5852 if(name != nullptr)
5853 outs() << name;
5854 outs() << "\n";
5855 }
5856}
5857
5858static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5859 uint32_t size, bool verbose,
5860 bool PrintXarHeader, bool PrintXarFileHeaders,
5861 std::string XarMemberName) {
5862 if(size < sizeof(struct xar_header)) {
5863 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5864 "of struct xar_header)\n";
5865 return;
5866 }
5867 struct xar_header XarHeader;
5868 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5869 if (sys::IsLittleEndianHost)
5870 swapStruct(XarHeader);
5871 if (PrintXarHeader) {
5872 if (!XarMemberName.empty())
5873 outs() << "In xar member " << XarMemberName << ": ";
5874 else
5875 outs() << "For (__LLVM,__bundle) section: ";
5876 outs() << "xar header\n";
5877 if (XarHeader.magic == XAR_HEADER_MAGIC)
5878 outs() << " magic XAR_HEADER_MAGIC\n";
5879 else
5880 outs() << " magic "
5881 << format_hex(XarHeader.magic, 10, true)
5882 << " (not XAR_HEADER_MAGIC)\n";
5883 outs() << " size " << XarHeader.size << "\n";
5884 outs() << " version " << XarHeader.version << "\n";
5885 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5886 << "\n";
5887 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5888 << "\n";
5889 outs() << " cksum_alg ";
5890 switch (XarHeader.cksum_alg) {
5891 case XAR_CKSUM_NONE:
5892 outs() << "XAR_CKSUM_NONE\n";
5893 break;
5894 case XAR_CKSUM_SHA1:
5895 outs() << "XAR_CKSUM_SHA1\n";
5896 break;
5897 case XAR_CKSUM_MD5:
5898 outs() << "XAR_CKSUM_MD5\n";
5899 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005900#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005901 case XAR_CKSUM_SHA256:
5902 outs() << "XAR_CKSUM_SHA256\n";
5903 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005904#endif
5905#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005906 case XAR_CKSUM_SHA512:
5907 outs() << "XAR_CKSUM_SHA512\n";
5908 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005909#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005910 default:
5911 outs() << XarHeader.cksum_alg << "\n";
5912 }
5913 }
5914
5915 SmallString<128> XarFilename;
5916 int FD;
5917 std::error_code XarEC =
5918 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5919 if (XarEC) {
5920 errs() << XarEC.message() << "\n";
5921 return;
5922 }
5923 tool_output_file XarFile(XarFilename, FD);
5924 raw_fd_ostream &XarOut = XarFile.os();
5925 StringRef XarContents(sect, size);
5926 XarOut << XarContents;
5927 XarOut.close();
5928 if (XarOut.has_error())
5929 return;
5930
5931 xar_t xar = xar_open(XarFilename.c_str(), READ);
5932 if (!xar) {
5933 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5934 return;
5935 }
5936
5937 SmallString<128> TocFilename;
5938 std::error_code TocEC =
5939 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5940 if (TocEC) {
5941 errs() << TocEC.message() << "\n";
5942 return;
5943 }
5944 xar_serialize(xar, TocFilename.c_str());
5945
5946 if (PrintXarFileHeaders) {
5947 if (!XarMemberName.empty())
5948 outs() << "In xar member " << XarMemberName << ": ";
5949 else
5950 outs() << "For (__LLVM,__bundle) section: ";
5951 outs() << "xar archive files:\n";
5952 PrintXarFilesSummary(XarFilename.c_str(), xar);
5953 }
5954
5955 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5956 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5957 if (std::error_code EC = FileOrErr.getError()) {
5958 errs() << EC.message() << "\n";
5959 return;
5960 }
5961 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5962
5963 if (!XarMemberName.empty())
5964 outs() << "In xar member " << XarMemberName << ": ";
5965 else
5966 outs() << "For (__LLVM,__bundle) section: ";
5967 outs() << "xar table of contents:\n";
5968 outs() << Buffer->getBuffer() << "\n";
5969
5970 // TODO: Go through the xar's files.
5971 xar_iter_t xi = xar_iter_new();
5972 if(!xi){
5973 errs() << "Can't obtain an xar iterator for xar archive "
5974 << XarFilename.c_str() << "\n";
5975 xar_close(xar);
5976 return;
5977 }
5978 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5979 const char *key;
5980 xar_iter_t xp;
5981 const char *member_name, *member_type, *member_size_string;
5982 size_t member_size;
5983
5984 xp = xar_iter_new();
5985 if(!xp){
5986 errs() << "Can't obtain an xar iterator for xar archive "
5987 << XarFilename.c_str() << "\n";
5988 xar_close(xar);
5989 return;
5990 }
5991 member_name = NULL;
5992 member_type = NULL;
5993 member_size_string = NULL;
5994 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5995 const char *val = nullptr;
5996 xar_prop_get(xf, key, &val);
5997#if 0 // Useful for debugging.
5998 outs() << "key: " << key << " value: " << val << "\n";
5999#endif
6000 if(strcmp(key, "name") == 0)
6001 member_name = val;
6002 if(strcmp(key, "type") == 0)
6003 member_type = val;
6004 if(strcmp(key, "data/size") == 0)
6005 member_size_string = val;
6006 }
6007 /*
6008 * If we find a file with a name, date/size and type properties
6009 * and with the type being "file" see if that is a xar file.
6010 */
6011 if (member_name != NULL && member_type != NULL &&
6012 strcmp(member_type, "file") == 0 &&
6013 member_size_string != NULL){
6014 // Extract the file into a buffer.
6015 char *endptr;
6016 member_size = strtoul(member_size_string, &endptr, 10);
6017 if (*endptr == '\0' && member_size != 0) {
6018 char *buffer = (char *) ::operator new (member_size);
6019 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6020#if 0 // Useful for debugging.
6021 outs() << "xar member: " << member_name << " extracted\n";
6022#endif
6023 // Set the XarMemberName we want to see printed in the header.
6024 std::string OldXarMemberName;
6025 // If XarMemberName is already set this is nested. So
6026 // save the old name and create the nested name.
6027 if (!XarMemberName.empty()) {
6028 OldXarMemberName = XarMemberName;
6029 XarMemberName =
6030 (Twine("[") + XarMemberName + "]" + member_name).str();
6031 } else {
6032 OldXarMemberName = "";
6033 XarMemberName = member_name;
6034 }
6035 // See if this is could be a xar file (nested).
6036 if (member_size >= sizeof(struct xar_header)) {
6037#if 0 // Useful for debugging.
6038 outs() << "could be a xar file: " << member_name << "\n";
6039#endif
6040 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6041 if (sys::IsLittleEndianHost)
6042 swapStruct(XarHeader);
6043 if(XarHeader.magic == XAR_HEADER_MAGIC)
6044 DumpBitcodeSection(O, buffer, member_size, verbose,
6045 PrintXarHeader, PrintXarFileHeaders,
6046 XarMemberName);
6047 }
6048 XarMemberName = OldXarMemberName;
6049 }
6050 delete buffer;
6051 }
6052 }
6053 xar_iter_free(xp);
6054 }
6055 xar_close(xar);
6056}
6057#endif // defined(HAVE_LIBXAR)
6058
Kevin Enderby0fc11822015-04-01 20:57:01 +00006059static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6060 if (O->is64Bit())
6061 printObjc2_64bit_MetaData(O, verbose);
6062 else {
6063 MachO::mach_header H;
6064 H = O->getHeader();
6065 if (H.cputype == MachO::CPU_TYPE_ARM)
6066 printObjc2_32bit_MetaData(O, verbose);
6067 else {
6068 // This is the 32-bit non-arm cputype case. Which is normally
6069 // the first Objective-C ABI. But it may be the case of a
6070 // binary for the iOS simulator which is the second Objective-C
6071 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6072 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006073 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006074 printObjc2_32bit_MetaData(O, verbose);
6075 }
6076 }
6077}
6078
Kevin Enderbybf246f52014-09-24 23:08:22 +00006079// GuessLiteralPointer returns a string which for the item in the Mach-O file
6080// for the address passed in as ReferenceValue for printing as a comment with
6081// the instruction and also returns the corresponding type of that item
6082// indirectly through ReferenceType.
6083//
6084// If ReferenceValue is an address of literal cstring then a pointer to the
6085// cstring is returned and ReferenceType is set to
6086// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6087//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006088// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6089// Class ref that name is returned and the ReferenceType is set accordingly.
6090//
6091// Lastly, literals which are Symbol address in a literal pool are looked for
6092// and if found the symbol name is returned and ReferenceType is set to
6093// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6094//
6095// If there is no item in the Mach-O file for the address passed in as
6096// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006097static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6098 uint64_t ReferencePC,
6099 uint64_t *ReferenceType,
6100 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006101 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006102 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6103 uint64_t sect_addr = info->S.getAddress();
6104 uint64_t sect_offset = ReferencePC - sect_addr;
6105 bool reloc_found = false;
6106 DataRefImpl Rel;
6107 MachO::any_relocation_info RE;
6108 bool isExtern = false;
6109 SymbolRef Symbol;
6110 for (const RelocationRef &Reloc : info->S.relocations()) {
6111 uint64_t RelocOffset = Reloc.getOffset();
6112 if (RelocOffset == sect_offset) {
6113 Rel = Reloc.getRawDataRefImpl();
6114 RE = info->O->getRelocation(Rel);
6115 if (info->O->isRelocationScattered(RE))
6116 continue;
6117 isExtern = info->O->getPlainRelocationExternal(RE);
6118 if (isExtern) {
6119 symbol_iterator RelocSym = Reloc.getSymbol();
6120 Symbol = *RelocSym;
6121 }
6122 reloc_found = true;
6123 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006124 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006125 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006126 // If there is an external relocation entry for a symbol in a section
6127 // then used that symbol's value for the value of the reference.
6128 if (reloc_found && isExtern) {
6129 if (info->O->getAnyRelocationPCRel(RE)) {
6130 unsigned Type = info->O->getAnyRelocationType(RE);
6131 if (Type == MachO::X86_64_RELOC_SIGNED) {
6132 ReferenceValue = Symbol.getValue();
6133 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006134 }
6135 }
6136 }
6137
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006138 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6139 // Message refs and Class refs.
6140 bool classref, selref, msgref, cfstring;
6141 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6142 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006143 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006144 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6145 // And the pointer_value in that section is typically zero as it will be
6146 // set by dyld as part of the "bind information".
6147 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6148 if (name != nullptr) {
6149 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006150 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006151 if (class_name != nullptr && class_name[1] == '_' &&
6152 class_name[2] != '\0') {
6153 info->class_name = class_name + 2;
6154 return name;
6155 }
6156 }
6157 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006158
David Blaikie33dd45d02015-03-23 18:39:02 +00006159 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006160 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6161 const char *name =
6162 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6163 if (name != nullptr)
6164 info->class_name = name;
6165 else
6166 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006167 return name;
6168 }
6169
David Blaikie33dd45d02015-03-23 18:39:02 +00006170 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006171 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6172 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6173 return name;
6174 }
6175
David Blaikie33dd45d02015-03-23 18:39:02 +00006176 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006177 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6178
6179 if (pointer_value != 0)
6180 ReferenceValue = pointer_value;
6181
6182 const char *name = GuessCstringPointer(ReferenceValue, info);
6183 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006184 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006185 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6186 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006187 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006188 info->class_name = nullptr;
6189 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6190 info->selector_name = name;
6191 } else
6192 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6193 return name;
6194 }
6195
6196 // Lastly look for an indirect symbol with this ReferenceValue which is in
6197 // a literal pool. If found return that symbol name.
6198 name = GuessIndirectSymbol(ReferenceValue, info);
6199 if (name) {
6200 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6201 return name;
6202 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006203
6204 return nullptr;
6205}
6206
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006207// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006208// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006209// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6210// is created and returns the symbol name that matches the ReferenceValue or
6211// nullptr if none. The ReferenceType is passed in for the IN type of
6212// reference the instruction is making from the values in defined in the header
6213// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6214// Out type and the ReferenceName will also be set which is added as a comment
6215// to the disassembled instruction.
6216//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006217#if HAVE_CXXABI_H
6218// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006219// returned through ReferenceName and ReferenceType is set to
6220// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00006221#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006222//
6223// When this is called to get a symbol name for a branch target then the
6224// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6225// SymbolValue will be looked for in the indirect symbol table to determine if
6226// it is an address for a symbol stub. If so then the symbol name for that
6227// stub is returned indirectly through ReferenceName and then ReferenceType is
6228// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6229//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006230// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006231// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6232// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6233// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006234// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006235static const char *SymbolizerSymbolLookUp(void *DisInfo,
6236 uint64_t ReferenceValue,
6237 uint64_t *ReferenceType,
6238 uint64_t ReferencePC,
6239 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006240 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006241 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006242 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006243 *ReferenceName = nullptr;
6244 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006245 return nullptr;
6246 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006247
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006248 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006249
Kevin Enderby85974882014-09-26 22:20:44 +00006250 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6251 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006252 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006253 method_reference(info, ReferenceType, ReferenceName);
6254 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6255 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6256 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00006257#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006258 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006259 if (info->demangled_name != nullptr)
6260 free(info->demangled_name);
6261 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006262 info->demangled_name =
6263 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006264 if (info->demangled_name != nullptr) {
6265 *ReferenceName = info->demangled_name;
6266 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6267 } else
6268 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6269 } else
6270#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006271 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6272 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6273 *ReferenceName =
6274 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006275 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006276 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006277 else
6278 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006279 // If this is arm64 and the reference is an adrp instruction save the
6280 // instruction, passed in ReferenceValue and the address of the instruction
6281 // for use later if we see and add immediate instruction.
6282 } else if (info->O->getArch() == Triple::aarch64 &&
6283 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6284 info->adrp_inst = ReferenceValue;
6285 info->adrp_addr = ReferencePC;
6286 SymbolName = nullptr;
6287 *ReferenceName = nullptr;
6288 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6289 // If this is arm64 and reference is an add immediate instruction and we
6290 // have
6291 // seen an adrp instruction just before it and the adrp's Xd register
6292 // matches
6293 // this add's Xn register reconstruct the value being referenced and look to
6294 // see if it is a literal pointer. Note the add immediate instruction is
6295 // passed in ReferenceValue.
6296 } else if (info->O->getArch() == Triple::aarch64 &&
6297 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6298 ReferencePC - 4 == info->adrp_addr &&
6299 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6300 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6301 uint32_t addxri_inst;
6302 uint64_t adrp_imm, addxri_imm;
6303
6304 adrp_imm =
6305 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6306 if (info->adrp_inst & 0x0200000)
6307 adrp_imm |= 0xfffffffffc000000LL;
6308
6309 addxri_inst = ReferenceValue;
6310 addxri_imm = (addxri_inst >> 10) & 0xfff;
6311 if (((addxri_inst >> 22) & 0x3) == 1)
6312 addxri_imm <<= 12;
6313
6314 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6315 (adrp_imm << 12) + addxri_imm;
6316
6317 *ReferenceName =
6318 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6319 if (*ReferenceName == nullptr)
6320 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6321 // If this is arm64 and the reference is a load register instruction and we
6322 // have seen an adrp instruction just before it and the adrp's Xd register
6323 // matches this add's Xn register reconstruct the value being referenced and
6324 // look to see if it is a literal pointer. Note the load register
6325 // instruction is passed in ReferenceValue.
6326 } else if (info->O->getArch() == Triple::aarch64 &&
6327 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6328 ReferencePC - 4 == info->adrp_addr &&
6329 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6330 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6331 uint32_t ldrxui_inst;
6332 uint64_t adrp_imm, ldrxui_imm;
6333
6334 adrp_imm =
6335 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6336 if (info->adrp_inst & 0x0200000)
6337 adrp_imm |= 0xfffffffffc000000LL;
6338
6339 ldrxui_inst = ReferenceValue;
6340 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6341
6342 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6343 (adrp_imm << 12) + (ldrxui_imm << 3);
6344
6345 *ReferenceName =
6346 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6347 if (*ReferenceName == nullptr)
6348 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6349 }
6350 // If this arm64 and is an load register (PC-relative) instruction the
6351 // ReferenceValue is the PC plus the immediate value.
6352 else if (info->O->getArch() == Triple::aarch64 &&
6353 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6354 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6355 *ReferenceName =
6356 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6357 if (*ReferenceName == nullptr)
6358 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00006359 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00006360#if HAVE_CXXABI_H
6361 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6362 if (info->demangled_name != nullptr)
6363 free(info->demangled_name);
6364 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006365 info->demangled_name =
6366 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006367 if (info->demangled_name != nullptr) {
6368 *ReferenceName = info->demangled_name;
6369 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6370 }
6371 }
6372#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006373 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006374 *ReferenceName = nullptr;
6375 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6376 }
6377
6378 return SymbolName;
6379}
6380
Kevin Enderbybf246f52014-09-24 23:08:22 +00006381/// \brief Emits the comments that are stored in the CommentStream.
6382/// Each comment in the CommentStream must end with a newline.
6383static void emitComments(raw_svector_ostream &CommentStream,
6384 SmallString<128> &CommentsToEmit,
6385 formatted_raw_ostream &FormattedOS,
6386 const MCAsmInfo &MAI) {
6387 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006388 StringRef Comments = CommentsToEmit.str();
6389 // Get the default information for printing a comment.
6390 const char *CommentBegin = MAI.getCommentString();
6391 unsigned CommentColumn = MAI.getCommentColumn();
6392 bool IsFirst = true;
6393 while (!Comments.empty()) {
6394 if (!IsFirst)
6395 FormattedOS << '\n';
6396 // Emit a line of comments.
6397 FormattedOS.PadToColumn(CommentColumn);
6398 size_t Position = Comments.find('\n');
6399 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6400 // Move after the newline character.
6401 Comments = Comments.substr(Position + 1);
6402 IsFirst = false;
6403 }
6404 FormattedOS.flush();
6405
6406 // Tell the comment stream that the vector changed underneath it.
6407 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006408}
6409
Kevin Enderby95df54c2015-02-04 01:01:38 +00006410static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6411 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006412 const char *McpuDefault = nullptr;
6413 const Target *ThumbTarget = nullptr;
6414 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006415 if (!TheTarget) {
6416 // GetTarget prints out stuff.
6417 return;
6418 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006419 if (MCPU.empty() && McpuDefault)
6420 MCPU = McpuDefault;
6421
Ahmed Charles56440fd2014-03-06 05:51:42 +00006422 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006423 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006424 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006425 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006426
Kevin Enderbyc9595622014-08-06 23:24:41 +00006427 // Package up features to be passed to target/subtarget
6428 std::string FeaturesStr;
6429 if (MAttrs.size()) {
6430 SubtargetFeatures Features;
6431 for (unsigned i = 0; i != MAttrs.size(); ++i)
6432 Features.AddFeature(MAttrs[i]);
6433 FeaturesStr = Features.getString();
6434 }
6435
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006436 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006437 std::unique_ptr<const MCRegisterInfo> MRI(
6438 TheTarget->createMCRegInfo(TripleName));
6439 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006440 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006441 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006442 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006443 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006444 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006445 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006446 std::unique_ptr<MCSymbolizer> Symbolizer;
6447 struct DisassembleInfo SymbolizerInfo;
6448 std::unique_ptr<MCRelocationInfo> RelInfo(
6449 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6450 if (RelInfo) {
6451 Symbolizer.reset(TheTarget->createMCSymbolizer(
6452 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006453 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006454 DisAsm->setSymbolizer(std::move(Symbolizer));
6455 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006456 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006457 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006458 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006459 // Set the display preference for hex vs. decimal immediates.
6460 IP->setPrintImmHex(PrintImmHex);
6461 // Comment stream and backing vector.
6462 SmallString<128> CommentsToEmit;
6463 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006464 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6465 // if it is done then arm64 comments for string literals don't get printed
6466 // and some constant get printed instead and not setting it causes intel
6467 // (32-bit and 64-bit) comments printed with different spacing before the
6468 // comment causing different diffs with the 'C' disassembler library API.
6469 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006470
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006471 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006472 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006473 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006474 return;
6475 }
6476
Tim Northover09ca33e2016-04-22 23:23:31 +00006477 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006478 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6479 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6480 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006481 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006482 std::unique_ptr<MCInstPrinter> ThumbIP;
6483 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006484 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6485 struct DisassembleInfo ThumbSymbolizerInfo;
6486 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006487 if (ThumbTarget) {
6488 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6489 ThumbAsmInfo.reset(
6490 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6491 ThumbSTI.reset(
6492 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6493 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6494 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006495 MCContext *PtrThumbCtx = ThumbCtx.get();
6496 ThumbRelInfo.reset(
6497 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6498 if (ThumbRelInfo) {
6499 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6500 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006501 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006502 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6503 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006504 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6505 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006506 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6507 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006508 // Set the display preference for hex vs. decimal immediates.
6509 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006510 }
6511
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006512 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006513 errs() << "error: couldn't initialize disassembler for target "
6514 << ThumbTripleName << '\n';
6515 return;
6516 }
6517
Charles Davis8bdfafd2013-09-01 04:28:48 +00006518 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006519
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006520 // FIXME: Using the -cfg command line option, this code used to be able to
6521 // annotate relocations with the referenced symbol's name, and if this was
6522 // inside a __[cf]string section, the data it points to. This is now replaced
6523 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006524 std::vector<SectionRef> Sections;
6525 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006526 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006527 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006528
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006529 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006530 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006531
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006532 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006533 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006534
Kevin Enderby273ae012013-06-06 17:20:50 +00006535 // Build a data in code table that is sorted on by the address of each entry.
6536 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006537 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006538 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006539 else
6540 BaseAddress = BaseSegmentAddress;
6541 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006542 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006543 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006544 uint32_t Offset;
6545 DI->getOffset(Offset);
6546 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6547 }
6548 array_pod_sort(Dices.begin(), Dices.end());
6549
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006550#ifndef NDEBUG
6551 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6552#else
6553 raw_ostream &DebugOut = nulls();
6554#endif
6555
Ahmed Charles56440fd2014-03-06 05:51:42 +00006556 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006557 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006558 // Try to find debug info and set up the DIContext for it.
6559 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006560 // A separate DSym file path was specified, parse it as a macho file,
6561 // get the sections and supply it to the section name parsing machinery.
6562 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006563 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006564 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006565 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006566 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006567 return;
6568 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006569 DbgObj =
6570 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6571 .get()
6572 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006573 }
6574
Eric Christopher7370b552012-11-12 21:40:38 +00006575 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006576 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006577 }
6578
Colin LeMahieufcc32762015-07-29 19:08:10 +00006579 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006580 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006581
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006582 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006583 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006584 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6585 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006586
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006587 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006588
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006589 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006590 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006591 continue;
6592
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006593 StringRef BytesStr;
6594 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006595 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6596 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006597 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006598
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006599 bool symbolTableWorked = false;
6600
Kevin Enderbybf246f52014-09-24 23:08:22 +00006601 // Create a map of symbol addresses to symbol names for use by
6602 // the SymbolizerSymbolLookUp() routine.
6603 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006604 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006605 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006606 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6607 if (!STOrErr) {
6608 std::string Buf;
6609 raw_string_ostream OS(Buf);
6610 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6611 OS.flush();
6612 report_fatal_error(Buf);
6613 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006614 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006615 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6616 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006617 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006618 Expected<StringRef> SymNameOrErr = Symbol.getName();
6619 if (!SymNameOrErr) {
6620 std::string Buf;
6621 raw_string_ostream OS(Buf);
6622 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6623 OS.flush();
6624 report_fatal_error(Buf);
6625 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006626 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006627 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006628 if (!DisSymName.empty() && DisSymName == SymName)
6629 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006630 }
6631 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006632 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006633 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6634 return;
6635 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006636 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006637 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006638 SymbolizerInfo.O = MachOOF;
6639 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006640 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006641 SymbolizerInfo.Sections = &Sections;
6642 SymbolizerInfo.class_name = nullptr;
6643 SymbolizerInfo.selector_name = nullptr;
6644 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006645 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006646 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006647 SymbolizerInfo.adrp_addr = 0;
6648 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006649 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006650 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006651 ThumbSymbolizerInfo.O = MachOOF;
6652 ThumbSymbolizerInfo.S = Sections[SectIdx];
6653 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6654 ThumbSymbolizerInfo.Sections = &Sections;
6655 ThumbSymbolizerInfo.class_name = nullptr;
6656 ThumbSymbolizerInfo.selector_name = nullptr;
6657 ThumbSymbolizerInfo.method = nullptr;
6658 ThumbSymbolizerInfo.demangled_name = nullptr;
6659 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006660 ThumbSymbolizerInfo.adrp_addr = 0;
6661 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006662
Kevin Enderby4b627be2016-04-28 20:14:13 +00006663 unsigned int Arch = MachOOF->getArch();
6664
Tim Northoverf203ab52016-07-14 22:13:32 +00006665 // Skip all symbols if this is a stubs file.
6666 if (Bytes.size() == 0)
6667 return;
6668
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006669 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006670 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006671 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6672 if (!SymNameOrErr) {
6673 std::string Buf;
6674 raw_string_ostream OS(Buf);
6675 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6676 OS.flush();
6677 report_fatal_error(Buf);
6678 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006679 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006680
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006681 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6682 if (!STOrErr) {
6683 std::string Buf;
6684 raw_string_ostream OS(Buf);
6685 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6686 OS.flush();
6687 report_fatal_error(Buf);
6688 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006689 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006690 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006691 continue;
6692
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006693 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006694 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006695 if (!containsSym) {
6696 if (!DisSymName.empty() && DisSymName == SymName) {
6697 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6698 return;
6699 }
6700 continue;
6701 }
6702 // The __mh_execute_header is special and we need to deal with that fact
6703 // this symbol is before the start of the (__TEXT,__text) section and at the
6704 // address of the start of the __TEXT segment. This is because this symbol
6705 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6706 // start of the section in a standard MH_EXECUTE filetype.
6707 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6708 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6709 return;
6710 }
6711 // When this code is trying to disassemble a symbol at a time and in the case
6712 // there is only the __mh_execute_header symbol left as in a stripped
6713 // executable, we need to deal with this by ignoring this symbol so the whole
6714 // section is disassembled and this symbol is then not displayed.
6715 if (SymName == "__mh_execute_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006716 continue;
6717
Kevin Enderby6a221752015-03-17 17:10:57 +00006718 // If we are only disassembling one symbol see if this is that symbol.
6719 if (!DisSymName.empty() && DisSymName != SymName)
6720 continue;
6721
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006722 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00006723 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00006724 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006725 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006726 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006727
Tim Northoverf203ab52016-07-14 22:13:32 +00006728 if (Start > SectSize) {
6729 outs() << "section data ends, " << SymName
6730 << " lies outside valid range\n";
6731 return;
6732 }
6733
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006734 // Stop disassembling either at the beginning of the next symbol or at
6735 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006736 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006737 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006738 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006739 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006740 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6741 if (!STOrErr) {
6742 std::string Buf;
6743 raw_string_ostream OS(Buf);
6744 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6745 OS.flush();
6746 report_fatal_error(Buf);
6747 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006748 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006749 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006750 containsNextSym =
6751 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006752 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006753 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006754 break;
6755 }
6756 ++NextSymIdx;
6757 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006758
Tim Northoverf203ab52016-07-14 22:13:32 +00006759 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006760 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006761
6762 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006763
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006764 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006765 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6766
6767 // We only need the dedicated Thumb target if there's a real choice
6768 // (i.e. we're not targeting M-class) and the function is Thumb.
6769 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006770
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006771 outs() << SymName << ":\n";
6772 DILineInfo lastLine;
6773 for (uint64_t Index = Start; Index < End; Index += Size) {
6774 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006775
Kevin Enderbybf246f52014-09-24 23:08:22 +00006776 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006777 if (!NoLeadingAddr) {
6778 if (FullLeadingAddr) {
6779 if (MachOOF->is64Bit())
6780 outs() << format("%016" PRIx64, PC);
6781 else
6782 outs() << format("%08" PRIx64, PC);
6783 } else {
6784 outs() << format("%8" PRIx64 ":", PC);
6785 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006786 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006787 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006788 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006789
6790 // Check the data in code table here to see if this is data not an
6791 // instruction to be disassembled.
6792 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006793 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006794 dice_table_iterator DTI =
6795 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6796 compareDiceTableEntries);
6797 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006798 uint16_t Length;
6799 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006800 uint16_t Kind;
6801 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006802 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006803 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6804 (PC == (DTI->first + Length - 1)) && (Length & 1))
6805 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006806 continue;
6807 }
6808
Kevin Enderbybf246f52014-09-24 23:08:22 +00006809 SmallVector<char, 64> AnnotationsBytes;
6810 raw_svector_ostream Annotations(AnnotationsBytes);
6811
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006812 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006813 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006814 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006815 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006816 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006817 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006818 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006819 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006820 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006821 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006822 }
6823 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006824 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006825 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006826 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006827 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006828 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006829 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006830
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006831 // Print debug info.
6832 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006833 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006834 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006835 if (dli != lastLine && dli.Line != 0)
6836 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6837 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006838 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006839 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006840 outs() << "\n";
6841 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006842 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006843 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006844 outs() << format("\t.byte 0x%02x #bad opcode\n",
6845 *(Bytes.data() + Index) & 0xff);
6846 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006847 } else if (Arch == Triple::aarch64 ||
6848 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006849 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6850 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6851 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6852 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6853 outs() << format("\t.long\t0x%08x\n", opcode);
6854 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006855 } else if (Arch == Triple::arm) {
6856 assert(IsThumb && "ARM mode should have been dealt with above");
6857 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6858 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6859 outs() << format("\t.short\t0x%04x\n", opcode);
6860 Size = 2;
6861 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006862 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6863 if (Size == 0)
6864 Size = 1; // skip illegible bytes
6865 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006866 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006867 }
6868 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006869 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006870 // Reading the symbol table didn't work, disassemble the whole section.
6871 uint64_t SectAddress = Sections[SectIdx].getAddress();
6872 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006873 uint64_t InstSize;
6874 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006875 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006876
Kevin Enderbybf246f52014-09-24 23:08:22 +00006877 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006878 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6879 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006880 if (!NoLeadingAddr) {
6881 if (FullLeadingAddr) {
6882 if (MachOOF->is64Bit())
6883 outs() << format("%016" PRIx64, PC);
6884 else
6885 outs() << format("%08" PRIx64, PC);
6886 } else {
6887 outs() << format("%8" PRIx64 ":", PC);
6888 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006889 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006890 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006891 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006892 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006893 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006894 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006895 outs() << "\n";
6896 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006897 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006898 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006899 outs() << format("\t.byte 0x%02x #bad opcode\n",
6900 *(Bytes.data() + Index) & 0xff);
6901 InstSize = 1; // skip exactly one illegible byte and move on.
6902 } else {
6903 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6904 if (InstSize == 0)
6905 InstSize = 1; // skip illegible bytes
6906 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006907 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006908 }
6909 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006910 // The TripleName's need to be reset if we are called again for a different
6911 // archtecture.
6912 TripleName = "";
6913 ThumbTripleName = "";
6914
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006915 if (SymbolizerInfo.method != nullptr)
6916 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006917 if (SymbolizerInfo.demangled_name != nullptr)
6918 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006919 if (SymbolizerInfo.bindtable != nullptr)
6920 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006921 if (ThumbSymbolizerInfo.method != nullptr)
6922 free(ThumbSymbolizerInfo.method);
6923 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6924 free(ThumbSymbolizerInfo.demangled_name);
6925 if (ThumbSymbolizerInfo.bindtable != nullptr)
6926 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006927 }
6928}
Tim Northover4bd286a2014-08-01 13:07:19 +00006929
Tim Northover39c70bb2014-08-12 11:52:59 +00006930//===----------------------------------------------------------------------===//
6931// __compact_unwind section dumping
6932//===----------------------------------------------------------------------===//
6933
Tim Northover4bd286a2014-08-01 13:07:19 +00006934namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006935
6936template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006937 using llvm::support::little;
6938 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006939
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006940 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6941 Buf += sizeof(T);
6942 return Val;
6943}
Tim Northover39c70bb2014-08-12 11:52:59 +00006944
Tim Northover4bd286a2014-08-01 13:07:19 +00006945struct CompactUnwindEntry {
6946 uint32_t OffsetInSection;
6947
6948 uint64_t FunctionAddr;
6949 uint32_t Length;
6950 uint32_t CompactEncoding;
6951 uint64_t PersonalityAddr;
6952 uint64_t LSDAAddr;
6953
6954 RelocationRef FunctionReloc;
6955 RelocationRef PersonalityReloc;
6956 RelocationRef LSDAReloc;
6957
6958 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006959 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006960 if (Is64)
6961 read<uint64_t>(Contents.data() + Offset);
6962 else
6963 read<uint32_t>(Contents.data() + Offset);
6964 }
6965
6966private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006967 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006968 FunctionAddr = readNext<UIntPtr>(Buf);
6969 Length = readNext<uint32_t>(Buf);
6970 CompactEncoding = readNext<uint32_t>(Buf);
6971 PersonalityAddr = readNext<UIntPtr>(Buf);
6972 LSDAAddr = readNext<UIntPtr>(Buf);
6973 }
6974};
6975}
6976
6977/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6978/// and data being relocated, determine the best base Name and Addend to use for
6979/// display purposes.
6980///
6981/// 1. An Extern relocation will directly reference a symbol (and the data is
6982/// then already an addend), so use that.
6983/// 2. Otherwise the data is an offset in the object file's layout; try to find
6984// a symbol before it in the same section, and use the offset from there.
6985/// 3. Finally, if all that fails, fall back to an offset from the start of the
6986/// referenced section.
6987static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6988 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006989 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006990 StringRef &Name, uint64_t &Addend) {
6991 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006992 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6993 if (!NameOrErr) {
6994 std::string Buf;
6995 raw_string_ostream OS(Buf);
6996 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6997 OS.flush();
6998 report_fatal_error(Buf);
6999 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007000 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007001 Addend = Addr;
7002 return;
7003 }
7004
7005 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007006 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007007
Rafael Espindola80291272014-10-08 15:28:58 +00007008 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007009
7010 auto Sym = Symbols.upper_bound(Addr);
7011 if (Sym == Symbols.begin()) {
7012 // The first symbol in the object is after this reference, the best we can
7013 // do is section-relative notation.
7014 RelocSection.getName(Name);
7015 Addend = Addr - SectionAddr;
7016 return;
7017 }
7018
7019 // Go back one so that SymbolAddress <= Addr.
7020 --Sym;
7021
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007022 auto SectOrErr = Sym->second.getSection();
7023 if (!SectOrErr) {
7024 std::string Buf;
7025 raw_string_ostream OS(Buf);
7026 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
7027 OS.flush();
7028 report_fatal_error(Buf);
7029 }
7030 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007031 if (RelocSection == *SymSection) {
7032 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007033 Expected<StringRef> NameOrErr = Sym->second.getName();
7034 if (!NameOrErr) {
7035 std::string Buf;
7036 raw_string_ostream OS(Buf);
7037 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7038 OS.flush();
7039 report_fatal_error(Buf);
7040 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007041 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007042 Addend = Addr - Sym->first;
7043 return;
7044 }
7045
7046 // There is a symbol before this reference, but it's in a different
7047 // section. Probably not helpful to mention it, so use the section name.
7048 RelocSection.getName(Name);
7049 Addend = Addr - SectionAddr;
7050}
7051
7052static void printUnwindRelocDest(const MachOObjectFile *Obj,
7053 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007054 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007055 StringRef Name;
7056 uint64_t Addend;
7057
Rafael Espindola854038e2015-06-26 14:51:16 +00007058 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007059 return;
7060
Tim Northover4bd286a2014-08-01 13:07:19 +00007061 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7062
7063 outs() << Name;
7064 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007065 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007066}
7067
7068static void
7069printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7070 std::map<uint64_t, SymbolRef> &Symbols,
7071 const SectionRef &CompactUnwind) {
7072
7073 assert(Obj->isLittleEndian() &&
7074 "There should not be a big-endian .o with __compact_unwind");
7075
7076 bool Is64 = Obj->is64Bit();
7077 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7078 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7079
7080 StringRef Contents;
7081 CompactUnwind.getContents(Contents);
7082
7083 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7084
7085 // First populate the initial raw offsets, encodings and so on from the entry.
7086 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7087 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7088 CompactUnwinds.push_back(Entry);
7089 }
7090
7091 // Next we need to look at the relocations to find out what objects are
7092 // actually being referred to.
7093 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007094 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007095
7096 uint32_t EntryIdx = RelocAddress / EntrySize;
7097 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7098 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7099
7100 if (OffsetInEntry == 0)
7101 Entry.FunctionReloc = Reloc;
7102 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7103 Entry.PersonalityReloc = Reloc;
7104 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7105 Entry.LSDAReloc = Reloc;
7106 else
7107 llvm_unreachable("Unexpected relocation in __compact_unwind section");
7108 }
7109
7110 // Finally, we're ready to print the data we've gathered.
7111 outs() << "Contents of __compact_unwind section:\n";
7112 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007113 outs() << " Entry at offset "
7114 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007115
7116 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007117 outs() << " start: " << format("0x%" PRIx64,
7118 Entry.FunctionAddr) << ' ';
7119 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007120 outs() << '\n';
7121
7122 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007123 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7124 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007125 // 3. The 32-bit compact encoding.
7126 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007127 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007128
7129 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007130 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007131 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007132 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007133 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7134 Entry.PersonalityAddr);
7135 outs() << '\n';
7136 }
7137
7138 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007139 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007140 outs() << " LSDA: " << format("0x%" PRIx64,
7141 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007142 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7143 outs() << '\n';
7144 }
7145 }
7146}
7147
Tim Northover39c70bb2014-08-12 11:52:59 +00007148//===----------------------------------------------------------------------===//
7149// __unwind_info section dumping
7150//===----------------------------------------------------------------------===//
7151
7152static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7153 const char *Pos = PageStart;
7154 uint32_t Kind = readNext<uint32_t>(Pos);
7155 (void)Kind;
7156 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7157
7158 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7159 uint16_t NumEntries = readNext<uint16_t>(Pos);
7160
7161 Pos = PageStart + EntriesStart;
7162 for (unsigned i = 0; i < NumEntries; ++i) {
7163 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7164 uint32_t Encoding = readNext<uint32_t>(Pos);
7165
7166 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007167 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7168 << ", "
7169 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007170 }
7171}
7172
7173static void printCompressedSecondLevelUnwindPage(
7174 const char *PageStart, uint32_t FunctionBase,
7175 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7176 const char *Pos = PageStart;
7177 uint32_t Kind = readNext<uint32_t>(Pos);
7178 (void)Kind;
7179 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7180
7181 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7182 uint16_t NumEntries = readNext<uint16_t>(Pos);
7183
7184 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7185 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007186 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7187 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007188
7189 Pos = PageStart + EntriesStart;
7190 for (unsigned i = 0; i < NumEntries; ++i) {
7191 uint32_t Entry = readNext<uint32_t>(Pos);
7192 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7193 uint32_t EncodingIdx = Entry >> 24;
7194
7195 uint32_t Encoding;
7196 if (EncodingIdx < CommonEncodings.size())
7197 Encoding = CommonEncodings[EncodingIdx];
7198 else
7199 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7200
7201 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007202 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7203 << ", "
7204 << "encoding[" << EncodingIdx
7205 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007206 }
7207}
7208
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007209static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7210 std::map<uint64_t, SymbolRef> &Symbols,
7211 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007212
7213 assert(Obj->isLittleEndian() &&
7214 "There should not be a big-endian .o with __unwind_info");
7215
7216 outs() << "Contents of __unwind_info section:\n";
7217
7218 StringRef Contents;
7219 UnwindInfo.getContents(Contents);
7220 const char *Pos = Contents.data();
7221
7222 //===----------------------------------
7223 // Section header
7224 //===----------------------------------
7225
7226 uint32_t Version = readNext<uint32_t>(Pos);
7227 outs() << " Version: "
7228 << format("0x%" PRIx32, Version) << '\n';
7229 assert(Version == 1 && "only understand version 1");
7230
7231 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7232 outs() << " Common encodings array section offset: "
7233 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7234 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7235 outs() << " Number of common encodings in array: "
7236 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7237
7238 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7239 outs() << " Personality function array section offset: "
7240 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7241 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7242 outs() << " Number of personality functions in array: "
7243 << format("0x%" PRIx32, NumPersonalities) << '\n';
7244
7245 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7246 outs() << " Index array section offset: "
7247 << format("0x%" PRIx32, IndicesStart) << '\n';
7248 uint32_t NumIndices = readNext<uint32_t>(Pos);
7249 outs() << " Number of indices in array: "
7250 << format("0x%" PRIx32, NumIndices) << '\n';
7251
7252 //===----------------------------------
7253 // A shared list of common encodings
7254 //===----------------------------------
7255
7256 // These occupy indices in the range [0, N] whenever an encoding is referenced
7257 // from a compressed 2nd level index table. In practice the linker only
7258 // creates ~128 of these, so that indices are available to embed encodings in
7259 // the 2nd level index.
7260
7261 SmallVector<uint32_t, 64> CommonEncodings;
7262 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7263 Pos = Contents.data() + CommonEncodingsStart;
7264 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7265 uint32_t Encoding = readNext<uint32_t>(Pos);
7266 CommonEncodings.push_back(Encoding);
7267
7268 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7269 << '\n';
7270 }
7271
Tim Northover39c70bb2014-08-12 11:52:59 +00007272 //===----------------------------------
7273 // Personality functions used in this executable
7274 //===----------------------------------
7275
7276 // There should be only a handful of these (one per source language,
7277 // roughly). Particularly since they only get 2 bits in the compact encoding.
7278
7279 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7280 Pos = Contents.data() + PersonalitiesStart;
7281 for (unsigned i = 0; i < NumPersonalities; ++i) {
7282 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7283 outs() << " personality[" << i + 1
7284 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7285 }
7286
7287 //===----------------------------------
7288 // The level 1 index entries
7289 //===----------------------------------
7290
7291 // These specify an approximate place to start searching for the more detailed
7292 // information, sorted by PC.
7293
7294 struct IndexEntry {
7295 uint32_t FunctionOffset;
7296 uint32_t SecondLevelPageStart;
7297 uint32_t LSDAStart;
7298 };
7299
7300 SmallVector<IndexEntry, 4> IndexEntries;
7301
7302 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7303 Pos = Contents.data() + IndicesStart;
7304 for (unsigned i = 0; i < NumIndices; ++i) {
7305 IndexEntry Entry;
7306
7307 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7308 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7309 Entry.LSDAStart = readNext<uint32_t>(Pos);
7310 IndexEntries.push_back(Entry);
7311
7312 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007313 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7314 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007315 << "2nd level page offset="
7316 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007317 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007318 }
7319
Tim Northover39c70bb2014-08-12 11:52:59 +00007320 //===----------------------------------
7321 // Next come the LSDA tables
7322 //===----------------------------------
7323
7324 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7325 // the first top-level index's LSDAOffset to the last (sentinel).
7326
7327 outs() << " LSDA descriptors:\n";
7328 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7329 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7330 (2 * sizeof(uint32_t));
7331 for (int i = 0; i < NumLSDAs; ++i) {
7332 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7333 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7334 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007335 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7336 << ", "
7337 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007338 }
7339
7340 //===----------------------------------
7341 // Finally, the 2nd level indices
7342 //===----------------------------------
7343
7344 // Generally these are 4K in size, and have 2 possible forms:
7345 // + Regular stores up to 511 entries with disparate encodings
7346 // + Compressed stores up to 1021 entries if few enough compact encoding
7347 // values are used.
7348 outs() << " Second level indices:\n";
7349 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7350 // The final sentinel top-level index has no associated 2nd level page
7351 if (IndexEntries[i].SecondLevelPageStart == 0)
7352 break;
7353
7354 outs() << " Second level index[" << i << "]: "
7355 << "offset in section="
7356 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7357 << ", "
7358 << "base function offset="
7359 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7360
7361 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007362 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007363 if (Kind == 2)
7364 printRegularSecondLevelUnwindPage(Pos);
7365 else if (Kind == 3)
7366 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7367 CommonEncodings);
7368 else
7369 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00007370 }
7371}
7372
Tim Northover4bd286a2014-08-01 13:07:19 +00007373void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7374 std::map<uint64_t, SymbolRef> Symbols;
7375 for (const SymbolRef &SymRef : Obj->symbols()) {
7376 // Discard any undefined or absolute symbols. They're not going to take part
7377 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007378 auto SectOrErr = SymRef.getSection();
7379 if (!SectOrErr) {
7380 // TODO: Actually report errors helpfully.
7381 consumeError(SectOrErr.takeError());
7382 continue;
7383 }
7384 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007385 if (Section == Obj->section_end())
7386 continue;
7387
Rafael Espindoladea00162015-07-03 17:44:18 +00007388 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007389 Symbols.insert(std::make_pair(Addr, SymRef));
7390 }
7391
7392 for (const SectionRef &Section : Obj->sections()) {
7393 StringRef SectName;
7394 Section.getName(SectName);
7395 if (SectName == "__compact_unwind")
7396 printMachOCompactUnwindSection(Obj, Symbols, Section);
7397 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007398 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007399 }
7400}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007401
7402static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7403 uint32_t cpusubtype, uint32_t filetype,
7404 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7405 bool verbose) {
7406 outs() << "Mach header\n";
7407 outs() << " magic cputype cpusubtype caps filetype ncmds "
7408 "sizeofcmds flags\n";
7409 if (verbose) {
7410 if (magic == MachO::MH_MAGIC)
7411 outs() << " MH_MAGIC";
7412 else if (magic == MachO::MH_MAGIC_64)
7413 outs() << "MH_MAGIC_64";
7414 else
7415 outs() << format(" 0x%08" PRIx32, magic);
7416 switch (cputype) {
7417 case MachO::CPU_TYPE_I386:
7418 outs() << " I386";
7419 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7420 case MachO::CPU_SUBTYPE_I386_ALL:
7421 outs() << " ALL";
7422 break;
7423 default:
7424 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7425 break;
7426 }
7427 break;
7428 case MachO::CPU_TYPE_X86_64:
7429 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007430 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7431 case MachO::CPU_SUBTYPE_X86_64_ALL:
7432 outs() << " ALL";
7433 break;
7434 case MachO::CPU_SUBTYPE_X86_64_H:
7435 outs() << " Haswell";
7436 break;
7437 default:
7438 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7439 break;
7440 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007441 break;
7442 case MachO::CPU_TYPE_ARM:
7443 outs() << " ARM";
7444 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7445 case MachO::CPU_SUBTYPE_ARM_ALL:
7446 outs() << " ALL";
7447 break;
7448 case MachO::CPU_SUBTYPE_ARM_V4T:
7449 outs() << " V4T";
7450 break;
7451 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7452 outs() << " V5TEJ";
7453 break;
7454 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7455 outs() << " XSCALE";
7456 break;
7457 case MachO::CPU_SUBTYPE_ARM_V6:
7458 outs() << " V6";
7459 break;
7460 case MachO::CPU_SUBTYPE_ARM_V6M:
7461 outs() << " V6M";
7462 break;
7463 case MachO::CPU_SUBTYPE_ARM_V7:
7464 outs() << " V7";
7465 break;
7466 case MachO::CPU_SUBTYPE_ARM_V7EM:
7467 outs() << " V7EM";
7468 break;
7469 case MachO::CPU_SUBTYPE_ARM_V7K:
7470 outs() << " V7K";
7471 break;
7472 case MachO::CPU_SUBTYPE_ARM_V7M:
7473 outs() << " V7M";
7474 break;
7475 case MachO::CPU_SUBTYPE_ARM_V7S:
7476 outs() << " V7S";
7477 break;
7478 default:
7479 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7480 break;
7481 }
7482 break;
7483 case MachO::CPU_TYPE_ARM64:
7484 outs() << " ARM64";
7485 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7486 case MachO::CPU_SUBTYPE_ARM64_ALL:
7487 outs() << " ALL";
7488 break;
7489 default:
7490 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7491 break;
7492 }
7493 break;
7494 case MachO::CPU_TYPE_POWERPC:
7495 outs() << " PPC";
7496 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7497 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7498 outs() << " ALL";
7499 break;
7500 default:
7501 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7502 break;
7503 }
7504 break;
7505 case MachO::CPU_TYPE_POWERPC64:
7506 outs() << " PPC64";
7507 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7508 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7509 outs() << " ALL";
7510 break;
7511 default:
7512 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7513 break;
7514 }
7515 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007516 default:
7517 outs() << format(" %7d", cputype);
7518 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7519 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007520 }
7521 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007522 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007523 } else {
7524 outs() << format(" 0x%02" PRIx32,
7525 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7526 }
7527 switch (filetype) {
7528 case MachO::MH_OBJECT:
7529 outs() << " OBJECT";
7530 break;
7531 case MachO::MH_EXECUTE:
7532 outs() << " EXECUTE";
7533 break;
7534 case MachO::MH_FVMLIB:
7535 outs() << " FVMLIB";
7536 break;
7537 case MachO::MH_CORE:
7538 outs() << " CORE";
7539 break;
7540 case MachO::MH_PRELOAD:
7541 outs() << " PRELOAD";
7542 break;
7543 case MachO::MH_DYLIB:
7544 outs() << " DYLIB";
7545 break;
7546 case MachO::MH_DYLIB_STUB:
7547 outs() << " DYLIB_STUB";
7548 break;
7549 case MachO::MH_DYLINKER:
7550 outs() << " DYLINKER";
7551 break;
7552 case MachO::MH_BUNDLE:
7553 outs() << " BUNDLE";
7554 break;
7555 case MachO::MH_DSYM:
7556 outs() << " DSYM";
7557 break;
7558 case MachO::MH_KEXT_BUNDLE:
7559 outs() << " KEXTBUNDLE";
7560 break;
7561 default:
7562 outs() << format(" %10u", filetype);
7563 break;
7564 }
7565 outs() << format(" %5u", ncmds);
7566 outs() << format(" %10u", sizeofcmds);
7567 uint32_t f = flags;
7568 if (f & MachO::MH_NOUNDEFS) {
7569 outs() << " NOUNDEFS";
7570 f &= ~MachO::MH_NOUNDEFS;
7571 }
7572 if (f & MachO::MH_INCRLINK) {
7573 outs() << " INCRLINK";
7574 f &= ~MachO::MH_INCRLINK;
7575 }
7576 if (f & MachO::MH_DYLDLINK) {
7577 outs() << " DYLDLINK";
7578 f &= ~MachO::MH_DYLDLINK;
7579 }
7580 if (f & MachO::MH_BINDATLOAD) {
7581 outs() << " BINDATLOAD";
7582 f &= ~MachO::MH_BINDATLOAD;
7583 }
7584 if (f & MachO::MH_PREBOUND) {
7585 outs() << " PREBOUND";
7586 f &= ~MachO::MH_PREBOUND;
7587 }
7588 if (f & MachO::MH_SPLIT_SEGS) {
7589 outs() << " SPLIT_SEGS";
7590 f &= ~MachO::MH_SPLIT_SEGS;
7591 }
7592 if (f & MachO::MH_LAZY_INIT) {
7593 outs() << " LAZY_INIT";
7594 f &= ~MachO::MH_LAZY_INIT;
7595 }
7596 if (f & MachO::MH_TWOLEVEL) {
7597 outs() << " TWOLEVEL";
7598 f &= ~MachO::MH_TWOLEVEL;
7599 }
7600 if (f & MachO::MH_FORCE_FLAT) {
7601 outs() << " FORCE_FLAT";
7602 f &= ~MachO::MH_FORCE_FLAT;
7603 }
7604 if (f & MachO::MH_NOMULTIDEFS) {
7605 outs() << " NOMULTIDEFS";
7606 f &= ~MachO::MH_NOMULTIDEFS;
7607 }
7608 if (f & MachO::MH_NOFIXPREBINDING) {
7609 outs() << " NOFIXPREBINDING";
7610 f &= ~MachO::MH_NOFIXPREBINDING;
7611 }
7612 if (f & MachO::MH_PREBINDABLE) {
7613 outs() << " PREBINDABLE";
7614 f &= ~MachO::MH_PREBINDABLE;
7615 }
7616 if (f & MachO::MH_ALLMODSBOUND) {
7617 outs() << " ALLMODSBOUND";
7618 f &= ~MachO::MH_ALLMODSBOUND;
7619 }
7620 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7621 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7622 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7623 }
7624 if (f & MachO::MH_CANONICAL) {
7625 outs() << " CANONICAL";
7626 f &= ~MachO::MH_CANONICAL;
7627 }
7628 if (f & MachO::MH_WEAK_DEFINES) {
7629 outs() << " WEAK_DEFINES";
7630 f &= ~MachO::MH_WEAK_DEFINES;
7631 }
7632 if (f & MachO::MH_BINDS_TO_WEAK) {
7633 outs() << " BINDS_TO_WEAK";
7634 f &= ~MachO::MH_BINDS_TO_WEAK;
7635 }
7636 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7637 outs() << " ALLOW_STACK_EXECUTION";
7638 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7639 }
7640 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7641 outs() << " DEAD_STRIPPABLE_DYLIB";
7642 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7643 }
7644 if (f & MachO::MH_PIE) {
7645 outs() << " PIE";
7646 f &= ~MachO::MH_PIE;
7647 }
7648 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7649 outs() << " NO_REEXPORTED_DYLIBS";
7650 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7651 }
7652 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7653 outs() << " MH_HAS_TLV_DESCRIPTORS";
7654 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7655 }
7656 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7657 outs() << " MH_NO_HEAP_EXECUTION";
7658 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7659 }
7660 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7661 outs() << " APP_EXTENSION_SAFE";
7662 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7663 }
7664 if (f != 0 || flags == 0)
7665 outs() << format(" 0x%08" PRIx32, f);
7666 } else {
7667 outs() << format(" 0x%08" PRIx32, magic);
7668 outs() << format(" %7d", cputype);
7669 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7670 outs() << format(" 0x%02" PRIx32,
7671 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7672 outs() << format(" %10u", filetype);
7673 outs() << format(" %5u", ncmds);
7674 outs() << format(" %10u", sizeofcmds);
7675 outs() << format(" 0x%08" PRIx32, flags);
7676 }
7677 outs() << "\n";
7678}
7679
Kevin Enderby956366c2014-08-29 22:30:52 +00007680static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7681 StringRef SegName, uint64_t vmaddr,
7682 uint64_t vmsize, uint64_t fileoff,
7683 uint64_t filesize, uint32_t maxprot,
7684 uint32_t initprot, uint32_t nsects,
7685 uint32_t flags, uint32_t object_size,
7686 bool verbose) {
7687 uint64_t expected_cmdsize;
7688 if (cmd == MachO::LC_SEGMENT) {
7689 outs() << " cmd LC_SEGMENT\n";
7690 expected_cmdsize = nsects;
7691 expected_cmdsize *= sizeof(struct MachO::section);
7692 expected_cmdsize += sizeof(struct MachO::segment_command);
7693 } else {
7694 outs() << " cmd LC_SEGMENT_64\n";
7695 expected_cmdsize = nsects;
7696 expected_cmdsize *= sizeof(struct MachO::section_64);
7697 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7698 }
7699 outs() << " cmdsize " << cmdsize;
7700 if (cmdsize != expected_cmdsize)
7701 outs() << " Inconsistent size\n";
7702 else
7703 outs() << "\n";
7704 outs() << " segname " << SegName << "\n";
7705 if (cmd == MachO::LC_SEGMENT_64) {
7706 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7707 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7708 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007709 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7710 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007711 }
7712 outs() << " fileoff " << fileoff;
7713 if (fileoff > object_size)
7714 outs() << " (past end of file)\n";
7715 else
7716 outs() << "\n";
7717 outs() << " filesize " << filesize;
7718 if (fileoff + filesize > object_size)
7719 outs() << " (past end of file)\n";
7720 else
7721 outs() << "\n";
7722 if (verbose) {
7723 if ((maxprot &
7724 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7725 MachO::VM_PROT_EXECUTE)) != 0)
7726 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7727 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007728 outs() << " maxprot ";
7729 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7730 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7731 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007732 }
7733 if ((initprot &
7734 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7735 MachO::VM_PROT_EXECUTE)) != 0)
7736 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7737 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007738 outs() << " initprot ";
7739 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7740 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7741 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007742 }
7743 } else {
7744 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7745 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7746 }
7747 outs() << " nsects " << nsects << "\n";
7748 if (verbose) {
7749 outs() << " flags";
7750 if (flags == 0)
7751 outs() << " (none)\n";
7752 else {
7753 if (flags & MachO::SG_HIGHVM) {
7754 outs() << " HIGHVM";
7755 flags &= ~MachO::SG_HIGHVM;
7756 }
7757 if (flags & MachO::SG_FVMLIB) {
7758 outs() << " FVMLIB";
7759 flags &= ~MachO::SG_FVMLIB;
7760 }
7761 if (flags & MachO::SG_NORELOC) {
7762 outs() << " NORELOC";
7763 flags &= ~MachO::SG_NORELOC;
7764 }
7765 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7766 outs() << " PROTECTED_VERSION_1";
7767 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7768 }
7769 if (flags)
7770 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7771 else
7772 outs() << "\n";
7773 }
7774 } else {
7775 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7776 }
7777}
7778
7779static void PrintSection(const char *sectname, const char *segname,
7780 uint64_t addr, uint64_t size, uint32_t offset,
7781 uint32_t align, uint32_t reloff, uint32_t nreloc,
7782 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7783 uint32_t cmd, const char *sg_segname,
7784 uint32_t filetype, uint32_t object_size,
7785 bool verbose) {
7786 outs() << "Section\n";
7787 outs() << " sectname " << format("%.16s\n", sectname);
7788 outs() << " segname " << format("%.16s", segname);
7789 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7790 outs() << " (does not match segment)\n";
7791 else
7792 outs() << "\n";
7793 if (cmd == MachO::LC_SEGMENT_64) {
7794 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7795 outs() << " size " << format("0x%016" PRIx64, size);
7796 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007797 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7798 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007799 }
7800 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7801 outs() << " (past end of file)\n";
7802 else
7803 outs() << "\n";
7804 outs() << " offset " << offset;
7805 if (offset > object_size)
7806 outs() << " (past end of file)\n";
7807 else
7808 outs() << "\n";
7809 uint32_t align_shifted = 1 << align;
7810 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7811 outs() << " reloff " << reloff;
7812 if (reloff > object_size)
7813 outs() << " (past end of file)\n";
7814 else
7815 outs() << "\n";
7816 outs() << " nreloc " << nreloc;
7817 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7818 outs() << " (past end of file)\n";
7819 else
7820 outs() << "\n";
7821 uint32_t section_type = flags & MachO::SECTION_TYPE;
7822 if (verbose) {
7823 outs() << " type";
7824 if (section_type == MachO::S_REGULAR)
7825 outs() << " S_REGULAR\n";
7826 else if (section_type == MachO::S_ZEROFILL)
7827 outs() << " S_ZEROFILL\n";
7828 else if (section_type == MachO::S_CSTRING_LITERALS)
7829 outs() << " S_CSTRING_LITERALS\n";
7830 else if (section_type == MachO::S_4BYTE_LITERALS)
7831 outs() << " S_4BYTE_LITERALS\n";
7832 else if (section_type == MachO::S_8BYTE_LITERALS)
7833 outs() << " S_8BYTE_LITERALS\n";
7834 else if (section_type == MachO::S_16BYTE_LITERALS)
7835 outs() << " S_16BYTE_LITERALS\n";
7836 else if (section_type == MachO::S_LITERAL_POINTERS)
7837 outs() << " S_LITERAL_POINTERS\n";
7838 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7839 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7840 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7841 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7842 else if (section_type == MachO::S_SYMBOL_STUBS)
7843 outs() << " S_SYMBOL_STUBS\n";
7844 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7845 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7846 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7847 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7848 else if (section_type == MachO::S_COALESCED)
7849 outs() << " S_COALESCED\n";
7850 else if (section_type == MachO::S_INTERPOSING)
7851 outs() << " S_INTERPOSING\n";
7852 else if (section_type == MachO::S_DTRACE_DOF)
7853 outs() << " S_DTRACE_DOF\n";
7854 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7855 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7856 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7857 outs() << " S_THREAD_LOCAL_REGULAR\n";
7858 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7859 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7860 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7861 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7862 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7863 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7864 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7865 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7866 else
7867 outs() << format("0x%08" PRIx32, section_type) << "\n";
7868 outs() << "attributes";
7869 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7870 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7871 outs() << " PURE_INSTRUCTIONS";
7872 if (section_attributes & MachO::S_ATTR_NO_TOC)
7873 outs() << " NO_TOC";
7874 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7875 outs() << " STRIP_STATIC_SYMS";
7876 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7877 outs() << " NO_DEAD_STRIP";
7878 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7879 outs() << " LIVE_SUPPORT";
7880 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7881 outs() << " SELF_MODIFYING_CODE";
7882 if (section_attributes & MachO::S_ATTR_DEBUG)
7883 outs() << " DEBUG";
7884 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7885 outs() << " SOME_INSTRUCTIONS";
7886 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7887 outs() << " EXT_RELOC";
7888 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7889 outs() << " LOC_RELOC";
7890 if (section_attributes == 0)
7891 outs() << " (none)";
7892 outs() << "\n";
7893 } else
7894 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7895 outs() << " reserved1 " << reserved1;
7896 if (section_type == MachO::S_SYMBOL_STUBS ||
7897 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7898 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7899 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7900 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7901 outs() << " (index into indirect symbol table)\n";
7902 else
7903 outs() << "\n";
7904 outs() << " reserved2 " << reserved2;
7905 if (section_type == MachO::S_SYMBOL_STUBS)
7906 outs() << " (size of stubs)\n";
7907 else
7908 outs() << "\n";
7909}
7910
David Majnemer73cc6ff2014-11-13 19:48:56 +00007911static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007912 uint32_t object_size) {
7913 outs() << " cmd LC_SYMTAB\n";
7914 outs() << " cmdsize " << st.cmdsize;
7915 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7916 outs() << " Incorrect size\n";
7917 else
7918 outs() << "\n";
7919 outs() << " symoff " << st.symoff;
7920 if (st.symoff > object_size)
7921 outs() << " (past end of file)\n";
7922 else
7923 outs() << "\n";
7924 outs() << " nsyms " << st.nsyms;
7925 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007926 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007927 big_size = st.nsyms;
7928 big_size *= sizeof(struct MachO::nlist_64);
7929 big_size += st.symoff;
7930 if (big_size > object_size)
7931 outs() << " (past end of file)\n";
7932 else
7933 outs() << "\n";
7934 } else {
7935 big_size = st.nsyms;
7936 big_size *= sizeof(struct MachO::nlist);
7937 big_size += st.symoff;
7938 if (big_size > object_size)
7939 outs() << " (past end of file)\n";
7940 else
7941 outs() << "\n";
7942 }
7943 outs() << " stroff " << st.stroff;
7944 if (st.stroff > object_size)
7945 outs() << " (past end of file)\n";
7946 else
7947 outs() << "\n";
7948 outs() << " strsize " << st.strsize;
7949 big_size = st.stroff;
7950 big_size += st.strsize;
7951 if (big_size > object_size)
7952 outs() << " (past end of file)\n";
7953 else
7954 outs() << "\n";
7955}
7956
7957static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7958 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007959 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007960 outs() << " cmd LC_DYSYMTAB\n";
7961 outs() << " cmdsize " << dyst.cmdsize;
7962 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7963 outs() << " Incorrect size\n";
7964 else
7965 outs() << "\n";
7966 outs() << " ilocalsym " << dyst.ilocalsym;
7967 if (dyst.ilocalsym > nsyms)
7968 outs() << " (greater than the number of symbols)\n";
7969 else
7970 outs() << "\n";
7971 outs() << " nlocalsym " << dyst.nlocalsym;
7972 uint64_t big_size;
7973 big_size = dyst.ilocalsym;
7974 big_size += dyst.nlocalsym;
7975 if (big_size > nsyms)
7976 outs() << " (past the end of the symbol table)\n";
7977 else
7978 outs() << "\n";
7979 outs() << " iextdefsym " << dyst.iextdefsym;
7980 if (dyst.iextdefsym > nsyms)
7981 outs() << " (greater than the number of symbols)\n";
7982 else
7983 outs() << "\n";
7984 outs() << " nextdefsym " << dyst.nextdefsym;
7985 big_size = dyst.iextdefsym;
7986 big_size += dyst.nextdefsym;
7987 if (big_size > nsyms)
7988 outs() << " (past the end of the symbol table)\n";
7989 else
7990 outs() << "\n";
7991 outs() << " iundefsym " << dyst.iundefsym;
7992 if (dyst.iundefsym > nsyms)
7993 outs() << " (greater than the number of symbols)\n";
7994 else
7995 outs() << "\n";
7996 outs() << " nundefsym " << dyst.nundefsym;
7997 big_size = dyst.iundefsym;
7998 big_size += dyst.nundefsym;
7999 if (big_size > nsyms)
8000 outs() << " (past the end of the symbol table)\n";
8001 else
8002 outs() << "\n";
8003 outs() << " tocoff " << dyst.tocoff;
8004 if (dyst.tocoff > object_size)
8005 outs() << " (past end of file)\n";
8006 else
8007 outs() << "\n";
8008 outs() << " ntoc " << dyst.ntoc;
8009 big_size = dyst.ntoc;
8010 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8011 big_size += dyst.tocoff;
8012 if (big_size > object_size)
8013 outs() << " (past end of file)\n";
8014 else
8015 outs() << "\n";
8016 outs() << " modtaboff " << dyst.modtaboff;
8017 if (dyst.modtaboff > object_size)
8018 outs() << " (past end of file)\n";
8019 else
8020 outs() << "\n";
8021 outs() << " nmodtab " << dyst.nmodtab;
8022 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008023 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008024 modtabend = dyst.nmodtab;
8025 modtabend *= sizeof(struct MachO::dylib_module_64);
8026 modtabend += dyst.modtaboff;
8027 } else {
8028 modtabend = dyst.nmodtab;
8029 modtabend *= sizeof(struct MachO::dylib_module);
8030 modtabend += dyst.modtaboff;
8031 }
8032 if (modtabend > object_size)
8033 outs() << " (past end of file)\n";
8034 else
8035 outs() << "\n";
8036 outs() << " extrefsymoff " << dyst.extrefsymoff;
8037 if (dyst.extrefsymoff > object_size)
8038 outs() << " (past end of file)\n";
8039 else
8040 outs() << "\n";
8041 outs() << " nextrefsyms " << dyst.nextrefsyms;
8042 big_size = dyst.nextrefsyms;
8043 big_size *= sizeof(struct MachO::dylib_reference);
8044 big_size += dyst.extrefsymoff;
8045 if (big_size > object_size)
8046 outs() << " (past end of file)\n";
8047 else
8048 outs() << "\n";
8049 outs() << " indirectsymoff " << dyst.indirectsymoff;
8050 if (dyst.indirectsymoff > object_size)
8051 outs() << " (past end of file)\n";
8052 else
8053 outs() << "\n";
8054 outs() << " nindirectsyms " << dyst.nindirectsyms;
8055 big_size = dyst.nindirectsyms;
8056 big_size *= sizeof(uint32_t);
8057 big_size += dyst.indirectsymoff;
8058 if (big_size > object_size)
8059 outs() << " (past end of file)\n";
8060 else
8061 outs() << "\n";
8062 outs() << " extreloff " << dyst.extreloff;
8063 if (dyst.extreloff > object_size)
8064 outs() << " (past end of file)\n";
8065 else
8066 outs() << "\n";
8067 outs() << " nextrel " << dyst.nextrel;
8068 big_size = dyst.nextrel;
8069 big_size *= sizeof(struct MachO::relocation_info);
8070 big_size += dyst.extreloff;
8071 if (big_size > object_size)
8072 outs() << " (past end of file)\n";
8073 else
8074 outs() << "\n";
8075 outs() << " locreloff " << dyst.locreloff;
8076 if (dyst.locreloff > object_size)
8077 outs() << " (past end of file)\n";
8078 else
8079 outs() << "\n";
8080 outs() << " nlocrel " << dyst.nlocrel;
8081 big_size = dyst.nlocrel;
8082 big_size *= sizeof(struct MachO::relocation_info);
8083 big_size += dyst.locreloff;
8084 if (big_size > object_size)
8085 outs() << " (past end of file)\n";
8086 else
8087 outs() << "\n";
8088}
8089
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008090static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8091 uint32_t object_size) {
8092 if (dc.cmd == MachO::LC_DYLD_INFO)
8093 outs() << " cmd LC_DYLD_INFO\n";
8094 else
8095 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8096 outs() << " cmdsize " << dc.cmdsize;
8097 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8098 outs() << " Incorrect size\n";
8099 else
8100 outs() << "\n";
8101 outs() << " rebase_off " << dc.rebase_off;
8102 if (dc.rebase_off > object_size)
8103 outs() << " (past end of file)\n";
8104 else
8105 outs() << "\n";
8106 outs() << " rebase_size " << dc.rebase_size;
8107 uint64_t big_size;
8108 big_size = dc.rebase_off;
8109 big_size += dc.rebase_size;
8110 if (big_size > object_size)
8111 outs() << " (past end of file)\n";
8112 else
8113 outs() << "\n";
8114 outs() << " bind_off " << dc.bind_off;
8115 if (dc.bind_off > object_size)
8116 outs() << " (past end of file)\n";
8117 else
8118 outs() << "\n";
8119 outs() << " bind_size " << dc.bind_size;
8120 big_size = dc.bind_off;
8121 big_size += dc.bind_size;
8122 if (big_size > object_size)
8123 outs() << " (past end of file)\n";
8124 else
8125 outs() << "\n";
8126 outs() << " weak_bind_off " << dc.weak_bind_off;
8127 if (dc.weak_bind_off > object_size)
8128 outs() << " (past end of file)\n";
8129 else
8130 outs() << "\n";
8131 outs() << " weak_bind_size " << dc.weak_bind_size;
8132 big_size = dc.weak_bind_off;
8133 big_size += dc.weak_bind_size;
8134 if (big_size > object_size)
8135 outs() << " (past end of file)\n";
8136 else
8137 outs() << "\n";
8138 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8139 if (dc.lazy_bind_off > object_size)
8140 outs() << " (past end of file)\n";
8141 else
8142 outs() << "\n";
8143 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8144 big_size = dc.lazy_bind_off;
8145 big_size += dc.lazy_bind_size;
8146 if (big_size > object_size)
8147 outs() << " (past end of file)\n";
8148 else
8149 outs() << "\n";
8150 outs() << " export_off " << dc.export_off;
8151 if (dc.export_off > object_size)
8152 outs() << " (past end of file)\n";
8153 else
8154 outs() << "\n";
8155 outs() << " export_size " << dc.export_size;
8156 big_size = dc.export_off;
8157 big_size += dc.export_size;
8158 if (big_size > object_size)
8159 outs() << " (past end of file)\n";
8160 else
8161 outs() << "\n";
8162}
8163
8164static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8165 const char *Ptr) {
8166 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8167 outs() << " cmd LC_ID_DYLINKER\n";
8168 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8169 outs() << " cmd LC_LOAD_DYLINKER\n";
8170 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8171 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8172 else
8173 outs() << " cmd ?(" << dyld.cmd << ")\n";
8174 outs() << " cmdsize " << dyld.cmdsize;
8175 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8176 outs() << " Incorrect size\n";
8177 else
8178 outs() << "\n";
8179 if (dyld.name >= dyld.cmdsize)
8180 outs() << " name ?(bad offset " << dyld.name << ")\n";
8181 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008182 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008183 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8184 }
8185}
8186
8187static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8188 outs() << " cmd LC_UUID\n";
8189 outs() << " cmdsize " << uuid.cmdsize;
8190 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8191 outs() << " Incorrect size\n";
8192 else
8193 outs() << "\n";
8194 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008195 for (int i = 0; i < 16; ++i) {
8196 outs() << format("%02" PRIX32, uuid.uuid[i]);
8197 if (i == 3 || i == 5 || i == 7 || i == 9)
8198 outs() << "-";
8199 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008200 outs() << "\n";
8201}
8202
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008203static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008204 outs() << " cmd LC_RPATH\n";
8205 outs() << " cmdsize " << rpath.cmdsize;
8206 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8207 outs() << " Incorrect size\n";
8208 else
8209 outs() << "\n";
8210 if (rpath.path >= rpath.cmdsize)
8211 outs() << " path ?(bad offset " << rpath.path << ")\n";
8212 else {
8213 const char *P = (const char *)(Ptr) + rpath.path;
8214 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8215 }
8216}
8217
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008218static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008219 StringRef LoadCmdName;
8220 switch (vd.cmd) {
8221 case MachO::LC_VERSION_MIN_MACOSX:
8222 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8223 break;
8224 case MachO::LC_VERSION_MIN_IPHONEOS:
8225 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8226 break;
8227 case MachO::LC_VERSION_MIN_TVOS:
8228 LoadCmdName = "LC_VERSION_MIN_TVOS";
8229 break;
8230 case MachO::LC_VERSION_MIN_WATCHOS:
8231 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8232 break;
8233 default:
8234 llvm_unreachable("Unknown version min load command");
8235 }
8236
8237 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008238 outs() << " cmdsize " << vd.cmdsize;
8239 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8240 outs() << " Incorrect size\n";
8241 else
8242 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008243 outs() << " version "
8244 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8245 << MachOObjectFile::getVersionMinMinor(vd, false);
8246 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8247 if (Update != 0)
8248 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008249 outs() << "\n";
8250 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008251 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008252 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008253 outs() << " sdk "
8254 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8255 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008256 }
Davide Italiano56baef32015-08-26 12:26:11 +00008257 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8258 if (Update != 0)
8259 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008260 outs() << "\n";
8261}
8262
8263static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8264 outs() << " cmd LC_SOURCE_VERSION\n";
8265 outs() << " cmdsize " << sd.cmdsize;
8266 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8267 outs() << " Incorrect size\n";
8268 else
8269 outs() << "\n";
8270 uint64_t a = (sd.version >> 40) & 0xffffff;
8271 uint64_t b = (sd.version >> 30) & 0x3ff;
8272 uint64_t c = (sd.version >> 20) & 0x3ff;
8273 uint64_t d = (sd.version >> 10) & 0x3ff;
8274 uint64_t e = sd.version & 0x3ff;
8275 outs() << " version " << a << "." << b;
8276 if (e != 0)
8277 outs() << "." << c << "." << d << "." << e;
8278 else if (d != 0)
8279 outs() << "." << c << "." << d;
8280 else if (c != 0)
8281 outs() << "." << c;
8282 outs() << "\n";
8283}
8284
8285static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8286 outs() << " cmd LC_MAIN\n";
8287 outs() << " cmdsize " << ep.cmdsize;
8288 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8289 outs() << " Incorrect size\n";
8290 else
8291 outs() << "\n";
8292 outs() << " entryoff " << ep.entryoff << "\n";
8293 outs() << " stacksize " << ep.stacksize << "\n";
8294}
8295
Kevin Enderby0804f4672014-12-16 23:25:52 +00008296static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8297 uint32_t object_size) {
8298 outs() << " cmd LC_ENCRYPTION_INFO\n";
8299 outs() << " cmdsize " << ec.cmdsize;
8300 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8301 outs() << " Incorrect size\n";
8302 else
8303 outs() << "\n";
8304 outs() << " cryptoff " << ec.cryptoff;
8305 if (ec.cryptoff > object_size)
8306 outs() << " (past end of file)\n";
8307 else
8308 outs() << "\n";
8309 outs() << " cryptsize " << ec.cryptsize;
8310 if (ec.cryptsize > object_size)
8311 outs() << " (past end of file)\n";
8312 else
8313 outs() << "\n";
8314 outs() << " cryptid " << ec.cryptid << "\n";
8315}
8316
Kevin Enderby57538292014-12-17 01:01:30 +00008317static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008318 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008319 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8320 outs() << " cmdsize " << ec.cmdsize;
8321 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8322 outs() << " Incorrect size\n";
8323 else
8324 outs() << "\n";
8325 outs() << " cryptoff " << ec.cryptoff;
8326 if (ec.cryptoff > object_size)
8327 outs() << " (past end of file)\n";
8328 else
8329 outs() << "\n";
8330 outs() << " cryptsize " << ec.cryptsize;
8331 if (ec.cryptsize > object_size)
8332 outs() << " (past end of file)\n";
8333 else
8334 outs() << "\n";
8335 outs() << " cryptid " << ec.cryptid << "\n";
8336 outs() << " pad " << ec.pad << "\n";
8337}
8338
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008339static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8340 const char *Ptr) {
8341 outs() << " cmd LC_LINKER_OPTION\n";
8342 outs() << " cmdsize " << lo.cmdsize;
8343 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8344 outs() << " Incorrect size\n";
8345 else
8346 outs() << "\n";
8347 outs() << " count " << lo.count << "\n";
8348 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8349 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8350 uint32_t i = 0;
8351 while (left > 0) {
8352 while (*string == '\0' && left > 0) {
8353 string++;
8354 left--;
8355 }
8356 if (left > 0) {
8357 i++;
8358 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008359 uint32_t NullPos = StringRef(string, left).find('\0');
8360 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008361 string += len;
8362 left -= len;
8363 }
8364 }
8365 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008366 outs() << " count " << lo.count << " does not match number of strings "
8367 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008368}
8369
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008370static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8371 const char *Ptr) {
8372 outs() << " cmd LC_SUB_FRAMEWORK\n";
8373 outs() << " cmdsize " << sub.cmdsize;
8374 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8375 outs() << " Incorrect size\n";
8376 else
8377 outs() << "\n";
8378 if (sub.umbrella < sub.cmdsize) {
8379 const char *P = Ptr + sub.umbrella;
8380 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8381 } else {
8382 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8383 }
8384}
8385
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008386static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8387 const char *Ptr) {
8388 outs() << " cmd LC_SUB_UMBRELLA\n";
8389 outs() << " cmdsize " << sub.cmdsize;
8390 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8391 outs() << " Incorrect size\n";
8392 else
8393 outs() << "\n";
8394 if (sub.sub_umbrella < sub.cmdsize) {
8395 const char *P = Ptr + sub.sub_umbrella;
8396 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8397 } else {
8398 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8399 }
8400}
8401
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008402static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008403 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008404 outs() << " cmd LC_SUB_LIBRARY\n";
8405 outs() << " cmdsize " << sub.cmdsize;
8406 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8407 outs() << " Incorrect size\n";
8408 else
8409 outs() << "\n";
8410 if (sub.sub_library < sub.cmdsize) {
8411 const char *P = Ptr + sub.sub_library;
8412 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8413 } else {
8414 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8415 }
8416}
8417
Kevin Enderby186eac32014-12-19 21:06:24 +00008418static void PrintSubClientCommand(MachO::sub_client_command sub,
8419 const char *Ptr) {
8420 outs() << " cmd LC_SUB_CLIENT\n";
8421 outs() << " cmdsize " << sub.cmdsize;
8422 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8423 outs() << " Incorrect size\n";
8424 else
8425 outs() << "\n";
8426 if (sub.client < sub.cmdsize) {
8427 const char *P = Ptr + sub.client;
8428 outs() << " client " << P << " (offset " << sub.client << ")\n";
8429 } else {
8430 outs() << " client ?(bad offset " << sub.client << ")\n";
8431 }
8432}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008433
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008434static void PrintRoutinesCommand(MachO::routines_command r) {
8435 outs() << " cmd LC_ROUTINES\n";
8436 outs() << " cmdsize " << r.cmdsize;
8437 if (r.cmdsize != sizeof(struct MachO::routines_command))
8438 outs() << " Incorrect size\n";
8439 else
8440 outs() << "\n";
8441 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8442 outs() << " init_module " << r.init_module << "\n";
8443 outs() << " reserved1 " << r.reserved1 << "\n";
8444 outs() << " reserved2 " << r.reserved2 << "\n";
8445 outs() << " reserved3 " << r.reserved3 << "\n";
8446 outs() << " reserved4 " << r.reserved4 << "\n";
8447 outs() << " reserved5 " << r.reserved5 << "\n";
8448 outs() << " reserved6 " << r.reserved6 << "\n";
8449}
8450
8451static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8452 outs() << " cmd LC_ROUTINES_64\n";
8453 outs() << " cmdsize " << r.cmdsize;
8454 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8455 outs() << " Incorrect size\n";
8456 else
8457 outs() << "\n";
8458 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8459 outs() << " init_module " << r.init_module << "\n";
8460 outs() << " reserved1 " << r.reserved1 << "\n";
8461 outs() << " reserved2 " << r.reserved2 << "\n";
8462 outs() << " reserved3 " << r.reserved3 << "\n";
8463 outs() << " reserved4 " << r.reserved4 << "\n";
8464 outs() << " reserved5 " << r.reserved5 << "\n";
8465 outs() << " reserved6 " << r.reserved6 << "\n";
8466}
8467
Kevin Enderby48ef5342014-12-23 22:56:39 +00008468static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8469 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8470 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8471 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8472 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8473 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8474 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8475 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8476 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8477 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8478 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8479 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8480 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8481 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8482 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8483 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8484 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8485 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8486 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8487 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8488 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8489 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8490}
8491
Kevin Enderby227df342014-12-23 23:43:59 +00008492static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008493 uint32_t f;
8494 outs() << "\t mmst_reg ";
8495 for (f = 0; f < 10; f++)
8496 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8497 outs() << "\n";
8498 outs() << "\t mmst_rsrv ";
8499 for (f = 0; f < 6; f++)
8500 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8501 outs() << "\n";
8502}
8503
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008504static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008505 uint32_t f;
8506 outs() << "\t xmm_reg ";
8507 for (f = 0; f < 16; f++)
8508 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8509 outs() << "\n";
8510}
8511
8512static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8513 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8514 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8515 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8516 outs() << " denorm " << fpu.fpu_fcw.denorm;
8517 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8518 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8519 outs() << " undfl " << fpu.fpu_fcw.undfl;
8520 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8521 outs() << "\t\t pc ";
8522 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8523 outs() << "FP_PREC_24B ";
8524 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8525 outs() << "FP_PREC_53B ";
8526 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8527 outs() << "FP_PREC_64B ";
8528 else
8529 outs() << fpu.fpu_fcw.pc << " ";
8530 outs() << "rc ";
8531 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8532 outs() << "FP_RND_NEAR ";
8533 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8534 outs() << "FP_RND_DOWN ";
8535 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8536 outs() << "FP_RND_UP ";
8537 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008538 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008539 outs() << "\n";
8540 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8541 outs() << " denorm " << fpu.fpu_fsw.denorm;
8542 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8543 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8544 outs() << " undfl " << fpu.fpu_fsw.undfl;
8545 outs() << " precis " << fpu.fpu_fsw.precis;
8546 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8547 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8548 outs() << " c0 " << fpu.fpu_fsw.c0;
8549 outs() << " c1 " << fpu.fpu_fsw.c1;
8550 outs() << " c2 " << fpu.fpu_fsw.c2;
8551 outs() << " tos " << fpu.fpu_fsw.tos;
8552 outs() << " c3 " << fpu.fpu_fsw.c3;
8553 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8554 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8555 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8556 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8557 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8558 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8559 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8560 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8561 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8562 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8563 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8564 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8565 outs() << "\n";
8566 outs() << "\t fpu_stmm0:\n";
8567 Print_mmst_reg(fpu.fpu_stmm0);
8568 outs() << "\t fpu_stmm1:\n";
8569 Print_mmst_reg(fpu.fpu_stmm1);
8570 outs() << "\t fpu_stmm2:\n";
8571 Print_mmst_reg(fpu.fpu_stmm2);
8572 outs() << "\t fpu_stmm3:\n";
8573 Print_mmst_reg(fpu.fpu_stmm3);
8574 outs() << "\t fpu_stmm4:\n";
8575 Print_mmst_reg(fpu.fpu_stmm4);
8576 outs() << "\t fpu_stmm5:\n";
8577 Print_mmst_reg(fpu.fpu_stmm5);
8578 outs() << "\t fpu_stmm6:\n";
8579 Print_mmst_reg(fpu.fpu_stmm6);
8580 outs() << "\t fpu_stmm7:\n";
8581 Print_mmst_reg(fpu.fpu_stmm7);
8582 outs() << "\t fpu_xmm0:\n";
8583 Print_xmm_reg(fpu.fpu_xmm0);
8584 outs() << "\t fpu_xmm1:\n";
8585 Print_xmm_reg(fpu.fpu_xmm1);
8586 outs() << "\t fpu_xmm2:\n";
8587 Print_xmm_reg(fpu.fpu_xmm2);
8588 outs() << "\t fpu_xmm3:\n";
8589 Print_xmm_reg(fpu.fpu_xmm3);
8590 outs() << "\t fpu_xmm4:\n";
8591 Print_xmm_reg(fpu.fpu_xmm4);
8592 outs() << "\t fpu_xmm5:\n";
8593 Print_xmm_reg(fpu.fpu_xmm5);
8594 outs() << "\t fpu_xmm6:\n";
8595 Print_xmm_reg(fpu.fpu_xmm6);
8596 outs() << "\t fpu_xmm7:\n";
8597 Print_xmm_reg(fpu.fpu_xmm7);
8598 outs() << "\t fpu_xmm8:\n";
8599 Print_xmm_reg(fpu.fpu_xmm8);
8600 outs() << "\t fpu_xmm9:\n";
8601 Print_xmm_reg(fpu.fpu_xmm9);
8602 outs() << "\t fpu_xmm10:\n";
8603 Print_xmm_reg(fpu.fpu_xmm10);
8604 outs() << "\t fpu_xmm11:\n";
8605 Print_xmm_reg(fpu.fpu_xmm11);
8606 outs() << "\t fpu_xmm12:\n";
8607 Print_xmm_reg(fpu.fpu_xmm12);
8608 outs() << "\t fpu_xmm13:\n";
8609 Print_xmm_reg(fpu.fpu_xmm13);
8610 outs() << "\t fpu_xmm14:\n";
8611 Print_xmm_reg(fpu.fpu_xmm14);
8612 outs() << "\t fpu_xmm15:\n";
8613 Print_xmm_reg(fpu.fpu_xmm15);
8614 outs() << "\t fpu_rsrv4:\n";
8615 for (uint32_t f = 0; f < 6; f++) {
8616 outs() << "\t ";
8617 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008618 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008619 outs() << "\n";
8620 }
8621 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8622 outs() << "\n";
8623}
8624
8625static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8626 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8627 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8628 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8629}
8630
8631static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8632 bool isLittleEndian, uint32_t cputype) {
8633 if (t.cmd == MachO::LC_THREAD)
8634 outs() << " cmd LC_THREAD\n";
8635 else if (t.cmd == MachO::LC_UNIXTHREAD)
8636 outs() << " cmd LC_UNIXTHREAD\n";
8637 else
8638 outs() << " cmd " << t.cmd << " (unknown)\n";
8639 outs() << " cmdsize " << t.cmdsize;
8640 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8641 outs() << " Incorrect size\n";
8642 else
8643 outs() << "\n";
8644
8645 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8646 const char *end = Ptr + t.cmdsize;
8647 uint32_t flavor, count, left;
8648 if (cputype == MachO::CPU_TYPE_X86_64) {
8649 while (begin < end) {
8650 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8651 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8652 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008653 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008654 flavor = 0;
8655 begin = end;
8656 }
8657 if (isLittleEndian != sys::IsLittleEndianHost)
8658 sys::swapByteOrder(flavor);
8659 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8660 memcpy((char *)&count, begin, sizeof(uint32_t));
8661 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008662 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008663 count = 0;
8664 begin = end;
8665 }
8666 if (isLittleEndian != sys::IsLittleEndianHost)
8667 sys::swapByteOrder(count);
8668 if (flavor == MachO::x86_THREAD_STATE64) {
8669 outs() << " flavor x86_THREAD_STATE64\n";
8670 if (count == MachO::x86_THREAD_STATE64_COUNT)
8671 outs() << " count x86_THREAD_STATE64_COUNT\n";
8672 else
8673 outs() << " count " << count
8674 << " (not x86_THREAD_STATE64_COUNT)\n";
8675 MachO::x86_thread_state64_t cpu64;
8676 left = end - begin;
8677 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8678 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8679 begin += sizeof(MachO::x86_thread_state64_t);
8680 } else {
8681 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8682 memcpy(&cpu64, begin, left);
8683 begin += left;
8684 }
8685 if (isLittleEndian != sys::IsLittleEndianHost)
8686 swapStruct(cpu64);
8687 Print_x86_thread_state64_t(cpu64);
8688 } else if (flavor == MachO::x86_THREAD_STATE) {
8689 outs() << " flavor x86_THREAD_STATE\n";
8690 if (count == MachO::x86_THREAD_STATE_COUNT)
8691 outs() << " count x86_THREAD_STATE_COUNT\n";
8692 else
8693 outs() << " count " << count
8694 << " (not x86_THREAD_STATE_COUNT)\n";
8695 struct MachO::x86_thread_state_t ts;
8696 left = end - begin;
8697 if (left >= sizeof(MachO::x86_thread_state_t)) {
8698 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8699 begin += sizeof(MachO::x86_thread_state_t);
8700 } else {
8701 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8702 memcpy(&ts, begin, left);
8703 begin += left;
8704 }
8705 if (isLittleEndian != sys::IsLittleEndianHost)
8706 swapStruct(ts);
8707 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8708 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8709 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8710 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8711 else
8712 outs() << "tsh.count " << ts.tsh.count
8713 << " (not x86_THREAD_STATE64_COUNT\n";
8714 Print_x86_thread_state64_t(ts.uts.ts64);
8715 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008716 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8717 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008718 }
8719 } else if (flavor == MachO::x86_FLOAT_STATE) {
8720 outs() << " flavor x86_FLOAT_STATE\n";
8721 if (count == MachO::x86_FLOAT_STATE_COUNT)
8722 outs() << " count x86_FLOAT_STATE_COUNT\n";
8723 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008724 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008725 struct MachO::x86_float_state_t fs;
8726 left = end - begin;
8727 if (left >= sizeof(MachO::x86_float_state_t)) {
8728 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8729 begin += sizeof(MachO::x86_float_state_t);
8730 } else {
8731 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8732 memcpy(&fs, begin, left);
8733 begin += left;
8734 }
8735 if (isLittleEndian != sys::IsLittleEndianHost)
8736 swapStruct(fs);
8737 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8738 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008739 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008740 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8741 else
8742 outs() << "fsh.count " << fs.fsh.count
8743 << " (not x86_FLOAT_STATE64_COUNT\n";
8744 Print_x86_float_state_t(fs.ufs.fs64);
8745 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008746 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8747 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008748 }
8749 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8750 outs() << " flavor x86_EXCEPTION_STATE\n";
8751 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8752 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8753 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008754 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008755 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8756 struct MachO::x86_exception_state_t es;
8757 left = end - begin;
8758 if (left >= sizeof(MachO::x86_exception_state_t)) {
8759 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8760 begin += sizeof(MachO::x86_exception_state_t);
8761 } else {
8762 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8763 memcpy(&es, begin, left);
8764 begin += left;
8765 }
8766 if (isLittleEndian != sys::IsLittleEndianHost)
8767 swapStruct(es);
8768 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8769 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008770 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008771 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8772 else
8773 outs() << "\t esh.count " << es.esh.count
8774 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8775 Print_x86_exception_state_t(es.ues.es64);
8776 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008777 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8778 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008779 }
8780 } else {
8781 outs() << " flavor " << flavor << " (unknown)\n";
8782 outs() << " count " << count << "\n";
8783 outs() << " state (unknown)\n";
8784 begin += count * sizeof(uint32_t);
8785 }
8786 }
8787 } else {
8788 while (begin < end) {
8789 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8790 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8791 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008792 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008793 flavor = 0;
8794 begin = end;
8795 }
8796 if (isLittleEndian != sys::IsLittleEndianHost)
8797 sys::swapByteOrder(flavor);
8798 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8799 memcpy((char *)&count, begin, sizeof(uint32_t));
8800 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008801 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008802 count = 0;
8803 begin = end;
8804 }
8805 if (isLittleEndian != sys::IsLittleEndianHost)
8806 sys::swapByteOrder(count);
8807 outs() << " flavor " << flavor << "\n";
8808 outs() << " count " << count << "\n";
8809 outs() << " state (Unknown cputype/cpusubtype)\n";
8810 begin += count * sizeof(uint32_t);
8811 }
8812 }
8813}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008814
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008815static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8816 if (dl.cmd == MachO::LC_ID_DYLIB)
8817 outs() << " cmd LC_ID_DYLIB\n";
8818 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8819 outs() << " cmd LC_LOAD_DYLIB\n";
8820 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8821 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8822 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8823 outs() << " cmd LC_REEXPORT_DYLIB\n";
8824 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8825 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8826 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8827 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8828 else
8829 outs() << " cmd " << dl.cmd << " (unknown)\n";
8830 outs() << " cmdsize " << dl.cmdsize;
8831 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8832 outs() << " Incorrect size\n";
8833 else
8834 outs() << "\n";
8835 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008836 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008837 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8838 } else {
8839 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8840 }
8841 outs() << " time stamp " << dl.dylib.timestamp << " ";
8842 time_t t = dl.dylib.timestamp;
8843 outs() << ctime(&t);
8844 outs() << " current version ";
8845 if (dl.dylib.current_version == 0xffffffff)
8846 outs() << "n/a\n";
8847 else
8848 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8849 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8850 << (dl.dylib.current_version & 0xff) << "\n";
8851 outs() << "compatibility version ";
8852 if (dl.dylib.compatibility_version == 0xffffffff)
8853 outs() << "n/a\n";
8854 else
8855 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8856 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8857 << (dl.dylib.compatibility_version & 0xff) << "\n";
8858}
8859
8860static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8861 uint32_t object_size) {
8862 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00008863 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008864 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8865 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8866 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8867 outs() << " cmd LC_FUNCTION_STARTS\n";
8868 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8869 outs() << " cmd LC_DATA_IN_CODE\n";
8870 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8871 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8872 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8873 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8874 else
8875 outs() << " cmd " << ld.cmd << " (?)\n";
8876 outs() << " cmdsize " << ld.cmdsize;
8877 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8878 outs() << " Incorrect size\n";
8879 else
8880 outs() << "\n";
8881 outs() << " dataoff " << ld.dataoff;
8882 if (ld.dataoff > object_size)
8883 outs() << " (past end of file)\n";
8884 else
8885 outs() << "\n";
8886 outs() << " datasize " << ld.datasize;
8887 uint64_t big_size = ld.dataoff;
8888 big_size += ld.datasize;
8889 if (big_size > object_size)
8890 outs() << " (past end of file)\n";
8891 else
8892 outs() << "\n";
8893}
8894
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008895static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8896 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008897 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008898 unsigned Index = 0;
8899 for (const auto &Command : Obj->load_commands()) {
8900 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008901 if (Command.C.cmd == MachO::LC_SEGMENT) {
8902 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8903 const char *sg_segname = SLC.segname;
8904 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8905 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8906 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8907 verbose);
8908 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008909 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008910 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8911 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8912 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8913 }
8914 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8915 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8916 const char *sg_segname = SLC_64.segname;
8917 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8918 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8919 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8920 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8921 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8922 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8923 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8924 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8925 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8926 sg_segname, filetype, Buf.size(), verbose);
8927 }
8928 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8929 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008930 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008931 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8932 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8933 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008934 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8935 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008936 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8937 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8938 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8939 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8940 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8941 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8942 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8943 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8944 PrintDyldLoadCommand(Dyld, Command.Ptr);
8945 } else if (Command.C.cmd == MachO::LC_UUID) {
8946 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8947 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008948 } else if (Command.C.cmd == MachO::LC_RPATH) {
8949 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8950 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008951 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008952 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8953 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8954 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008955 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8956 PrintVersionMinLoadCommand(Vd);
8957 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8958 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8959 PrintSourceVersionCommand(Sd);
8960 } else if (Command.C.cmd == MachO::LC_MAIN) {
8961 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8962 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008963 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008964 MachO::encryption_info_command Ei =
8965 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008966 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008967 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008968 MachO::encryption_info_command_64 Ei =
8969 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008970 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008971 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008972 MachO::linker_option_command Lo =
8973 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008974 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008975 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8976 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8977 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008978 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8979 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8980 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008981 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8982 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8983 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008984 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8985 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8986 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008987 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8988 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8989 PrintRoutinesCommand(Rc);
8990 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8991 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8992 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008993 } else if (Command.C.cmd == MachO::LC_THREAD ||
8994 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8995 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8996 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008997 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8998 Command.C.cmd == MachO::LC_ID_DYLIB ||
8999 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9000 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9001 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9002 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009003 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9004 PrintDylibCommand(Dl, Command.Ptr);
9005 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9006 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9007 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9008 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9009 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9010 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9011 MachO::linkedit_data_command Ld =
9012 Obj->getLinkeditDataLoadCommand(Command);
9013 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009014 } else {
9015 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9016 << ")\n";
9017 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9018 // TODO: get and print the raw bytes of the load command.
9019 }
9020 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009021 }
9022}
9023
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009024static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009025 if (Obj->is64Bit()) {
9026 MachO::mach_header_64 H_64;
9027 H_64 = Obj->getHeader64();
9028 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9029 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9030 } else {
9031 MachO::mach_header H;
9032 H = Obj->getHeader();
9033 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9034 H.sizeofcmds, H.flags, verbose);
9035 }
9036}
9037
9038void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9039 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009040 PrintMachHeader(file, !NonVerbose);
9041}
9042
9043void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9044 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009045 uint32_t filetype = 0;
9046 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009047 if (file->is64Bit()) {
9048 MachO::mach_header_64 H_64;
9049 H_64 = file->getHeader64();
9050 filetype = H_64.filetype;
9051 cputype = H_64.cputype;
9052 } else {
9053 MachO::mach_header H;
9054 H = file->getHeader();
9055 filetype = H.filetype;
9056 cputype = H.cputype;
9057 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009058 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009059}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009060
9061//===----------------------------------------------------------------------===//
9062// export trie dumping
9063//===----------------------------------------------------------------------===//
9064
9065void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009066 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9067 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009068 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9069 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9070 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9071 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9072 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9073 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9074 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9075 if (ReExport)
9076 outs() << "[re-export] ";
9077 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009078 outs() << format("0x%08llX ",
9079 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009080 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009081 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009082 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009083 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009084 if (WeakDef) {
9085 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009086 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009087 }
9088 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009089 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009090 outs() << ", ";
9091 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009092 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009093 }
9094 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009095 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009096 outs() << ", ";
9097 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009098 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009099 }
9100 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009101 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009102 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009103 outs() << format("resolver=0x%08llX", Entry.other());
9104 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009105 }
9106 outs() << "]";
9107 }
9108 if (ReExport) {
9109 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009110 int Ordinal = Entry.other() - 1;
9111 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9112 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009113 outs() << " (from " << DylibName << ")";
9114 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009115 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009116 }
9117 outs() << "\n";
9118 }
9119}
Nick Kledzikac431442014-09-12 21:34:15 +00009120
Nick Kledzikac431442014-09-12 21:34:15 +00009121//===----------------------------------------------------------------------===//
9122// rebase table dumping
9123//===----------------------------------------------------------------------===//
9124
9125namespace {
9126class SegInfo {
9127public:
9128 SegInfo(const object::MachOObjectFile *Obj);
9129
9130 StringRef segmentName(uint32_t SegIndex);
9131 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9132 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009133 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00009134
9135private:
9136 struct SectionInfo {
9137 uint64_t Address;
9138 uint64_t Size;
9139 StringRef SectionName;
9140 StringRef SegmentName;
9141 uint64_t OffsetInSegment;
9142 uint64_t SegmentStartAddress;
9143 uint32_t SegmentIndex;
9144 };
9145 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9146 SmallVector<SectionInfo, 32> Sections;
9147};
9148}
9149
9150SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9151 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00009152 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00009153 StringRef CurSegName;
9154 uint64_t CurSegAddress;
9155 for (const SectionRef &Section : Obj->sections()) {
9156 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00009157 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00009158 Info.Address = Section.getAddress();
9159 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00009160 Info.SegmentName =
9161 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9162 if (!Info.SegmentName.equals(CurSegName)) {
9163 ++CurSegIndex;
9164 CurSegName = Info.SegmentName;
9165 CurSegAddress = Info.Address;
9166 }
9167 Info.SegmentIndex = CurSegIndex - 1;
9168 Info.OffsetInSegment = Info.Address - CurSegAddress;
9169 Info.SegmentStartAddress = CurSegAddress;
9170 Sections.push_back(Info);
9171 }
9172}
9173
9174StringRef SegInfo::segmentName(uint32_t SegIndex) {
9175 for (const SectionInfo &SI : Sections) {
9176 if (SI.SegmentIndex == SegIndex)
9177 return SI.SegmentName;
9178 }
9179 llvm_unreachable("invalid segIndex");
9180}
9181
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009182bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9183 uint64_t OffsetInSeg) {
9184 for (const SectionInfo &SI : Sections) {
9185 if (SI.SegmentIndex != SegIndex)
9186 continue;
9187 if (SI.OffsetInSegment > OffsetInSeg)
9188 continue;
9189 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9190 continue;
9191 return true;
9192 }
9193 return false;
9194}
9195
Nick Kledzikac431442014-09-12 21:34:15 +00009196const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9197 uint64_t OffsetInSeg) {
9198 for (const SectionInfo &SI : Sections) {
9199 if (SI.SegmentIndex != SegIndex)
9200 continue;
9201 if (SI.OffsetInSegment > OffsetInSeg)
9202 continue;
9203 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9204 continue;
9205 return SI;
9206 }
9207 llvm_unreachable("segIndex and offset not in any section");
9208}
9209
9210StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9211 return findSection(SegIndex, OffsetInSeg).SectionName;
9212}
9213
9214uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9215 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9216 return SI.SegmentStartAddress + OffsetInSeg;
9217}
9218
9219void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9220 // Build table of sections so names can used in final output.
9221 SegInfo sectionTable(Obj);
9222
9223 outs() << "segment section address type\n";
9224 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9225 uint32_t SegIndex = Entry.segmentIndex();
9226 uint64_t OffsetInSeg = Entry.segmentOffset();
9227 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9228 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9229 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9230
9231 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009232 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9233 SegmentName.str().c_str(), SectionName.str().c_str(),
9234 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009235 }
9236}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009237
9238static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9239 StringRef DylibName;
9240 switch (Ordinal) {
9241 case MachO::BIND_SPECIAL_DYLIB_SELF:
9242 return "this-image";
9243 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9244 return "main-executable";
9245 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9246 return "flat-namespace";
9247 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009248 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009249 std::error_code EC =
9250 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009251 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009252 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009253 return DylibName;
9254 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009255 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009256 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009257}
9258
9259//===----------------------------------------------------------------------===//
9260// bind table dumping
9261//===----------------------------------------------------------------------===//
9262
9263void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9264 // Build table of sections so names can used in final output.
9265 SegInfo sectionTable(Obj);
9266
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009267 outs() << "segment section address type "
9268 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009269 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9270 uint32_t SegIndex = Entry.segmentIndex();
9271 uint64_t OffsetInSeg = Entry.segmentOffset();
9272 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9273 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9274 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9275
9276 // Table lines look like:
9277 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009278 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009279 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009280 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009281 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009282 << left_justify(SectionName, 18) << " "
9283 << format_hex(Address, 10, true) << " "
9284 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009285 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009286 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009287 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009288 }
9289}
9290
9291//===----------------------------------------------------------------------===//
9292// lazy bind table dumping
9293//===----------------------------------------------------------------------===//
9294
9295void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9296 // Build table of sections so names can used in final output.
9297 SegInfo sectionTable(Obj);
9298
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009299 outs() << "segment section address "
9300 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009301 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9302 uint32_t SegIndex = Entry.segmentIndex();
9303 uint64_t OffsetInSeg = Entry.segmentOffset();
9304 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9305 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9306 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9307
9308 // Table lines look like:
9309 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009310 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009311 << left_justify(SectionName, 18) << " "
9312 << format_hex(Address, 10, true) << " "
9313 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009314 << Entry.symbolName() << "\n";
9315 }
9316}
9317
Nick Kledzik56ebef42014-09-16 01:41:51 +00009318//===----------------------------------------------------------------------===//
9319// weak bind table dumping
9320//===----------------------------------------------------------------------===//
9321
9322void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9323 // Build table of sections so names can used in final output.
9324 SegInfo sectionTable(Obj);
9325
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009326 outs() << "segment section address "
9327 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009328 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9329 // Strong symbols don't have a location to update.
9330 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009331 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009332 << Entry.symbolName() << "\n";
9333 continue;
9334 }
9335 uint32_t SegIndex = Entry.segmentIndex();
9336 uint64_t OffsetInSeg = Entry.segmentOffset();
9337 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9338 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9339 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9340
9341 // Table lines look like:
9342 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009343 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009344 << left_justify(SectionName, 18) << " "
9345 << format_hex(Address, 10, true) << " "
9346 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009347 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9348 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009349 }
9350}
9351
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009352// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9353// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9354// information for that address. If the address is found its binding symbol
9355// name is returned. If not nullptr is returned.
9356static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9357 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009358 if (info->bindtable == nullptr) {
9359 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009360 SegInfo sectionTable(info->O);
9361 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9362 uint32_t SegIndex = Entry.segmentIndex();
9363 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009364 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
9365 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009366 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9367 const char *SymbolName = nullptr;
9368 StringRef name = Entry.symbolName();
9369 if (!name.empty())
9370 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00009371 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009372 }
9373 }
Kevin Enderby078be602014-10-23 19:53:12 +00009374 for (bind_table_iterator BI = info->bindtable->begin(),
9375 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009376 BI != BE; ++BI) {
9377 uint64_t Address = BI->first;
9378 if (ReferenceValue == Address) {
9379 const char *SymbolName = BI->second;
9380 return SymbolName;
9381 }
9382 }
9383 return nullptr;
9384}