blob: faace1dfb629edf9207f73f0259e71982c493347 [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"
Rafael Espindolab940b662016-09-06 19:16:48 +000023#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000024#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000025#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000026#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000027#include "llvm/MC/MCInst.h"
28#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCInstrDesc.h"
30#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000031#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000032#include "llvm/MC/MCSubtargetInfo.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000033#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000034#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000037#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000041#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000046#include "llvm/Support/ToolOutputFile.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include <algorithm>
49#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000050#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000051
Kevin Enderby9873e2c2016-05-23 21:34:12 +000052#ifdef HAVE_LIBXAR
53extern "C" {
54#include <xar/xar.h>
55}
56#endif
57
Benjamin Kramer43a772e2011-09-19 17:56:04 +000058using namespace llvm;
59using namespace object;
60
61static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062 UseDbg("g",
63 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<std::string> DSYMFile("dsym",
66 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000070
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000071static cl::opt<bool> NoLeadingAddr("no-leading-addr",
72 cl::desc("Print no leading address"));
73
Kevin Enderbyf9d60f02016-11-29 21:43:40 +000074static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
75 cl::desc("Print no leading headers"));
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",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000134 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000135
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();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000189 if (!ATypeOrErr)
190 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000191 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000192 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000193 if (!BTypeOrErr)
194 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000195 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000196 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
197 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000198 return AAddr < BAddr;
199 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000200};
201
Kevin Enderby273ae012013-06-06 17:20:50 +0000202// Types for the storted data in code table that is built before disassembly
203// and the predicate function to sort them.
204typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
205typedef std::vector<DiceTableEntry> DiceTable;
206typedef DiceTable::iterator dice_table_iterator;
207
Kevin Enderby930fdc72014-11-06 19:00:13 +0000208// This is used to search for a data in code table entry for the PC being
209// disassembled. The j parameter has the PC in j.first. A single data in code
210// table entry can cover many bytes for each of its Kind's. So if the offset,
211// aka the i.first value, of the data in code table entry plus its Length
212// covers the PC being searched for this will return true. If not it will
213// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000214static bool compareDiceTableEntries(const DiceTableEntry &i,
215 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000216 uint16_t Length;
217 i.second.getLength(Length);
218
219 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000220}
221
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000222static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000223 unsigned short Kind) {
224 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000225
226 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000227 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000228 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000229 if (Length >= 4) {
230 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000231 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000232 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000233 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000234 Size = 4;
235 } else if (Length >= 2) {
236 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000237 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000238 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000239 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000240 Size = 2;
241 } else {
242 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000243 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000244 Value = bytes[0];
245 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000246 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000247 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 if (Kind == MachO::DICE_KIND_DATA)
249 outs() << "\t@ KIND_DATA\n";
250 else
251 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000252 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000253 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000254 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000255 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000256 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000257 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
258 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000259 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000260 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000261 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000262 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000263 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000264 outs() << "\t.short " << format("%5u", Value & 0xffff)
265 << "\t@ KIND_JUMP_TABLE16\n";
266 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000267 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000268 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000269 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
270 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000271 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000272 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000273 outs() << "\t.long " << Value;
274 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
275 outs() << "\t@ KIND_JUMP_TABLE32\n";
276 else
277 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
278 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000279 break;
280 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000281 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000282}
283
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000284static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000285 std::vector<SectionRef> &Sections,
286 std::vector<SymbolRef> &Symbols,
287 SmallVectorImpl<uint64_t> &FoundFns,
288 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000289 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000290 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000291 if (!SymName)
292 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000293 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000294 Symbols.push_back(Symbol);
295 }
Owen Andersond9243c42011-10-17 21:37:35 +0000296
Alexey Samsonov48803e52014-03-13 14:37:36 +0000297 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000298 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000299 Section.getName(SectName);
300 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000301 }
302
Kevin Enderby273ae012013-06-06 17:20:50 +0000303 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000304 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000305 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000306 // We found a function starts segment, parse the addresses for later
307 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000308 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000309 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000310
Charles Davis8bdfafd2013-09-01 04:28:48 +0000311 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000312 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
313 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000314 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000315 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000316 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000317 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000318 }
319 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000320 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000321}
322
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000323static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
324 uint32_t n, uint32_t count,
325 uint32_t stride, uint64_t addr) {
326 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
327 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
328 if (n > nindirectsyms)
329 outs() << " (entries start past the end of the indirect symbol "
330 "table) (reserved1 field greater than the table size)";
331 else if (n + count > nindirectsyms)
332 outs() << " (entries extends past the end of the indirect symbol "
333 "table)";
334 outs() << "\n";
335 uint32_t cputype = O->getHeader().cputype;
336 if (cputype & MachO::CPU_ARCH_ABI64)
337 outs() << "address index";
338 else
339 outs() << "address index";
340 if (verbose)
341 outs() << " name\n";
342 else
343 outs() << "\n";
344 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
345 if (cputype & MachO::CPU_ARCH_ABI64)
346 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
347 else
Tim Northover43978372016-04-26 18:29:16 +0000348 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000349 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
350 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
351 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
352 outs() << "LOCAL\n";
353 continue;
354 }
355 if (indirect_symbol ==
356 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
357 outs() << "LOCAL ABSOLUTE\n";
358 continue;
359 }
360 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
361 outs() << "ABSOLUTE\n";
362 continue;
363 }
364 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000365 if (verbose) {
366 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
367 if (indirect_symbol < Symtab.nsyms) {
368 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
369 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000370 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000371 if (!SymName)
372 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000373 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000374 } else {
375 outs() << "?";
376 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000377 }
378 outs() << "\n";
379 }
380}
381
382static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000383 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000384 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
385 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
386 for (unsigned J = 0; J < Seg.nsects; ++J) {
387 MachO::section_64 Sec = O->getSection64(Load, J);
388 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
389 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
390 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
391 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
392 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
393 section_type == MachO::S_SYMBOL_STUBS) {
394 uint32_t stride;
395 if (section_type == MachO::S_SYMBOL_STUBS)
396 stride = Sec.reserved2;
397 else
398 stride = 8;
399 if (stride == 0) {
400 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
401 << Sec.sectname << ") "
402 << "(size of stubs in reserved2 field is zero)\n";
403 continue;
404 }
405 uint32_t count = Sec.size / stride;
406 outs() << "Indirect symbols for (" << Sec.segname << ","
407 << Sec.sectname << ") " << count << " entries";
408 uint32_t n = Sec.reserved1;
409 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
410 }
411 }
412 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
413 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
414 for (unsigned J = 0; J < Seg.nsects; ++J) {
415 MachO::section Sec = O->getSection(Load, J);
416 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
417 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
418 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
419 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
420 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
421 section_type == MachO::S_SYMBOL_STUBS) {
422 uint32_t stride;
423 if (section_type == MachO::S_SYMBOL_STUBS)
424 stride = Sec.reserved2;
425 else
426 stride = 4;
427 if (stride == 0) {
428 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
429 << Sec.sectname << ") "
430 << "(size of stubs in reserved2 field is zero)\n";
431 continue;
432 }
433 uint32_t count = Sec.size / stride;
434 outs() << "Indirect symbols for (" << Sec.segname << ","
435 << Sec.sectname << ") " << count << " entries";
436 uint32_t n = Sec.reserved1;
437 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
438 }
439 }
440 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000441 }
442}
443
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000444static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
445 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
446 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
447 outs() << "Data in code table (" << nentries << " entries)\n";
448 outs() << "offset length kind\n";
449 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
450 ++DI) {
451 uint32_t Offset;
452 DI->getOffset(Offset);
453 outs() << format("0x%08" PRIx32, Offset) << " ";
454 uint16_t Length;
455 DI->getLength(Length);
456 outs() << format("%6u", Length) << " ";
457 uint16_t Kind;
458 DI->getKind(Kind);
459 if (verbose) {
460 switch (Kind) {
461 case MachO::DICE_KIND_DATA:
462 outs() << "DATA";
463 break;
464 case MachO::DICE_KIND_JUMP_TABLE8:
465 outs() << "JUMP_TABLE8";
466 break;
467 case MachO::DICE_KIND_JUMP_TABLE16:
468 outs() << "JUMP_TABLE16";
469 break;
470 case MachO::DICE_KIND_JUMP_TABLE32:
471 outs() << "JUMP_TABLE32";
472 break;
473 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
474 outs() << "ABS_JUMP_TABLE32";
475 break;
476 default:
477 outs() << format("0x%04" PRIx32, Kind);
478 break;
479 }
480 } else
481 outs() << format("0x%04" PRIx32, Kind);
482 outs() << "\n";
483 }
484}
485
Kevin Enderby9a509442015-01-27 21:28:24 +0000486static void PrintLinkOptHints(MachOObjectFile *O) {
487 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
488 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
489 uint32_t nloh = LohLC.datasize;
490 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
491 for (uint32_t i = 0; i < nloh;) {
492 unsigned n;
493 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
494 i += n;
495 outs() << " identifier " << identifier << " ";
496 if (i >= nloh)
497 return;
498 switch (identifier) {
499 case 1:
500 outs() << "AdrpAdrp\n";
501 break;
502 case 2:
503 outs() << "AdrpLdr\n";
504 break;
505 case 3:
506 outs() << "AdrpAddLdr\n";
507 break;
508 case 4:
509 outs() << "AdrpLdrGotLdr\n";
510 break;
511 case 5:
512 outs() << "AdrpAddStr\n";
513 break;
514 case 6:
515 outs() << "AdrpLdrGotStr\n";
516 break;
517 case 7:
518 outs() << "AdrpAdd\n";
519 break;
520 case 8:
521 outs() << "AdrpLdrGot\n";
522 break;
523 default:
524 outs() << "Unknown identifier value\n";
525 break;
526 }
527 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
528 i += n;
529 outs() << " narguments " << narguments << "\n";
530 if (i >= nloh)
531 return;
532
533 for (uint32_t j = 0; j < narguments; j++) {
534 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
535 i += n;
536 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
537 if (i >= nloh)
538 return;
539 }
540 }
541}
542
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000543static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000544 unsigned Index = 0;
545 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000546 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
547 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
548 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
549 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
550 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
551 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
552 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
553 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
554 if (dl.dylib.name < dl.cmdsize) {
555 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
556 if (JustId)
557 outs() << p << "\n";
558 else {
559 outs() << "\t" << p;
560 outs() << " (compatibility version "
561 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
562 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
563 << (dl.dylib.compatibility_version & 0xff) << ",";
564 outs() << " current version "
565 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
566 << ((dl.dylib.current_version >> 8) & 0xff) << "."
567 << (dl.dylib.current_version & 0xff) << ")\n";
568 }
569 } else {
570 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
571 if (Load.C.cmd == MachO::LC_ID_DYLIB)
572 outs() << "LC_ID_DYLIB ";
573 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
574 outs() << "LC_LOAD_DYLIB ";
575 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
576 outs() << "LC_LOAD_WEAK_DYLIB ";
577 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
578 outs() << "LC_LAZY_LOAD_DYLIB ";
579 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
580 outs() << "LC_REEXPORT_DYLIB ";
581 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
582 outs() << "LC_LOAD_UPWARD_DYLIB ";
583 else
584 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000585 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000586 }
587 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000588 }
589}
590
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000591typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
592
593static void CreateSymbolAddressMap(MachOObjectFile *O,
594 SymbolAddressMap *AddrMap) {
595 // Create a map of symbol addresses to symbol names.
596 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000597 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000598 if (!STOrErr)
599 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000600 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000601 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
602 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000603 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000604 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000605 if (!SymNameOrErr)
606 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000607 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000608 if (!SymName.startswith(".objc"))
609 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000610 }
611 }
612}
613
614// GuessSymbolName is passed the address of what might be a symbol and a
615// pointer to the SymbolAddressMap. It returns the name of a symbol
616// with that address or nullptr if no symbol is found with that address.
617static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
618 const char *SymbolName = nullptr;
619 // A DenseMap can't lookup up some values.
620 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
621 StringRef name = AddrMap->lookup(value);
622 if (!name.empty())
623 SymbolName = name.data();
624 }
625 return SymbolName;
626}
627
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000628static void DumpCstringChar(const char c) {
629 char p[2];
630 p[0] = c;
631 p[1] = '\0';
632 outs().write_escaped(p);
633}
634
Kevin Enderby10ba0412015-02-04 21:38:42 +0000635static void DumpCstringSection(MachOObjectFile *O, const char *sect,
636 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000637 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000638 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000639 if (print_addresses) {
640 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000641 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000642 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000643 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000644 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000645 for (; i < sect_size && sect[i] != '\0'; i++)
646 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000647 if (i < sect_size && sect[i] == '\0')
648 outs() << "\n";
649 }
650}
651
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000652static void DumpLiteral4(uint32_t l, float f) {
653 outs() << format("0x%08" PRIx32, l);
654 if ((l & 0x7f800000) != 0x7f800000)
655 outs() << format(" (%.16e)\n", f);
656 else {
657 if (l == 0x7f800000)
658 outs() << " (+Infinity)\n";
659 else if (l == 0xff800000)
660 outs() << " (-Infinity)\n";
661 else if ((l & 0x00400000) == 0x00400000)
662 outs() << " (non-signaling Not-a-Number)\n";
663 else
664 outs() << " (signaling Not-a-Number)\n";
665 }
666}
667
668static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
669 uint32_t sect_size, uint64_t sect_addr,
670 bool print_addresses) {
671 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
672 if (print_addresses) {
673 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000674 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000675 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000676 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000677 }
678 float f;
679 memcpy(&f, sect + i, sizeof(float));
680 if (O->isLittleEndian() != sys::IsLittleEndianHost)
681 sys::swapByteOrder(f);
682 uint32_t l;
683 memcpy(&l, sect + i, sizeof(uint32_t));
684 if (O->isLittleEndian() != sys::IsLittleEndianHost)
685 sys::swapByteOrder(l);
686 DumpLiteral4(l, f);
687 }
688}
689
690static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
691 double d) {
692 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
693 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000694 Hi = (O->isLittleEndian()) ? l1 : l0;
695 Lo = (O->isLittleEndian()) ? l0 : l1;
696
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000697 // Hi is the high word, so this is equivalent to if(isfinite(d))
698 if ((Hi & 0x7ff00000) != 0x7ff00000)
699 outs() << format(" (%.16e)\n", d);
700 else {
701 if (Hi == 0x7ff00000 && Lo == 0)
702 outs() << " (+Infinity)\n";
703 else if (Hi == 0xfff00000 && Lo == 0)
704 outs() << " (-Infinity)\n";
705 else if ((Hi & 0x00080000) == 0x00080000)
706 outs() << " (non-signaling Not-a-Number)\n";
707 else
708 outs() << " (signaling Not-a-Number)\n";
709 }
710}
711
712static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
713 uint32_t sect_size, uint64_t sect_addr,
714 bool print_addresses) {
715 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
716 if (print_addresses) {
717 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000718 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000719 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000720 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000721 }
722 double d;
723 memcpy(&d, sect + i, sizeof(double));
724 if (O->isLittleEndian() != sys::IsLittleEndianHost)
725 sys::swapByteOrder(d);
726 uint32_t l0, l1;
727 memcpy(&l0, sect + i, sizeof(uint32_t));
728 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
729 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
730 sys::swapByteOrder(l0);
731 sys::swapByteOrder(l1);
732 }
733 DumpLiteral8(O, l0, l1, d);
734 }
735}
736
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000737static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
738 outs() << format("0x%08" PRIx32, l0) << " ";
739 outs() << format("0x%08" PRIx32, l1) << " ";
740 outs() << format("0x%08" PRIx32, l2) << " ";
741 outs() << format("0x%08" PRIx32, l3) << "\n";
742}
743
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000744static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
745 uint32_t sect_size, uint64_t sect_addr,
746 bool print_addresses) {
747 for (uint32_t i = 0; i < sect_size; i += 16) {
748 if (print_addresses) {
749 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000750 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000751 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000752 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000753 }
754 uint32_t l0, l1, l2, l3;
755 memcpy(&l0, sect + i, sizeof(uint32_t));
756 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
757 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
758 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
759 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
760 sys::swapByteOrder(l0);
761 sys::swapByteOrder(l1);
762 sys::swapByteOrder(l2);
763 sys::swapByteOrder(l3);
764 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000765 DumpLiteral16(l0, l1, l2, l3);
766 }
767}
768
769static void DumpLiteralPointerSection(MachOObjectFile *O,
770 const SectionRef &Section,
771 const char *sect, uint32_t sect_size,
772 uint64_t sect_addr,
773 bool print_addresses) {
774 // Collect the literal sections in this Mach-O file.
775 std::vector<SectionRef> LiteralSections;
776 for (const SectionRef &Section : O->sections()) {
777 DataRefImpl Ref = Section.getRawDataRefImpl();
778 uint32_t section_type;
779 if (O->is64Bit()) {
780 const MachO::section_64 Sec = O->getSection64(Ref);
781 section_type = Sec.flags & MachO::SECTION_TYPE;
782 } else {
783 const MachO::section Sec = O->getSection(Ref);
784 section_type = Sec.flags & MachO::SECTION_TYPE;
785 }
786 if (section_type == MachO::S_CSTRING_LITERALS ||
787 section_type == MachO::S_4BYTE_LITERALS ||
788 section_type == MachO::S_8BYTE_LITERALS ||
789 section_type == MachO::S_16BYTE_LITERALS)
790 LiteralSections.push_back(Section);
791 }
792
793 // Set the size of the literal pointer.
794 uint32_t lp_size = O->is64Bit() ? 8 : 4;
795
Eric Christopher572e03a2015-06-19 01:53:21 +0000796 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000797 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
798 for (const RelocationRef &Reloc : Section.relocations()) {
799 DataRefImpl Rel;
800 MachO::any_relocation_info RE;
801 bool isExtern = false;
802 Rel = Reloc.getRawDataRefImpl();
803 RE = O->getRelocation(Rel);
804 isExtern = O->getPlainRelocationExternal(RE);
805 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000806 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000807 symbol_iterator RelocSym = Reloc.getSymbol();
808 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
809 }
810 }
811 array_pod_sort(Relocs.begin(), Relocs.end());
812
813 // Dump each literal pointer.
814 for (uint32_t i = 0; i < sect_size; i += lp_size) {
815 if (print_addresses) {
816 if (O->is64Bit())
817 outs() << format("%016" PRIx64, sect_addr + i) << " ";
818 else
819 outs() << format("%08" PRIx64, sect_addr + i) << " ";
820 }
821 uint64_t lp;
822 if (O->is64Bit()) {
823 memcpy(&lp, sect + i, sizeof(uint64_t));
824 if (O->isLittleEndian() != sys::IsLittleEndianHost)
825 sys::swapByteOrder(lp);
826 } else {
827 uint32_t li;
828 memcpy(&li, sect + i, sizeof(uint32_t));
829 if (O->isLittleEndian() != sys::IsLittleEndianHost)
830 sys::swapByteOrder(li);
831 lp = li;
832 }
833
834 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +0000835 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
836 return P.first == i;
837 });
David Blaikie33dd45d02015-03-23 18:39:02 +0000838 if (Reloc != Relocs.end()) {
839 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000840 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000841 if (!SymName)
842 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000843 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000844 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000845 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000846
847 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +0000848 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
849 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
850 });
David Blaikie33dd45d02015-03-23 18:39:02 +0000851 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000852 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000853 continue;
854 }
855
856 uint64_t SectAddress = Sect->getAddress();
857 uint64_t SectSize = Sect->getSize();
858
859 StringRef SectName;
860 Sect->getName(SectName);
861 DataRefImpl Ref = Sect->getRawDataRefImpl();
862 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
863 outs() << SegmentName << ":" << SectName << ":";
864
865 uint32_t section_type;
866 if (O->is64Bit()) {
867 const MachO::section_64 Sec = O->getSection64(Ref);
868 section_type = Sec.flags & MachO::SECTION_TYPE;
869 } else {
870 const MachO::section Sec = O->getSection(Ref);
871 section_type = Sec.flags & MachO::SECTION_TYPE;
872 }
873
874 StringRef BytesStr;
875 Sect->getContents(BytesStr);
876 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
877
878 switch (section_type) {
879 case MachO::S_CSTRING_LITERALS:
880 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
881 i++) {
882 DumpCstringChar(Contents[i]);
883 }
884 outs() << "\n";
885 break;
886 case MachO::S_4BYTE_LITERALS:
887 float f;
888 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
889 uint32_t l;
890 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
891 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
892 sys::swapByteOrder(f);
893 sys::swapByteOrder(l);
894 }
895 DumpLiteral4(l, f);
896 break;
897 case MachO::S_8BYTE_LITERALS: {
898 double d;
899 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
900 uint32_t l0, l1;
901 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
902 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
903 sizeof(uint32_t));
904 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
905 sys::swapByteOrder(f);
906 sys::swapByteOrder(l0);
907 sys::swapByteOrder(l1);
908 }
909 DumpLiteral8(O, l0, l1, d);
910 break;
911 }
912 case MachO::S_16BYTE_LITERALS: {
913 uint32_t l0, l1, l2, l3;
914 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
915 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
916 sizeof(uint32_t));
917 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
918 sizeof(uint32_t));
919 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
920 sizeof(uint32_t));
921 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
922 sys::swapByteOrder(l0);
923 sys::swapByteOrder(l1);
924 sys::swapByteOrder(l2);
925 sys::swapByteOrder(l3);
926 }
927 DumpLiteral16(l0, l1, l2, l3);
928 break;
929 }
930 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000931 }
932}
933
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000934static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
935 uint32_t sect_size, uint64_t sect_addr,
936 SymbolAddressMap *AddrMap,
937 bool verbose) {
938 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000939 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000940 for (uint32_t i = 0; i < sect_size; i += stride) {
941 const char *SymbolName = nullptr;
942 if (O->is64Bit()) {
943 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
944 uint64_t pointer_value;
945 memcpy(&pointer_value, sect + i, stride);
946 if (O->isLittleEndian() != sys::IsLittleEndianHost)
947 sys::swapByteOrder(pointer_value);
948 outs() << format("0x%016" PRIx64, pointer_value);
949 if (verbose)
950 SymbolName = GuessSymbolName(pointer_value, AddrMap);
951 } else {
952 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
953 uint32_t pointer_value;
954 memcpy(&pointer_value, sect + i, stride);
955 if (O->isLittleEndian() != sys::IsLittleEndianHost)
956 sys::swapByteOrder(pointer_value);
957 outs() << format("0x%08" PRIx32, pointer_value);
958 if (verbose)
959 SymbolName = GuessSymbolName(pointer_value, AddrMap);
960 }
961 if (SymbolName)
962 outs() << " " << SymbolName;
963 outs() << "\n";
964 }
965}
966
967static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
968 uint32_t size, uint64_t addr) {
969 uint32_t cputype = O->getHeader().cputype;
970 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
971 uint32_t j;
972 for (uint32_t i = 0; i < size; i += j, addr += j) {
973 if (O->is64Bit())
974 outs() << format("%016" PRIx64, addr) << "\t";
975 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000976 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000977 for (j = 0; j < 16 && i + j < size; j++) {
978 uint8_t byte_word = *(sect + i + j);
979 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
980 }
981 outs() << "\n";
982 }
983 } else {
984 uint32_t j;
985 for (uint32_t i = 0; i < size; i += j, addr += j) {
986 if (O->is64Bit())
987 outs() << format("%016" PRIx64, addr) << "\t";
988 else
Kevin Enderbyc4930852016-04-27 22:36:18 +0000989 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000990 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
991 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +0000992 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000993 uint32_t long_word;
994 memcpy(&long_word, sect + i + j, sizeof(int32_t));
995 if (O->isLittleEndian() != sys::IsLittleEndianHost)
996 sys::swapByteOrder(long_word);
997 outs() << format("%08" PRIx32, long_word) << " ";
998 } else {
999 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001000 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001001 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1002 }
1003 }
1004 }
1005 outs() << "\n";
1006 }
1007 }
1008}
1009
Kevin Enderby95df54c2015-02-04 01:01:38 +00001010static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1011 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001012static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1013 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001014#ifdef HAVE_LIBXAR
1015static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1016 uint32_t size, bool verbose,
1017 bool PrintXarHeader, bool PrintXarFileHeaders,
1018 std::string XarMemberName);
1019#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001020
1021static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1022 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001023 SymbolAddressMap AddrMap;
1024 if (verbose)
1025 CreateSymbolAddressMap(O, &AddrMap);
1026
Colin LeMahieufcc32762015-07-29 19:08:10 +00001027 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1028 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001029 std::pair<StringRef, StringRef> DumpSegSectName;
1030 DumpSegSectName = DumpSection.split(',');
1031 StringRef DumpSegName, DumpSectName;
1032 if (DumpSegSectName.second.size()) {
1033 DumpSegName = DumpSegSectName.first;
1034 DumpSectName = DumpSegSectName.second;
1035 } else {
1036 DumpSegName = "";
1037 DumpSectName = DumpSegSectName.first;
1038 }
1039 for (const SectionRef &Section : O->sections()) {
1040 StringRef SectName;
1041 Section.getName(SectName);
1042 DataRefImpl Ref = Section.getRawDataRefImpl();
1043 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1044 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1045 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001046
Kevin Enderby95df54c2015-02-04 01:01:38 +00001047 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001048 if (O->is64Bit()) {
1049 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001050 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001051
1052 } else {
1053 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001054 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001055 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001056 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001057
1058 StringRef BytesStr;
1059 Section.getContents(BytesStr);
1060 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1061 uint32_t sect_size = BytesStr.size();
1062 uint64_t sect_addr = Section.getAddress();
1063
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001064 outs() << "Contents of (" << SegName << "," << SectName
1065 << ") section\n";
1066
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001067 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001068 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1069 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1070 DisassembleMachO(Filename, O, SegName, SectName);
1071 continue;
1072 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001073 if (SegName == "__TEXT" && SectName == "__info_plist") {
1074 outs() << sect;
1075 continue;
1076 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001077 if (SegName == "__OBJC" && SectName == "__protocol") {
1078 DumpProtocolSection(O, sect, sect_size, sect_addr);
1079 continue;
1080 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001081#ifdef HAVE_LIBXAR
1082 if (SegName == "__LLVM" && SectName == "__bundle") {
1083 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1084 ArchiveHeaders, "");
1085 continue;
1086 }
1087#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001088 switch (section_type) {
1089 case MachO::S_REGULAR:
1090 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1091 break;
1092 case MachO::S_ZEROFILL:
1093 outs() << "zerofill section and has no contents in the file\n";
1094 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001095 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001096 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001097 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001098 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001099 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 break;
1101 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001102 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001103 break;
1104 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001105 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1106 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001107 case MachO::S_LITERAL_POINTERS:
1108 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001109 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001110 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001111 case MachO::S_MOD_INIT_FUNC_POINTERS:
1112 case MachO::S_MOD_TERM_FUNC_POINTERS:
1113 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1114 verbose);
1115 break;
1116 default:
1117 outs() << "Unknown section type ("
1118 << format("0x%08" PRIx32, section_type) << ")\n";
1119 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1120 break;
1121 }
1122 } else {
1123 if (section_type == MachO::S_ZEROFILL)
1124 outs() << "zerofill section and has no contents in the file\n";
1125 else
1126 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1127 }
1128 }
1129 }
1130 }
1131}
1132
Kevin Enderbycd66be52015-03-11 22:06:32 +00001133static void DumpInfoPlistSectionContents(StringRef Filename,
1134 MachOObjectFile *O) {
1135 for (const SectionRef &Section : O->sections()) {
1136 StringRef SectName;
1137 Section.getName(SectName);
1138 DataRefImpl Ref = Section.getRawDataRefImpl();
1139 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1140 if (SegName == "__TEXT" && SectName == "__info_plist") {
1141 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1142 StringRef BytesStr;
1143 Section.getContents(BytesStr);
1144 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1145 outs() << sect;
1146 return;
1147 }
1148 }
1149}
1150
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001151// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1152// and if it is and there is a list of architecture flags is specified then
1153// check to make sure this Mach-O file is one of those architectures or all
1154// architectures were specified. If not then an error is generated and this
1155// routine returns false. Else it returns true.
1156static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001157 auto *MachO = dyn_cast<MachOObjectFile>(O);
1158
1159 if (!MachO || ArchAll || ArchFlags.empty())
1160 return true;
1161
1162 MachO::mach_header H;
1163 MachO::mach_header_64 H_64;
1164 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001165 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001166 if (MachO->is64Bit()) {
1167 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001168 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1169 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001170 } else {
1171 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001172 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1173 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001174 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001175 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001176 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001177 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001178 })) {
1179 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1180 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001181 }
1182 return true;
1183}
1184
Kevin Enderby0fc11822015-04-01 20:57:01 +00001185static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1186
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001187// ProcessMachO() is passed a single opened Mach-O file, which may be an
1188// archive member and or in a slice of a universal file. It prints the
1189// the file name and header info and then processes it according to the
1190// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001191static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001192 StringRef ArchiveMemberName = StringRef(),
1193 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001194 // If we are doing some processing here on the Mach-O file print the header
1195 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001196 // UniversalHeaders or ArchiveHeaders.
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001197 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001198 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001199 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001200 if (!NoLeadingHeaders) {
1201 outs() << Name;
1202 if (!ArchiveMemberName.empty())
1203 outs() << '(' << ArchiveMemberName << ')';
1204 if (!ArchitectureName.empty())
1205 outs() << " (architecture " << ArchitectureName << ")";
1206 outs() << ":\n";
1207 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001208 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001209 // To use the report_error() form with an ArchiveName and FileName set
1210 // these up based on what is passed for Name and ArchiveMemberName.
1211 StringRef ArchiveName;
1212 StringRef FileName;
1213 if (!ArchiveMemberName.empty()) {
1214 ArchiveName = Name;
1215 FileName = ArchiveMemberName;
1216 } else {
1217 ArchiveName = StringRef();
1218 FileName = Name;
1219 }
1220
1221 // If we need the symbol table to do the operation then check it here to
1222 // produce a good error message as to where the Mach-O file comes from in
1223 // the error message.
1224 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1225 UnwindInfo)
1226 if (Error Err = MachOOF->checkSymbolTable())
1227 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001228
1229 if (Disassemble)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001230 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001231 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001232 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001233 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001234 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001235 if (LinkOptHints)
1236 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001237 if (Relocations)
1238 PrintRelocations(MachOOF);
1239 if (SectionHeaders)
1240 PrintSectionHeaders(MachOOF);
1241 if (SectionContents)
1242 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001243 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001244 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001245 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001246 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001247 if (DylibsUsed)
1248 PrintDylibs(MachOOF, false);
1249 if (DylibId)
1250 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001251 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001252 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001253 if (UnwindInfo)
1254 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001255 if (PrivateHeaders) {
1256 printMachOFileHeader(MachOOF);
1257 printMachOLoadCommands(MachOOF);
1258 }
1259 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001260 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001261 if (ObjcMetaData)
1262 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001263 if (ExportsTrie)
1264 printExportsTrie(MachOOF);
1265 if (Rebase)
1266 printRebaseTable(MachOOF);
1267 if (Bind)
1268 printBindTable(MachOOF);
1269 if (LazyBind)
1270 printLazyBindTable(MachOOF);
1271 if (WeakBind)
1272 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001273
1274 if (DwarfDumpType != DIDT_Null) {
1275 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1276 // Dump the complete DWARF structure.
1277 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1278 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001279}
1280
Kevin Enderby131d1772015-01-09 19:22:37 +00001281// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1282static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1283 outs() << " cputype (" << cputype << ")\n";
1284 outs() << " cpusubtype (" << cpusubtype << ")\n";
1285}
1286
1287// printCPUType() helps print_fat_headers by printing the cputype and
1288// pusubtype (symbolically for the one's it knows about).
1289static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1290 switch (cputype) {
1291 case MachO::CPU_TYPE_I386:
1292 switch (cpusubtype) {
1293 case MachO::CPU_SUBTYPE_I386_ALL:
1294 outs() << " cputype CPU_TYPE_I386\n";
1295 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1296 break;
1297 default:
1298 printUnknownCPUType(cputype, cpusubtype);
1299 break;
1300 }
1301 break;
1302 case MachO::CPU_TYPE_X86_64:
1303 switch (cpusubtype) {
1304 case MachO::CPU_SUBTYPE_X86_64_ALL:
1305 outs() << " cputype CPU_TYPE_X86_64\n";
1306 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1307 break;
1308 case MachO::CPU_SUBTYPE_X86_64_H:
1309 outs() << " cputype CPU_TYPE_X86_64\n";
1310 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1311 break;
1312 default:
1313 printUnknownCPUType(cputype, cpusubtype);
1314 break;
1315 }
1316 break;
1317 case MachO::CPU_TYPE_ARM:
1318 switch (cpusubtype) {
1319 case MachO::CPU_SUBTYPE_ARM_ALL:
1320 outs() << " cputype CPU_TYPE_ARM\n";
1321 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1322 break;
1323 case MachO::CPU_SUBTYPE_ARM_V4T:
1324 outs() << " cputype CPU_TYPE_ARM\n";
1325 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1326 break;
1327 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1328 outs() << " cputype CPU_TYPE_ARM\n";
1329 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1330 break;
1331 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1332 outs() << " cputype CPU_TYPE_ARM\n";
1333 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1334 break;
1335 case MachO::CPU_SUBTYPE_ARM_V6:
1336 outs() << " cputype CPU_TYPE_ARM\n";
1337 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1338 break;
1339 case MachO::CPU_SUBTYPE_ARM_V6M:
1340 outs() << " cputype CPU_TYPE_ARM\n";
1341 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1342 break;
1343 case MachO::CPU_SUBTYPE_ARM_V7:
1344 outs() << " cputype CPU_TYPE_ARM\n";
1345 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1346 break;
1347 case MachO::CPU_SUBTYPE_ARM_V7EM:
1348 outs() << " cputype CPU_TYPE_ARM\n";
1349 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1350 break;
1351 case MachO::CPU_SUBTYPE_ARM_V7K:
1352 outs() << " cputype CPU_TYPE_ARM\n";
1353 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1354 break;
1355 case MachO::CPU_SUBTYPE_ARM_V7M:
1356 outs() << " cputype CPU_TYPE_ARM\n";
1357 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1358 break;
1359 case MachO::CPU_SUBTYPE_ARM_V7S:
1360 outs() << " cputype CPU_TYPE_ARM\n";
1361 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1362 break;
1363 default:
1364 printUnknownCPUType(cputype, cpusubtype);
1365 break;
1366 }
1367 break;
1368 case MachO::CPU_TYPE_ARM64:
1369 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1370 case MachO::CPU_SUBTYPE_ARM64_ALL:
1371 outs() << " cputype CPU_TYPE_ARM64\n";
1372 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1373 break;
1374 default:
1375 printUnknownCPUType(cputype, cpusubtype);
1376 break;
1377 }
1378 break;
1379 default:
1380 printUnknownCPUType(cputype, cpusubtype);
1381 break;
1382 }
1383}
1384
1385static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1386 bool verbose) {
1387 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001388 if (verbose) {
1389 if (UB->getMagic() == MachO::FAT_MAGIC)
1390 outs() << "fat_magic FAT_MAGIC\n";
1391 else // UB->getMagic() == MachO::FAT_MAGIC_64
1392 outs() << "fat_magic FAT_MAGIC_64\n";
1393 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001394 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1395
1396 uint32_t nfat_arch = UB->getNumberOfObjects();
1397 StringRef Buf = UB->getData();
1398 uint64_t size = Buf.size();
1399 uint64_t big_size = sizeof(struct MachO::fat_header) +
1400 nfat_arch * sizeof(struct MachO::fat_arch);
1401 outs() << "nfat_arch " << UB->getNumberOfObjects();
1402 if (nfat_arch == 0)
1403 outs() << " (malformed, contains zero architecture types)\n";
1404 else if (big_size > size)
1405 outs() << " (malformed, architectures past end of file)\n";
1406 else
1407 outs() << "\n";
1408
1409 for (uint32_t i = 0; i < nfat_arch; ++i) {
1410 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1411 uint32_t cputype = OFA.getCPUType();
1412 uint32_t cpusubtype = OFA.getCPUSubType();
1413 outs() << "architecture ";
1414 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1415 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1416 uint32_t other_cputype = other_OFA.getCPUType();
1417 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001418 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001419 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001420 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001421 outs() << "(illegal duplicate architecture) ";
1422 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001423 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001424 }
1425 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001426 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001427 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1428 } else {
1429 outs() << i << "\n";
1430 outs() << " cputype " << cputype << "\n";
1431 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1432 << "\n";
1433 }
1434 if (verbose &&
1435 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1436 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1437 else
1438 outs() << " capabilities "
1439 << format("0x%" PRIx32,
1440 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1441 outs() << " offset " << OFA.getOffset();
1442 if (OFA.getOffset() > size)
1443 outs() << " (past end of file)";
1444 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1445 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1446 outs() << "\n";
1447 outs() << " size " << OFA.getSize();
1448 big_size = OFA.getOffset() + OFA.getSize();
1449 if (big_size > size)
1450 outs() << " (past end of file)";
1451 outs() << "\n";
1452 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1453 << ")\n";
1454 }
1455}
1456
Kevin Enderby6524bd82016-07-19 20:47:07 +00001457static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1458 bool verbose, bool print_offset,
1459 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001460 if (print_offset)
1461 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001462 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1463 if (!ModeOrErr)
1464 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1465 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001466 if (verbose) {
1467 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1468 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1469 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001470 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1471 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1472 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1473 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1474 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1475 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1476 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1477 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1478 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001479 } else {
1480 outs() << format("0%o ", Mode);
1481 }
1482
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001483 Expected<unsigned> UIDOrErr = C.getUID();
1484 if (!UIDOrErr)
1485 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1486 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001487 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001488 Expected<unsigned> GIDOrErr = C.getGID();
1489 if (!GIDOrErr)
1490 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1491 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001492 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001493 Expected<uint64_t> Size = C.getRawSize();
1494 if (!Size)
1495 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001496 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001497
1498 StringRef RawLastModified = C.getRawLastModified();
1499 if (verbose) {
1500 unsigned Seconds;
1501 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001502 outs() << "(date: \"" << RawLastModified
1503 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001504 else {
1505 // Since cime(3) returns a 26 character string of the form:
1506 // "Sun Sep 16 01:03:52 1973\n\0"
1507 // just print 24 characters.
1508 time_t t = Seconds;
1509 outs() << format("%.24s ", ctime(&t));
1510 }
1511 } else {
1512 outs() << RawLastModified << " ";
1513 }
1514
1515 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001516 Expected<StringRef> NameOrErr = C.getName();
1517 if (!NameOrErr) {
1518 consumeError(NameOrErr.takeError());
1519 Expected<StringRef> NameOrErr = C.getRawName();
1520 if (!NameOrErr)
1521 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1522 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001523 outs() << RawName << "\n";
1524 } else {
1525 StringRef Name = NameOrErr.get();
1526 outs() << Name << "\n";
1527 }
1528 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001529 Expected<StringRef> NameOrErr = C.getRawName();
1530 if (!NameOrErr)
1531 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1532 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001533 outs() << RawName << "\n";
1534 }
1535}
1536
Kevin Enderby6524bd82016-07-19 20:47:07 +00001537static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1538 bool print_offset,
1539 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001540 Error Err = Error::success();
1541 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001542 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001543 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1544
Lang Hamesfc209622016-07-14 02:24:01 +00001545 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001546 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001547}
1548
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001549// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1550// -arch flags selecting just those slices as specified by them and also parses
1551// archive files. Then for each individual Mach-O file ProcessMachO() is
1552// called to process the file based on the command line options.
1553void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001554 // Check for -arch all and verifiy the -arch flags are valid.
1555 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1556 if (ArchFlags[i] == "all") {
1557 ArchAll = true;
1558 } else {
1559 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1560 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1561 "'for the -arch option\n";
1562 return;
1563 }
1564 }
1565 }
1566
1567 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001568 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1569 if (!BinaryOrErr)
1570 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001571 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001572
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001573 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1574 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001575 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001576 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1577
Mehdi Amini41af4302016-11-11 04:28:40 +00001578 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001579 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001580 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1581 if (!ChildOrErr) {
1582 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1583 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001584 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001585 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001586 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1587 if (!checkMachOAndArchFlags(O, Filename))
1588 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001589 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001590 }
1591 }
Lang Hamesfc209622016-07-14 02:24:01 +00001592 if (Err)
1593 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001594 return;
1595 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001596 if (UniversalHeaders) {
1597 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001598 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001599 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001600 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1601 // If we have a list of architecture flags specified dump only those.
1602 if (!ArchAll && ArchFlags.size() != 0) {
1603 // Look for a slice in the universal binary that matches each ArchFlag.
1604 bool ArchFound;
1605 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1606 ArchFound = false;
1607 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1608 E = UB->end_objects();
1609 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001610 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001611 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001612 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001613 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001614 std::string ArchitectureName = "";
1615 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +00001616 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001617 if (ObjOrErr) {
1618 ObjectFile &O = *ObjOrErr.get();
1619 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001620 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001621 } else if (auto E = isNotObjectErrorInvalidFileType(
1622 ObjOrErr.takeError())) {
1623 report_error(Filename, StringRef(), std::move(E),
1624 ArchitectureName);
1625 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001626 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001627 I->getAsArchive()) {
1628 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001629 outs() << "Archive : " << Filename;
1630 if (!ArchitectureName.empty())
1631 outs() << " (architecture " << ArchitectureName << ")";
1632 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001633 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001634 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1635 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001636 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001637 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001638 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1639 if (!ChildOrErr) {
1640 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001641 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001642 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001643 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001644 if (MachOObjectFile *O =
1645 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001646 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001647 }
Lang Hamesfc209622016-07-14 02:24:01 +00001648 if (Err)
1649 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001650 } else {
1651 consumeError(AOrErr.takeError());
1652 error("Mach-O universal file: " + Filename + " for " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001653 "architecture " + StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001654 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001655 }
1656 }
1657 }
1658 if (!ArchFound) {
1659 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1660 << "architecture: " + ArchFlags[i] + "\n";
1661 return;
1662 }
1663 }
1664 return;
1665 }
1666 // No architecture flags were specified so if this contains a slice that
1667 // matches the host architecture dump only that.
1668 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001669 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1670 E = UB->end_objects();
1671 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001672 if (MachOObjectFile::getHostArch().getArchName() ==
Kevin Enderby59343a92016-12-16 22:54:02 +00001673 I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001674 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001675 std::string ArchiveName;
1676 ArchiveName.clear();
1677 if (ObjOrErr) {
1678 ObjectFile &O = *ObjOrErr.get();
1679 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001680 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001681 } else if (auto E = isNotObjectErrorInvalidFileType(
1682 ObjOrErr.takeError())) {
1683 report_error(Filename, std::move(E));
1684 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001685 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001686 I->getAsArchive()) {
1687 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001688 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001689 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001690 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1691 ArchiveMemberOffsets);
Mehdi Amini41af4302016-11-11 04:28:40 +00001692 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001693 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001694 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1695 if (!ChildOrErr) {
1696 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1697 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001698 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001699 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001700 if (MachOObjectFile *O =
1701 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001702 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001703 }
Lang Hamesfc209622016-07-14 02:24:01 +00001704 if (Err)
1705 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001706 } else {
1707 consumeError(AOrErr.takeError());
1708 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001709 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001710 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001711 }
1712 return;
1713 }
1714 }
1715 }
1716 // Either all architectures have been specified or none have been specified
1717 // and this does not contain the host architecture so dump all the slices.
1718 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1719 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1720 E = UB->end_objects();
1721 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001722 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001723 std::string ArchitectureName = "";
1724 if (moreThanOneArch)
Kevin Enderby59343a92016-12-16 22:54:02 +00001725 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001726 if (ObjOrErr) {
1727 ObjectFile &Obj = *ObjOrErr.get();
1728 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001729 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001730 } else if (auto E = isNotObjectErrorInvalidFileType(
1731 ObjOrErr.takeError())) {
1732 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1733 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001734 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1735 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001736 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001737 outs() << "Archive : " << Filename;
1738 if (!ArchitectureName.empty())
1739 outs() << " (architecture " << ArchitectureName << ")";
1740 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001741 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001742 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1743 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001744 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001745 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001746 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1747 if (!ChildOrErr) {
1748 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001749 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001750 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001751 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001752 if (MachOObjectFile *O =
1753 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1754 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001755 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1756 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001757 }
1758 }
Lang Hamesfc209622016-07-14 02:24:01 +00001759 if (Err)
1760 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001761 } else {
1762 consumeError(AOrErr.takeError());
1763 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001764 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001765 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001766 }
1767 }
1768 return;
1769 }
1770 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1771 if (!checkMachOAndArchFlags(O, Filename))
1772 return;
1773 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001774 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001775 } else
1776 errs() << "llvm-objdump: '" << Filename << "': "
1777 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001778 return;
1779 }
1780 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001781}
1782
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001783// The block of info used by the Symbolizer call backs.
1784struct DisassembleInfo {
1785 bool verbose;
1786 MachOObjectFile *O;
1787 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001788 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001789 std::vector<SectionRef> *Sections;
1790 const char *class_name;
1791 const char *selector_name;
1792 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001793 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001794 uint64_t adrp_addr;
1795 uint32_t adrp_inst;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00001796 std::unique_ptr<SymbolAddressMap> bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001797 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001798};
1799
1800// SymbolizerGetOpInfo() is the operand information call back function.
1801// This is called to get the symbolic information for operand(s) of an
1802// instruction when it is being done. This routine does this from
1803// the relocation information, symbol table, etc. That block of information
1804// is a pointer to the struct DisassembleInfo that was passed when the
1805// disassembler context was created and passed to back to here when
1806// called back by the disassembler for instruction operands that could have
1807// relocation information. The address of the instruction containing operand is
1808// at the Pc parameter. The immediate value the operand has is passed in
1809// op_info->Value and is at Offset past the start of the instruction and has a
1810// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1811// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1812// names and addends of the symbolic expression to add for the operand. The
1813// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1814// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001815static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1816 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001817 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1818 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001819 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001820
1821 // Make sure all fields returned are zero if we don't set them.
1822 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1823 op_info->Value = value;
1824
1825 // If the TagType is not the value 1 which it code knows about or if no
1826 // verbose symbolic information is wanted then just return 0, indicating no
1827 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001828 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001829 return 0;
1830
1831 unsigned int Arch = info->O->getArch();
1832 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001833 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1834 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001835 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1836 // TODO:
1837 // Search the external relocation entries of a fully linked image
1838 // (if any) for an entry that matches this segment offset.
1839 // uint32_t seg_offset = (Pc + Offset);
1840 return 0;
1841 }
1842 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1843 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001844 uint32_t sect_addr = info->S.getAddress();
1845 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1846 bool reloc_found = false;
1847 DataRefImpl Rel;
1848 MachO::any_relocation_info RE;
1849 bool isExtern = false;
1850 SymbolRef Symbol;
1851 bool r_scattered = false;
1852 uint32_t r_value, pair_r_value, r_type;
1853 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001854 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001855 if (RelocOffset == sect_offset) {
1856 Rel = Reloc.getRawDataRefImpl();
1857 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001858 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001859 r_scattered = info->O->isRelocationScattered(RE);
1860 if (r_scattered) {
1861 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001862 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1863 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1864 DataRefImpl RelNext = Rel;
1865 info->O->moveRelocationNext(RelNext);
1866 MachO::any_relocation_info RENext;
1867 RENext = info->O->getRelocation(RelNext);
1868 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001869 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001870 else
1871 return 0;
1872 }
1873 } else {
1874 isExtern = info->O->getPlainRelocationExternal(RE);
1875 if (isExtern) {
1876 symbol_iterator RelocSym = Reloc.getSymbol();
1877 Symbol = *RelocSym;
1878 }
1879 }
1880 reloc_found = true;
1881 break;
1882 }
1883 }
1884 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001885 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001886 if (!SymName)
1887 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001888 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001889 op_info->AddSymbol.Present = 1;
1890 op_info->AddSymbol.Name = name;
1891 // For i386 extern relocation entries the value in the instruction is
1892 // the offset from the symbol, and value is already set in op_info->Value.
1893 return 1;
1894 }
1895 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1896 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001897 const char *add = GuessSymbolName(r_value, info->AddrMap);
1898 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001899 uint32_t offset = value - (r_value - pair_r_value);
1900 op_info->AddSymbol.Present = 1;
1901 if (add != nullptr)
1902 op_info->AddSymbol.Name = add;
1903 else
1904 op_info->AddSymbol.Value = r_value;
1905 op_info->SubtractSymbol.Present = 1;
1906 if (sub != nullptr)
1907 op_info->SubtractSymbol.Name = sub;
1908 else
1909 op_info->SubtractSymbol.Value = pair_r_value;
1910 op_info->Value = offset;
1911 return 1;
1912 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001913 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001914 }
1915 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001916 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1917 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001918 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1919 // TODO:
1920 // Search the external relocation entries of a fully linked image
1921 // (if any) for an entry that matches this segment offset.
1922 // uint64_t seg_offset = (Pc + Offset);
1923 return 0;
1924 }
1925 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1926 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001927 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001928 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1929 bool reloc_found = false;
1930 DataRefImpl Rel;
1931 MachO::any_relocation_info RE;
1932 bool isExtern = false;
1933 SymbolRef Symbol;
1934 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001935 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001936 if (RelocOffset == sect_offset) {
1937 Rel = Reloc.getRawDataRefImpl();
1938 RE = info->O->getRelocation(Rel);
1939 // NOTE: Scattered relocations don't exist on x86_64.
1940 isExtern = info->O->getPlainRelocationExternal(RE);
1941 if (isExtern) {
1942 symbol_iterator RelocSym = Reloc.getSymbol();
1943 Symbol = *RelocSym;
1944 }
1945 reloc_found = true;
1946 break;
1947 }
1948 }
1949 if (reloc_found && isExtern) {
1950 // The Value passed in will be adjusted by the Pc if the instruction
1951 // adds the Pc. But for x86_64 external relocation entries the Value
1952 // is the offset from the external symbol.
1953 if (info->O->getAnyRelocationPCRel(RE))
1954 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001955 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001956 if (!SymName)
1957 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001958 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001959 unsigned Type = info->O->getAnyRelocationType(RE);
1960 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1961 DataRefImpl RelNext = Rel;
1962 info->O->moveRelocationNext(RelNext);
1963 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1964 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1965 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1966 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1967 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1968 op_info->SubtractSymbol.Present = 1;
1969 op_info->SubtractSymbol.Name = name;
1970 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1971 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001972 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001973 if (!SymNameNext)
1974 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001975 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001976 }
1977 }
1978 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1979 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1980 op_info->AddSymbol.Present = 1;
1981 op_info->AddSymbol.Name = name;
1982 return 1;
1983 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001984 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001985 }
1986 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001987 if (Offset != 0 || (Size != 4 && Size != 2))
1988 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001989 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1990 // TODO:
1991 // Search the external relocation entries of a fully linked image
1992 // (if any) for an entry that matches this segment offset.
1993 // uint32_t seg_offset = (Pc + Offset);
1994 return 0;
1995 }
1996 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1997 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001998 uint32_t sect_addr = info->S.getAddress();
1999 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002000 DataRefImpl Rel;
2001 MachO::any_relocation_info RE;
2002 bool isExtern = false;
2003 SymbolRef Symbol;
2004 bool r_scattered = false;
2005 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002006 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002007 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2008 uint64_t RelocOffset = Reloc.getOffset();
2009 return RelocOffset == sect_offset;
2010 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002011
2012 if (Reloc == info->S.relocations().end())
2013 return 0;
2014
2015 Rel = Reloc->getRawDataRefImpl();
2016 RE = info->O->getRelocation(Rel);
2017 r_length = info->O->getAnyRelocationLength(RE);
2018 r_scattered = info->O->isRelocationScattered(RE);
2019 if (r_scattered) {
2020 r_value = info->O->getScatteredRelocationValue(RE);
2021 r_type = info->O->getScatteredRelocationType(RE);
2022 } else {
2023 r_type = info->O->getAnyRelocationType(RE);
2024 isExtern = info->O->getPlainRelocationExternal(RE);
2025 if (isExtern) {
2026 symbol_iterator RelocSym = Reloc->getSymbol();
2027 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002028 }
2029 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002030 if (r_type == MachO::ARM_RELOC_HALF ||
2031 r_type == MachO::ARM_RELOC_SECTDIFF ||
2032 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2033 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2034 DataRefImpl RelNext = Rel;
2035 info->O->moveRelocationNext(RelNext);
2036 MachO::any_relocation_info RENext;
2037 RENext = info->O->getRelocation(RelNext);
2038 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2039 if (info->O->isRelocationScattered(RENext))
2040 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2041 }
2042
2043 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002044 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002045 if (!SymName)
2046 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002047 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002048 op_info->AddSymbol.Present = 1;
2049 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002050 switch (r_type) {
2051 case MachO::ARM_RELOC_HALF:
2052 if ((r_length & 0x1) == 1) {
2053 op_info->Value = value << 16 | other_half;
2054 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2055 } else {
2056 op_info->Value = other_half << 16 | value;
2057 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002058 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002059 break;
2060 default:
2061 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002062 }
2063 return 1;
2064 }
2065 // If we have a branch that is not an external relocation entry then
2066 // return 0 so the code in tryAddingSymbolicOperand() can use the
2067 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002068 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002069 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2070 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002071 return 0;
2072
2073 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002074 if (r_type == MachO::ARM_RELOC_HALF ||
2075 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2076 if ((r_length & 0x1) == 1)
2077 value = value << 16 | other_half;
2078 else
2079 value = other_half << 16 | value;
2080 }
2081 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2082 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2083 offset = value - r_value;
2084 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002085 }
2086
David Blaikie33dd45d02015-03-23 18:39:02 +00002087 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002088 if ((r_length & 0x1) == 1)
2089 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2090 else
2091 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002092 const char *add = GuessSymbolName(r_value, info->AddrMap);
2093 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002094 int32_t offset = value - (r_value - pair_r_value);
2095 op_info->AddSymbol.Present = 1;
2096 if (add != nullptr)
2097 op_info->AddSymbol.Name = add;
2098 else
2099 op_info->AddSymbol.Value = r_value;
2100 op_info->SubtractSymbol.Present = 1;
2101 if (sub != nullptr)
2102 op_info->SubtractSymbol.Name = sub;
2103 else
2104 op_info->SubtractSymbol.Value = pair_r_value;
2105 op_info->Value = offset;
2106 return 1;
2107 }
2108
Kevin Enderby930fdc72014-11-06 19:00:13 +00002109 op_info->AddSymbol.Present = 1;
2110 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002111 if (r_type == MachO::ARM_RELOC_HALF) {
2112 if ((r_length & 0x1) == 1)
2113 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2114 else
2115 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002116 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002117 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002118 if (add != nullptr) {
2119 op_info->AddSymbol.Name = add;
2120 return 1;
2121 }
2122 op_info->AddSymbol.Value = value;
2123 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002124 }
2125 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002126 if (Offset != 0 || Size != 4)
2127 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002128 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2129 // TODO:
2130 // Search the external relocation entries of a fully linked image
2131 // (if any) for an entry that matches this segment offset.
2132 // uint64_t seg_offset = (Pc + Offset);
2133 return 0;
2134 }
2135 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2136 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002137 uint64_t sect_addr = info->S.getAddress();
2138 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002139 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002140 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2141 uint64_t RelocOffset = Reloc.getOffset();
2142 return RelocOffset == sect_offset;
2143 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002144
David Blaikie33dd45d02015-03-23 18:39:02 +00002145 if (Reloc == info->S.relocations().end())
2146 return 0;
2147
2148 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2149 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2150 uint32_t r_type = info->O->getAnyRelocationType(RE);
2151 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2152 DataRefImpl RelNext = Rel;
2153 info->O->moveRelocationNext(RelNext);
2154 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2155 if (value == 0) {
2156 value = info->O->getPlainRelocationSymbolNum(RENext);
2157 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002158 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002159 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002160 // NOTE: Scattered relocations don't exist on arm64.
2161 if (!info->O->getPlainRelocationExternal(RE))
2162 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002163 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002164 if (!SymName)
2165 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002166 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002167 op_info->AddSymbol.Present = 1;
2168 op_info->AddSymbol.Name = name;
2169
2170 switch (r_type) {
2171 case MachO::ARM64_RELOC_PAGE21:
2172 /* @page */
2173 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2174 break;
2175 case MachO::ARM64_RELOC_PAGEOFF12:
2176 /* @pageoff */
2177 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2178 break;
2179 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2180 /* @gotpage */
2181 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2182 break;
2183 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2184 /* @gotpageoff */
2185 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2186 break;
2187 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2188 /* @tvlppage is not implemented in llvm-mc */
2189 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2190 break;
2191 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2192 /* @tvlppageoff is not implemented in llvm-mc */
2193 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2194 break;
2195 default:
2196 case MachO::ARM64_RELOC_BRANCH26:
2197 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2198 break;
2199 }
2200 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002201 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002202 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002203}
2204
Kevin Enderbybf246f52014-09-24 23:08:22 +00002205// GuessCstringPointer is passed the address of what might be a pointer to a
2206// literal string in a cstring section. If that address is in a cstring section
2207// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002208static const char *GuessCstringPointer(uint64_t ReferenceValue,
2209 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002210 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002211 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2212 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2213 for (unsigned J = 0; J < Seg.nsects; ++J) {
2214 MachO::section_64 Sec = info->O->getSection64(Load, J);
2215 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2216 if (section_type == MachO::S_CSTRING_LITERALS &&
2217 ReferenceValue >= Sec.addr &&
2218 ReferenceValue < Sec.addr + Sec.size) {
2219 uint64_t sect_offset = ReferenceValue - Sec.addr;
2220 uint64_t object_offset = Sec.offset + sect_offset;
2221 StringRef MachOContents = info->O->getData();
2222 uint64_t object_size = MachOContents.size();
2223 const char *object_addr = (const char *)MachOContents.data();
2224 if (object_offset < object_size) {
2225 const char *name = object_addr + object_offset;
2226 return name;
2227 } else {
2228 return nullptr;
2229 }
2230 }
2231 }
2232 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2233 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2234 for (unsigned J = 0; J < Seg.nsects; ++J) {
2235 MachO::section Sec = info->O->getSection(Load, J);
2236 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2237 if (section_type == MachO::S_CSTRING_LITERALS &&
2238 ReferenceValue >= Sec.addr &&
2239 ReferenceValue < Sec.addr + Sec.size) {
2240 uint64_t sect_offset = ReferenceValue - Sec.addr;
2241 uint64_t object_offset = Sec.offset + sect_offset;
2242 StringRef MachOContents = info->O->getData();
2243 uint64_t object_size = MachOContents.size();
2244 const char *object_addr = (const char *)MachOContents.data();
2245 if (object_offset < object_size) {
2246 const char *name = object_addr + object_offset;
2247 return name;
2248 } else {
2249 return nullptr;
2250 }
2251 }
2252 }
2253 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002254 }
2255 return nullptr;
2256}
2257
Kevin Enderby85974882014-09-26 22:20:44 +00002258// GuessIndirectSymbol returns the name of the indirect symbol for the
2259// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2260// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2261// symbol name being referenced by the stub or pointer.
2262static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2263 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002264 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2265 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002266 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002267 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2268 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2269 for (unsigned J = 0; J < Seg.nsects; ++J) {
2270 MachO::section_64 Sec = info->O->getSection64(Load, J);
2271 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2272 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2273 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2274 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2275 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2276 section_type == MachO::S_SYMBOL_STUBS) &&
2277 ReferenceValue >= Sec.addr &&
2278 ReferenceValue < Sec.addr + Sec.size) {
2279 uint32_t stride;
2280 if (section_type == MachO::S_SYMBOL_STUBS)
2281 stride = Sec.reserved2;
2282 else
2283 stride = 8;
2284 if (stride == 0)
2285 return nullptr;
2286 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2287 if (index < Dysymtab.nindirectsyms) {
2288 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002289 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002290 if (indirect_symbol < Symtab.nsyms) {
2291 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2292 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002293 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002294 if (!SymName)
2295 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002296 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002297 return name;
2298 }
2299 }
2300 }
2301 }
2302 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2303 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2304 for (unsigned J = 0; J < Seg.nsects; ++J) {
2305 MachO::section Sec = info->O->getSection(Load, J);
2306 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2307 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2308 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2309 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2310 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2311 section_type == MachO::S_SYMBOL_STUBS) &&
2312 ReferenceValue >= Sec.addr &&
2313 ReferenceValue < Sec.addr + Sec.size) {
2314 uint32_t stride;
2315 if (section_type == MachO::S_SYMBOL_STUBS)
2316 stride = Sec.reserved2;
2317 else
2318 stride = 4;
2319 if (stride == 0)
2320 return nullptr;
2321 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2322 if (index < Dysymtab.nindirectsyms) {
2323 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002324 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002325 if (indirect_symbol < Symtab.nsyms) {
2326 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2327 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002328 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002329 if (!SymName)
2330 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002331 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002332 return name;
2333 }
2334 }
2335 }
2336 }
2337 }
Kevin Enderby85974882014-09-26 22:20:44 +00002338 }
2339 return nullptr;
2340}
2341
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002342// method_reference() is called passing it the ReferenceName that might be
2343// a reference it to an Objective-C method call. If so then it allocates and
2344// assembles a method call string with the values last seen and saved in
2345// the DisassembleInfo's class_name and selector_name fields. This is saved
2346// into the method field of the info and any previous string is free'ed.
2347// Then the class_name field in the info is set to nullptr. The method call
2348// string is set into ReferenceName and ReferenceType is set to
2349// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2350// then both ReferenceType and ReferenceName are left unchanged.
2351static void method_reference(struct DisassembleInfo *info,
2352 uint64_t *ReferenceType,
2353 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002354 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002355 if (*ReferenceName != nullptr) {
2356 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002357 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002358 if (info->method != nullptr)
2359 free(info->method);
2360 if (info->class_name != nullptr) {
2361 info->method = (char *)malloc(5 + strlen(info->class_name) +
2362 strlen(info->selector_name));
2363 if (info->method != nullptr) {
2364 strcpy(info->method, "+[");
2365 strcat(info->method, info->class_name);
2366 strcat(info->method, " ");
2367 strcat(info->method, info->selector_name);
2368 strcat(info->method, "]");
2369 *ReferenceName = info->method;
2370 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2371 }
2372 } else {
2373 info->method = (char *)malloc(9 + strlen(info->selector_name));
2374 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002375 if (Arch == Triple::x86_64)
2376 strcpy(info->method, "-[%rdi ");
2377 else if (Arch == Triple::aarch64)
2378 strcpy(info->method, "-[x0 ");
2379 else
2380 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002381 strcat(info->method, info->selector_name);
2382 strcat(info->method, "]");
2383 *ReferenceName = info->method;
2384 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2385 }
2386 }
2387 info->class_name = nullptr;
2388 }
2389 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 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 info->method = (char *)malloc(17 + strlen(info->selector_name));
2394 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002395 if (Arch == Triple::x86_64)
2396 strcpy(info->method, "-[[%rdi super] ");
2397 else if (Arch == Triple::aarch64)
2398 strcpy(info->method, "-[[x0 super] ");
2399 else
2400 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002401 strcat(info->method, info->selector_name);
2402 strcat(info->method, "]");
2403 *ReferenceName = info->method;
2404 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2405 }
2406 info->class_name = nullptr;
2407 }
2408 }
2409 }
2410}
2411
2412// GuessPointerPointer() is passed the address of what might be a pointer to
2413// a reference to an Objective-C class, selector, message ref or cfstring.
2414// If so the value of the pointer is returned and one of the booleans are set
2415// to true. If not zero is returned and all the booleans are set to false.
2416static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2417 struct DisassembleInfo *info,
2418 bool &classref, bool &selref, bool &msgref,
2419 bool &cfstring) {
2420 classref = false;
2421 selref = false;
2422 msgref = false;
2423 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002424 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002425 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2426 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2427 for (unsigned J = 0; J < Seg.nsects; ++J) {
2428 MachO::section_64 Sec = info->O->getSection64(Load, J);
2429 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2430 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2431 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2432 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2433 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2434 ReferenceValue >= Sec.addr &&
2435 ReferenceValue < Sec.addr + Sec.size) {
2436 uint64_t sect_offset = ReferenceValue - Sec.addr;
2437 uint64_t object_offset = Sec.offset + sect_offset;
2438 StringRef MachOContents = info->O->getData();
2439 uint64_t object_size = MachOContents.size();
2440 const char *object_addr = (const char *)MachOContents.data();
2441 if (object_offset < object_size) {
2442 uint64_t pointer_value;
2443 memcpy(&pointer_value, object_addr + object_offset,
2444 sizeof(uint64_t));
2445 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2446 sys::swapByteOrder(pointer_value);
2447 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2448 selref = true;
2449 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2450 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2451 classref = true;
2452 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2453 ReferenceValue + 8 < Sec.addr + Sec.size) {
2454 msgref = true;
2455 memcpy(&pointer_value, object_addr + object_offset + 8,
2456 sizeof(uint64_t));
2457 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2458 sys::swapByteOrder(pointer_value);
2459 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2460 cfstring = true;
2461 return pointer_value;
2462 } else {
2463 return 0;
2464 }
2465 }
2466 }
2467 }
2468 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002469 }
2470 return 0;
2471}
2472
2473// get_pointer_64 returns a pointer to the bytes in the object file at the
2474// Address from a section in the Mach-O file. And indirectly returns the
2475// offset into the section, number of bytes left in the section past the offset
2476// and which section is was being referenced. If the Address is not in a
2477// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002478static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2479 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002480 DisassembleInfo *info,
2481 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002482 offset = 0;
2483 left = 0;
2484 S = SectionRef();
2485 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2486 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2487 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002488 if (SectSize == 0)
2489 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002490 if (objc_only) {
2491 StringRef SectName;
2492 ((*(info->Sections))[SectIdx]).getName(SectName);
2493 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2494 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2495 if (SegName != "__OBJC" && SectName != "__cstring")
2496 continue;
2497 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002498 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2499 S = (*(info->Sections))[SectIdx];
2500 offset = Address - SectAddress;
2501 left = SectSize - offset;
2502 StringRef SectContents;
2503 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2504 return SectContents.data() + offset;
2505 }
2506 }
2507 return nullptr;
2508}
2509
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002510static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2511 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002512 DisassembleInfo *info,
2513 bool objc_only = false) {
2514 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002515}
2516
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002517// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2518// the symbol indirectly through n_value. Based on the relocation information
2519// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002520// If no relocation information is found and a non-zero ReferenceValue for the
2521// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002522static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2523 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002524 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002525 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002526 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002527 return nullptr;
2528
2529 // See if there is an external relocation entry at the sect_offset.
2530 bool reloc_found = false;
2531 DataRefImpl Rel;
2532 MachO::any_relocation_info RE;
2533 bool isExtern = false;
2534 SymbolRef Symbol;
2535 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002536 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002537 if (RelocOffset == sect_offset) {
2538 Rel = Reloc.getRawDataRefImpl();
2539 RE = info->O->getRelocation(Rel);
2540 if (info->O->isRelocationScattered(RE))
2541 continue;
2542 isExtern = info->O->getPlainRelocationExternal(RE);
2543 if (isExtern) {
2544 symbol_iterator RelocSym = Reloc.getSymbol();
2545 Symbol = *RelocSym;
2546 }
2547 reloc_found = true;
2548 break;
2549 }
2550 }
2551 // If there is an external relocation entry for a symbol in this section
2552 // at this section_offset then use that symbol's value for the n_value
2553 // and return its name.
2554 const char *SymbolName = nullptr;
2555 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002556 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002557 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002558 if (!NameOrError)
2559 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002560 StringRef Name = *NameOrError;
2561 if (!Name.empty()) {
2562 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002563 return SymbolName;
2564 }
2565 }
2566
2567 // TODO: For fully linked images, look through the external relocation
2568 // entries off the dynamic symtab command. For these the r_offset is from the
2569 // start of the first writeable segment in the Mach-O file. So the offset
2570 // to this section from that segment is passed to this routine by the caller,
2571 // as the database_offset. Which is the difference of the section's starting
2572 // address and the first writable segment.
2573 //
2574 // NOTE: need add passing the database_offset to this routine.
2575
Kevin Enderby0fc11822015-04-01 20:57:01 +00002576 // We did not find an external relocation entry so look up the ReferenceValue
2577 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002578 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002579
2580 return SymbolName;
2581}
2582
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002583static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2584 DisassembleInfo *info,
2585 uint32_t ReferenceValue) {
2586 uint64_t n_value64;
2587 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2588}
2589
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002590// These are structs in the Objective-C meta data and read to produce the
2591// comments for disassembly. While these are part of the ABI they are no
2592// public defintions. So the are here not in include/llvm/Support/MachO.h .
2593
2594// The cfstring object in a 64-bit Mach-O file.
2595struct cfstring64_t {
2596 uint64_t isa; // class64_t * (64-bit pointer)
2597 uint64_t flags; // flag bits
2598 uint64_t characters; // char * (64-bit pointer)
2599 uint64_t length; // number of non-NULL characters in above
2600};
2601
2602// The class object in a 64-bit Mach-O file.
2603struct class64_t {
2604 uint64_t isa; // class64_t * (64-bit pointer)
2605 uint64_t superclass; // class64_t * (64-bit pointer)
2606 uint64_t cache; // Cache (64-bit pointer)
2607 uint64_t vtable; // IMP * (64-bit pointer)
2608 uint64_t data; // class_ro64_t * (64-bit pointer)
2609};
2610
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002611struct class32_t {
2612 uint32_t isa; /* class32_t * (32-bit pointer) */
2613 uint32_t superclass; /* class32_t * (32-bit pointer) */
2614 uint32_t cache; /* Cache (32-bit pointer) */
2615 uint32_t vtable; /* IMP * (32-bit pointer) */
2616 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2617};
2618
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002619struct class_ro64_t {
2620 uint32_t flags;
2621 uint32_t instanceStart;
2622 uint32_t instanceSize;
2623 uint32_t reserved;
2624 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2625 uint64_t name; // const char * (64-bit pointer)
2626 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2627 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2628 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2629 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2630 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2631};
2632
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002633struct class_ro32_t {
2634 uint32_t flags;
2635 uint32_t instanceStart;
2636 uint32_t instanceSize;
2637 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2638 uint32_t name; /* const char * (32-bit pointer) */
2639 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2640 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2641 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2642 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2643 uint32_t baseProperties; /* const struct objc_property_list *
2644 (32-bit pointer) */
2645};
2646
2647/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002648#define RO_META (1 << 0)
2649#define RO_ROOT (1 << 1)
2650#define RO_HAS_CXX_STRUCTORS (1 << 2)
2651
2652struct method_list64_t {
2653 uint32_t entsize;
2654 uint32_t count;
2655 /* struct method64_t first; These structures follow inline */
2656};
2657
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002658struct method_list32_t {
2659 uint32_t entsize;
2660 uint32_t count;
2661 /* struct method32_t first; These structures follow inline */
2662};
2663
Kevin Enderby0fc11822015-04-01 20:57:01 +00002664struct method64_t {
2665 uint64_t name; /* SEL (64-bit pointer) */
2666 uint64_t types; /* const char * (64-bit pointer) */
2667 uint64_t imp; /* IMP (64-bit pointer) */
2668};
2669
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002670struct method32_t {
2671 uint32_t name; /* SEL (32-bit pointer) */
2672 uint32_t types; /* const char * (32-bit pointer) */
2673 uint32_t imp; /* IMP (32-bit pointer) */
2674};
2675
Kevin Enderby0fc11822015-04-01 20:57:01 +00002676struct protocol_list64_t {
2677 uint64_t count; /* uintptr_t (a 64-bit value) */
2678 /* struct protocol64_t * list[0]; These pointers follow inline */
2679};
2680
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002681struct protocol_list32_t {
2682 uint32_t count; /* uintptr_t (a 32-bit value) */
2683 /* struct protocol32_t * list[0]; These pointers follow inline */
2684};
2685
Kevin Enderby0fc11822015-04-01 20:57:01 +00002686struct protocol64_t {
2687 uint64_t isa; /* id * (64-bit pointer) */
2688 uint64_t name; /* const char * (64-bit pointer) */
2689 uint64_t protocols; /* struct protocol_list64_t *
2690 (64-bit pointer) */
2691 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2692 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2693 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2694 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2695 uint64_t instanceProperties; /* struct objc_property_list *
2696 (64-bit pointer) */
2697};
2698
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002699struct protocol32_t {
2700 uint32_t isa; /* id * (32-bit pointer) */
2701 uint32_t name; /* const char * (32-bit pointer) */
2702 uint32_t protocols; /* struct protocol_list_t *
2703 (32-bit pointer) */
2704 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2705 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2706 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2707 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2708 uint32_t instanceProperties; /* struct objc_property_list *
2709 (32-bit pointer) */
2710};
2711
Kevin Enderby0fc11822015-04-01 20:57:01 +00002712struct ivar_list64_t {
2713 uint32_t entsize;
2714 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002715 /* struct ivar64_t first; These structures follow inline */
2716};
2717
2718struct ivar_list32_t {
2719 uint32_t entsize;
2720 uint32_t count;
2721 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002722};
2723
2724struct ivar64_t {
2725 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2726 uint64_t name; /* const char * (64-bit pointer) */
2727 uint64_t type; /* const char * (64-bit pointer) */
2728 uint32_t alignment;
2729 uint32_t size;
2730};
2731
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002732struct ivar32_t {
2733 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2734 uint32_t name; /* const char * (32-bit pointer) */
2735 uint32_t type; /* const char * (32-bit pointer) */
2736 uint32_t alignment;
2737 uint32_t size;
2738};
2739
Kevin Enderby0fc11822015-04-01 20:57:01 +00002740struct objc_property_list64 {
2741 uint32_t entsize;
2742 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002743 /* struct objc_property64 first; These structures follow inline */
2744};
2745
2746struct objc_property_list32 {
2747 uint32_t entsize;
2748 uint32_t count;
2749 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002750};
2751
2752struct objc_property64 {
2753 uint64_t name; /* const char * (64-bit pointer) */
2754 uint64_t attributes; /* const char * (64-bit pointer) */
2755};
2756
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002757struct objc_property32 {
2758 uint32_t name; /* const char * (32-bit pointer) */
2759 uint32_t attributes; /* const char * (32-bit pointer) */
2760};
2761
Kevin Enderby0fc11822015-04-01 20:57:01 +00002762struct category64_t {
2763 uint64_t name; /* const char * (64-bit pointer) */
2764 uint64_t cls; /* struct class_t * (64-bit pointer) */
2765 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2766 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2767 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2768 uint64_t instanceProperties; /* struct objc_property_list *
2769 (64-bit pointer) */
2770};
2771
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002772struct category32_t {
2773 uint32_t name; /* const char * (32-bit pointer) */
2774 uint32_t cls; /* struct class_t * (32-bit pointer) */
2775 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2776 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2777 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2778 uint32_t instanceProperties; /* struct objc_property_list *
2779 (32-bit pointer) */
2780};
2781
Kevin Enderby0fc11822015-04-01 20:57:01 +00002782struct objc_image_info64 {
2783 uint32_t version;
2784 uint32_t flags;
2785};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002786struct objc_image_info32 {
2787 uint32_t version;
2788 uint32_t flags;
2789};
Kevin Enderby846c0002015-04-16 17:19:59 +00002790struct imageInfo_t {
2791 uint32_t version;
2792 uint32_t flags;
2793};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002794/* masks for objc_image_info.flags */
2795#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2796#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2797
2798struct message_ref64 {
2799 uint64_t imp; /* IMP (64-bit pointer) */
2800 uint64_t sel; /* SEL (64-bit pointer) */
2801};
2802
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002803struct message_ref32 {
2804 uint32_t imp; /* IMP (32-bit pointer) */
2805 uint32_t sel; /* SEL (32-bit pointer) */
2806};
2807
Kevin Enderby846c0002015-04-16 17:19:59 +00002808// Objective-C 1 (32-bit only) meta data structs.
2809
2810struct objc_module_t {
2811 uint32_t version;
2812 uint32_t size;
2813 uint32_t name; /* char * (32-bit pointer) */
2814 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2815};
2816
2817struct objc_symtab_t {
2818 uint32_t sel_ref_cnt;
2819 uint32_t refs; /* SEL * (32-bit pointer) */
2820 uint16_t cls_def_cnt;
2821 uint16_t cat_def_cnt;
2822 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2823};
2824
2825struct objc_class_t {
2826 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2827 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2828 uint32_t name; /* const char * (32-bit pointer) */
2829 int32_t version;
2830 int32_t info;
2831 int32_t instance_size;
2832 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2833 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2834 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2835 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2836};
2837
2838#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2839// class is not a metaclass
2840#define CLS_CLASS 0x1
2841// class is a metaclass
2842#define CLS_META 0x2
2843
2844struct objc_category_t {
2845 uint32_t category_name; /* char * (32-bit pointer) */
2846 uint32_t class_name; /* char * (32-bit pointer) */
2847 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2848 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2849 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2850};
2851
2852struct objc_ivar_t {
2853 uint32_t ivar_name; /* char * (32-bit pointer) */
2854 uint32_t ivar_type; /* char * (32-bit pointer) */
2855 int32_t ivar_offset;
2856};
2857
2858struct objc_ivar_list_t {
2859 int32_t ivar_count;
2860 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2861};
2862
2863struct objc_method_list_t {
2864 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2865 int32_t method_count;
2866 // struct objc_method_t method_list[1]; /* variable length structure */
2867};
2868
2869struct objc_method_t {
2870 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2871 uint32_t method_types; /* char * (32-bit pointer) */
2872 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2873 (32-bit pointer) */
2874};
2875
2876struct objc_protocol_list_t {
2877 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2878 int32_t count;
2879 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2880 // (32-bit pointer) */
2881};
2882
2883struct objc_protocol_t {
2884 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2885 uint32_t protocol_name; /* char * (32-bit pointer) */
2886 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2887 uint32_t instance_methods; /* struct objc_method_description_list *
2888 (32-bit pointer) */
2889 uint32_t class_methods; /* struct objc_method_description_list *
2890 (32-bit pointer) */
2891};
2892
2893struct objc_method_description_list_t {
2894 int32_t count;
2895 // struct objc_method_description_t list[1];
2896};
2897
2898struct objc_method_description_t {
2899 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2900 uint32_t types; /* char * (32-bit pointer) */
2901};
2902
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002903inline void swapStruct(struct cfstring64_t &cfs) {
2904 sys::swapByteOrder(cfs.isa);
2905 sys::swapByteOrder(cfs.flags);
2906 sys::swapByteOrder(cfs.characters);
2907 sys::swapByteOrder(cfs.length);
2908}
2909
2910inline void swapStruct(struct class64_t &c) {
2911 sys::swapByteOrder(c.isa);
2912 sys::swapByteOrder(c.superclass);
2913 sys::swapByteOrder(c.cache);
2914 sys::swapByteOrder(c.vtable);
2915 sys::swapByteOrder(c.data);
2916}
2917
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002918inline void swapStruct(struct class32_t &c) {
2919 sys::swapByteOrder(c.isa);
2920 sys::swapByteOrder(c.superclass);
2921 sys::swapByteOrder(c.cache);
2922 sys::swapByteOrder(c.vtable);
2923 sys::swapByteOrder(c.data);
2924}
2925
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002926inline void swapStruct(struct class_ro64_t &cro) {
2927 sys::swapByteOrder(cro.flags);
2928 sys::swapByteOrder(cro.instanceStart);
2929 sys::swapByteOrder(cro.instanceSize);
2930 sys::swapByteOrder(cro.reserved);
2931 sys::swapByteOrder(cro.ivarLayout);
2932 sys::swapByteOrder(cro.name);
2933 sys::swapByteOrder(cro.baseMethods);
2934 sys::swapByteOrder(cro.baseProtocols);
2935 sys::swapByteOrder(cro.ivars);
2936 sys::swapByteOrder(cro.weakIvarLayout);
2937 sys::swapByteOrder(cro.baseProperties);
2938}
2939
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002940inline void swapStruct(struct class_ro32_t &cro) {
2941 sys::swapByteOrder(cro.flags);
2942 sys::swapByteOrder(cro.instanceStart);
2943 sys::swapByteOrder(cro.instanceSize);
2944 sys::swapByteOrder(cro.ivarLayout);
2945 sys::swapByteOrder(cro.name);
2946 sys::swapByteOrder(cro.baseMethods);
2947 sys::swapByteOrder(cro.baseProtocols);
2948 sys::swapByteOrder(cro.ivars);
2949 sys::swapByteOrder(cro.weakIvarLayout);
2950 sys::swapByteOrder(cro.baseProperties);
2951}
2952
Kevin Enderby0fc11822015-04-01 20:57:01 +00002953inline void swapStruct(struct method_list64_t &ml) {
2954 sys::swapByteOrder(ml.entsize);
2955 sys::swapByteOrder(ml.count);
2956}
2957
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002958inline void swapStruct(struct method_list32_t &ml) {
2959 sys::swapByteOrder(ml.entsize);
2960 sys::swapByteOrder(ml.count);
2961}
2962
Kevin Enderby0fc11822015-04-01 20:57:01 +00002963inline void swapStruct(struct method64_t &m) {
2964 sys::swapByteOrder(m.name);
2965 sys::swapByteOrder(m.types);
2966 sys::swapByteOrder(m.imp);
2967}
2968
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002969inline void swapStruct(struct method32_t &m) {
2970 sys::swapByteOrder(m.name);
2971 sys::swapByteOrder(m.types);
2972 sys::swapByteOrder(m.imp);
2973}
2974
Kevin Enderby0fc11822015-04-01 20:57:01 +00002975inline void swapStruct(struct protocol_list64_t &pl) {
2976 sys::swapByteOrder(pl.count);
2977}
2978
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002979inline void swapStruct(struct protocol_list32_t &pl) {
2980 sys::swapByteOrder(pl.count);
2981}
2982
Kevin Enderby0fc11822015-04-01 20:57:01 +00002983inline void swapStruct(struct protocol64_t &p) {
2984 sys::swapByteOrder(p.isa);
2985 sys::swapByteOrder(p.name);
2986 sys::swapByteOrder(p.protocols);
2987 sys::swapByteOrder(p.instanceMethods);
2988 sys::swapByteOrder(p.classMethods);
2989 sys::swapByteOrder(p.optionalInstanceMethods);
2990 sys::swapByteOrder(p.optionalClassMethods);
2991 sys::swapByteOrder(p.instanceProperties);
2992}
2993
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002994inline void swapStruct(struct protocol32_t &p) {
2995 sys::swapByteOrder(p.isa);
2996 sys::swapByteOrder(p.name);
2997 sys::swapByteOrder(p.protocols);
2998 sys::swapByteOrder(p.instanceMethods);
2999 sys::swapByteOrder(p.classMethods);
3000 sys::swapByteOrder(p.optionalInstanceMethods);
3001 sys::swapByteOrder(p.optionalClassMethods);
3002 sys::swapByteOrder(p.instanceProperties);
3003}
3004
Kevin Enderby0fc11822015-04-01 20:57:01 +00003005inline void swapStruct(struct ivar_list64_t &il) {
3006 sys::swapByteOrder(il.entsize);
3007 sys::swapByteOrder(il.count);
3008}
3009
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003010inline void swapStruct(struct ivar_list32_t &il) {
3011 sys::swapByteOrder(il.entsize);
3012 sys::swapByteOrder(il.count);
3013}
3014
Kevin Enderby0fc11822015-04-01 20:57:01 +00003015inline void swapStruct(struct ivar64_t &i) {
3016 sys::swapByteOrder(i.offset);
3017 sys::swapByteOrder(i.name);
3018 sys::swapByteOrder(i.type);
3019 sys::swapByteOrder(i.alignment);
3020 sys::swapByteOrder(i.size);
3021}
3022
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003023inline void swapStruct(struct ivar32_t &i) {
3024 sys::swapByteOrder(i.offset);
3025 sys::swapByteOrder(i.name);
3026 sys::swapByteOrder(i.type);
3027 sys::swapByteOrder(i.alignment);
3028 sys::swapByteOrder(i.size);
3029}
3030
Kevin Enderby0fc11822015-04-01 20:57:01 +00003031inline void swapStruct(struct objc_property_list64 &pl) {
3032 sys::swapByteOrder(pl.entsize);
3033 sys::swapByteOrder(pl.count);
3034}
3035
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003036inline void swapStruct(struct objc_property_list32 &pl) {
3037 sys::swapByteOrder(pl.entsize);
3038 sys::swapByteOrder(pl.count);
3039}
3040
Kevin Enderby0fc11822015-04-01 20:57:01 +00003041inline void swapStruct(struct objc_property64 &op) {
3042 sys::swapByteOrder(op.name);
3043 sys::swapByteOrder(op.attributes);
3044}
3045
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003046inline void swapStruct(struct objc_property32 &op) {
3047 sys::swapByteOrder(op.name);
3048 sys::swapByteOrder(op.attributes);
3049}
3050
Kevin Enderby0fc11822015-04-01 20:57:01 +00003051inline void swapStruct(struct category64_t &c) {
3052 sys::swapByteOrder(c.name);
3053 sys::swapByteOrder(c.cls);
3054 sys::swapByteOrder(c.instanceMethods);
3055 sys::swapByteOrder(c.classMethods);
3056 sys::swapByteOrder(c.protocols);
3057 sys::swapByteOrder(c.instanceProperties);
3058}
3059
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003060inline void swapStruct(struct category32_t &c) {
3061 sys::swapByteOrder(c.name);
3062 sys::swapByteOrder(c.cls);
3063 sys::swapByteOrder(c.instanceMethods);
3064 sys::swapByteOrder(c.classMethods);
3065 sys::swapByteOrder(c.protocols);
3066 sys::swapByteOrder(c.instanceProperties);
3067}
3068
Kevin Enderby0fc11822015-04-01 20:57:01 +00003069inline void swapStruct(struct objc_image_info64 &o) {
3070 sys::swapByteOrder(o.version);
3071 sys::swapByteOrder(o.flags);
3072}
3073
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003074inline void swapStruct(struct objc_image_info32 &o) {
3075 sys::swapByteOrder(o.version);
3076 sys::swapByteOrder(o.flags);
3077}
3078
Kevin Enderby846c0002015-04-16 17:19:59 +00003079inline void swapStruct(struct imageInfo_t &o) {
3080 sys::swapByteOrder(o.version);
3081 sys::swapByteOrder(o.flags);
3082}
3083
Kevin Enderby0fc11822015-04-01 20:57:01 +00003084inline void swapStruct(struct message_ref64 &mr) {
3085 sys::swapByteOrder(mr.imp);
3086 sys::swapByteOrder(mr.sel);
3087}
3088
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003089inline void swapStruct(struct message_ref32 &mr) {
3090 sys::swapByteOrder(mr.imp);
3091 sys::swapByteOrder(mr.sel);
3092}
3093
Kevin Enderby846c0002015-04-16 17:19:59 +00003094inline void swapStruct(struct objc_module_t &module) {
3095 sys::swapByteOrder(module.version);
3096 sys::swapByteOrder(module.size);
3097 sys::swapByteOrder(module.name);
3098 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003099}
Kevin Enderby846c0002015-04-16 17:19:59 +00003100
3101inline void swapStruct(struct objc_symtab_t &symtab) {
3102 sys::swapByteOrder(symtab.sel_ref_cnt);
3103 sys::swapByteOrder(symtab.refs);
3104 sys::swapByteOrder(symtab.cls_def_cnt);
3105 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003106}
Kevin Enderby846c0002015-04-16 17:19:59 +00003107
3108inline void swapStruct(struct objc_class_t &objc_class) {
3109 sys::swapByteOrder(objc_class.isa);
3110 sys::swapByteOrder(objc_class.super_class);
3111 sys::swapByteOrder(objc_class.name);
3112 sys::swapByteOrder(objc_class.version);
3113 sys::swapByteOrder(objc_class.info);
3114 sys::swapByteOrder(objc_class.instance_size);
3115 sys::swapByteOrder(objc_class.ivars);
3116 sys::swapByteOrder(objc_class.methodLists);
3117 sys::swapByteOrder(objc_class.cache);
3118 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003119}
Kevin Enderby846c0002015-04-16 17:19:59 +00003120
3121inline void swapStruct(struct objc_category_t &objc_category) {
3122 sys::swapByteOrder(objc_category.category_name);
3123 sys::swapByteOrder(objc_category.class_name);
3124 sys::swapByteOrder(objc_category.instance_methods);
3125 sys::swapByteOrder(objc_category.class_methods);
3126 sys::swapByteOrder(objc_category.protocols);
3127}
3128
3129inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3130 sys::swapByteOrder(objc_ivar_list.ivar_count);
3131}
3132
3133inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3134 sys::swapByteOrder(objc_ivar.ivar_name);
3135 sys::swapByteOrder(objc_ivar.ivar_type);
3136 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003137}
Kevin Enderby846c0002015-04-16 17:19:59 +00003138
3139inline void swapStruct(struct objc_method_list_t &method_list) {
3140 sys::swapByteOrder(method_list.obsolete);
3141 sys::swapByteOrder(method_list.method_count);
3142}
3143
3144inline void swapStruct(struct objc_method_t &method) {
3145 sys::swapByteOrder(method.method_name);
3146 sys::swapByteOrder(method.method_types);
3147 sys::swapByteOrder(method.method_imp);
3148}
3149
3150inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3151 sys::swapByteOrder(protocol_list.next);
3152 sys::swapByteOrder(protocol_list.count);
3153}
3154
3155inline void swapStruct(struct objc_protocol_t &protocol) {
3156 sys::swapByteOrder(protocol.isa);
3157 sys::swapByteOrder(protocol.protocol_name);
3158 sys::swapByteOrder(protocol.protocol_list);
3159 sys::swapByteOrder(protocol.instance_methods);
3160 sys::swapByteOrder(protocol.class_methods);
3161}
3162
3163inline void swapStruct(struct objc_method_description_list_t &mdl) {
3164 sys::swapByteOrder(mdl.count);
3165}
3166
3167inline void swapStruct(struct objc_method_description_t &md) {
3168 sys::swapByteOrder(md.name);
3169 sys::swapByteOrder(md.types);
3170}
3171
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003172static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3173 struct DisassembleInfo *info);
3174
3175// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3176// to an Objective-C class and returns the class name. It is also passed the
3177// address of the pointer, so when the pointer is zero as it can be in an .o
3178// file, that is used to look for an external relocation entry with a symbol
3179// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003180static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3181 uint64_t ReferenceValue,
3182 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003183 const char *r;
3184 uint32_t offset, left;
3185 SectionRef S;
3186
3187 // The pointer_value can be 0 in an object file and have a relocation
3188 // entry for the class symbol at the ReferenceValue (the address of the
3189 // pointer).
3190 if (pointer_value == 0) {
3191 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3192 if (r == nullptr || left < sizeof(uint64_t))
3193 return nullptr;
3194 uint64_t n_value;
3195 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3196 if (symbol_name == nullptr)
3197 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003198 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003199 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3200 return class_name + 2;
3201 else
3202 return nullptr;
3203 }
3204
3205 // The case were the pointer_value is non-zero and points to a class defined
3206 // in this Mach-O file.
3207 r = get_pointer_64(pointer_value, offset, left, S, info);
3208 if (r == nullptr || left < sizeof(struct class64_t))
3209 return nullptr;
3210 struct class64_t c;
3211 memcpy(&c, r, sizeof(struct class64_t));
3212 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3213 swapStruct(c);
3214 if (c.data == 0)
3215 return nullptr;
3216 r = get_pointer_64(c.data, offset, left, S, info);
3217 if (r == nullptr || left < sizeof(struct class_ro64_t))
3218 return nullptr;
3219 struct class_ro64_t cro;
3220 memcpy(&cro, r, sizeof(struct class_ro64_t));
3221 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3222 swapStruct(cro);
3223 if (cro.name == 0)
3224 return nullptr;
3225 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3226 return name;
3227}
3228
3229// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3230// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003231static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3232 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003233 const char *r, *name;
3234 uint32_t offset, left;
3235 SectionRef S;
3236 struct cfstring64_t cfs;
3237 uint64_t cfs_characters;
3238
3239 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3240 if (r == nullptr || left < sizeof(struct cfstring64_t))
3241 return nullptr;
3242 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3243 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3244 swapStruct(cfs);
3245 if (cfs.characters == 0) {
3246 uint64_t n_value;
3247 const char *symbol_name = get_symbol_64(
3248 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3249 if (symbol_name == nullptr)
3250 return nullptr;
3251 cfs_characters = n_value;
3252 } else
3253 cfs_characters = cfs.characters;
3254 name = get_pointer_64(cfs_characters, offset, left, S, info);
3255
3256 return name;
3257}
3258
3259// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3260// of a pointer to an Objective-C selector reference when the pointer value is
3261// zero as in a .o file and is likely to have a external relocation entry with
3262// who's symbol's n_value is the real pointer to the selector name. If that is
3263// the case the real pointer to the selector name is returned else 0 is
3264// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003265static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3266 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003267 uint32_t offset, left;
3268 SectionRef S;
3269
3270 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3271 if (r == nullptr || left < sizeof(uint64_t))
3272 return 0;
3273 uint64_t n_value;
3274 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3275 if (symbol_name == nullptr)
3276 return 0;
3277 return n_value;
3278}
3279
Kevin Enderby0fc11822015-04-01 20:57:01 +00003280static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3281 const char *sectname) {
3282 for (const SectionRef &Section : O->sections()) {
3283 StringRef SectName;
3284 Section.getName(SectName);
3285 DataRefImpl Ref = Section.getRawDataRefImpl();
3286 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3287 if (SegName == segname && SectName == sectname)
3288 return Section;
3289 }
3290 return SectionRef();
3291}
3292
3293static void
3294walk_pointer_list_64(const char *listname, const SectionRef S,
3295 MachOObjectFile *O, struct DisassembleInfo *info,
3296 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3297 if (S == SectionRef())
3298 return;
3299
3300 StringRef SectName;
3301 S.getName(SectName);
3302 DataRefImpl Ref = S.getRawDataRefImpl();
3303 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3304 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3305
3306 StringRef BytesStr;
3307 S.getContents(BytesStr);
3308 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3309
3310 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3311 uint32_t left = S.getSize() - i;
3312 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3313 uint64_t p = 0;
3314 memcpy(&p, Contents + i, size);
3315 if (i + sizeof(uint64_t) > S.getSize())
3316 outs() << listname << " list pointer extends past end of (" << SegName
3317 << "," << SectName << ") section\n";
3318 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3319
3320 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3321 sys::swapByteOrder(p);
3322
3323 uint64_t n_value = 0;
3324 const char *name = get_symbol_64(i, S, info, n_value, p);
3325 if (name == nullptr)
3326 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3327
3328 if (n_value != 0) {
3329 outs() << format("0x%" PRIx64, n_value);
3330 if (p != 0)
3331 outs() << " + " << format("0x%" PRIx64, p);
3332 } else
3333 outs() << format("0x%" PRIx64, p);
3334 if (name != nullptr)
3335 outs() << " " << name;
3336 outs() << "\n";
3337
3338 p += n_value;
3339 if (func)
3340 func(p, info);
3341 }
3342}
3343
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003344static void
3345walk_pointer_list_32(const char *listname, const SectionRef S,
3346 MachOObjectFile *O, struct DisassembleInfo *info,
3347 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3348 if (S == SectionRef())
3349 return;
3350
3351 StringRef SectName;
3352 S.getName(SectName);
3353 DataRefImpl Ref = S.getRawDataRefImpl();
3354 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3355 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3356
3357 StringRef BytesStr;
3358 S.getContents(BytesStr);
3359 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3360
3361 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3362 uint32_t left = S.getSize() - i;
3363 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3364 uint32_t p = 0;
3365 memcpy(&p, Contents + i, size);
3366 if (i + sizeof(uint32_t) > S.getSize())
3367 outs() << listname << " list pointer extends past end of (" << SegName
3368 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003369 uint32_t Address = S.getAddress() + i;
3370 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003371
3372 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3373 sys::swapByteOrder(p);
3374 outs() << format("0x%" PRIx32, p);
3375
3376 const char *name = get_symbol_32(i, S, info, p);
3377 if (name != nullptr)
3378 outs() << " " << name;
3379 outs() << "\n";
3380
3381 if (func)
3382 func(p, info);
3383 }
3384}
3385
3386static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003387 if (layout_map == nullptr)
3388 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003389 outs() << " layout map: ";
3390 do {
3391 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3392 left--;
3393 layout_map++;
3394 } while (*layout_map != '\0' && left != 0);
3395 outs() << "\n";
3396}
3397
Kevin Enderby0fc11822015-04-01 20:57:01 +00003398static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3399 uint32_t offset, left;
3400 SectionRef S;
3401 const char *layout_map;
3402
3403 if (p == 0)
3404 return;
3405 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003406 print_layout_map(layout_map, left);
3407}
3408
3409static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3410 uint32_t offset, left;
3411 SectionRef S;
3412 const char *layout_map;
3413
3414 if (p == 0)
3415 return;
3416 layout_map = get_pointer_32(p, offset, left, S, info);
3417 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003418}
3419
3420static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3421 const char *indent) {
3422 struct method_list64_t ml;
3423 struct method64_t m;
3424 const char *r;
3425 uint32_t offset, xoffset, left, i;
3426 SectionRef S, xS;
3427 const char *name, *sym_name;
3428 uint64_t n_value;
3429
3430 r = get_pointer_64(p, offset, left, S, info);
3431 if (r == nullptr)
3432 return;
3433 memset(&ml, '\0', sizeof(struct method_list64_t));
3434 if (left < sizeof(struct method_list64_t)) {
3435 memcpy(&ml, r, left);
3436 outs() << " (method_list_t entends past the end of the section)\n";
3437 } else
3438 memcpy(&ml, r, sizeof(struct method_list64_t));
3439 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3440 swapStruct(ml);
3441 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3442 outs() << indent << "\t\t count " << ml.count << "\n";
3443
3444 p += sizeof(struct method_list64_t);
3445 offset += sizeof(struct method_list64_t);
3446 for (i = 0; i < ml.count; i++) {
3447 r = get_pointer_64(p, offset, left, S, info);
3448 if (r == nullptr)
3449 return;
3450 memset(&m, '\0', sizeof(struct method64_t));
3451 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003452 memcpy(&m, r, left);
3453 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003454 } else
3455 memcpy(&m, r, sizeof(struct method64_t));
3456 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3457 swapStruct(m);
3458
3459 outs() << indent << "\t\t name ";
3460 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3461 info, n_value, m.name);
3462 if (n_value != 0) {
3463 if (info->verbose && sym_name != nullptr)
3464 outs() << sym_name;
3465 else
3466 outs() << format("0x%" PRIx64, n_value);
3467 if (m.name != 0)
3468 outs() << " + " << format("0x%" PRIx64, m.name);
3469 } else
3470 outs() << format("0x%" PRIx64, m.name);
3471 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3472 if (name != nullptr)
3473 outs() << format(" %.*s", left, name);
3474 outs() << "\n";
3475
3476 outs() << indent << "\t\t types ";
3477 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3478 info, n_value, m.types);
3479 if (n_value != 0) {
3480 if (info->verbose && sym_name != nullptr)
3481 outs() << sym_name;
3482 else
3483 outs() << format("0x%" PRIx64, n_value);
3484 if (m.types != 0)
3485 outs() << " + " << format("0x%" PRIx64, m.types);
3486 } else
3487 outs() << format("0x%" PRIx64, m.types);
3488 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3489 if (name != nullptr)
3490 outs() << format(" %.*s", left, name);
3491 outs() << "\n";
3492
3493 outs() << indent << "\t\t imp ";
3494 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3495 n_value, m.imp);
3496 if (info->verbose && name == nullptr) {
3497 if (n_value != 0) {
3498 outs() << format("0x%" PRIx64, n_value) << " ";
3499 if (m.imp != 0)
3500 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3501 } else
3502 outs() << format("0x%" PRIx64, m.imp) << " ";
3503 }
3504 if (name != nullptr)
3505 outs() << name;
3506 outs() << "\n";
3507
3508 p += sizeof(struct method64_t);
3509 offset += sizeof(struct method64_t);
3510 }
3511}
3512
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003513static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3514 const char *indent) {
3515 struct method_list32_t ml;
3516 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003517 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003518 uint32_t offset, xoffset, left, i;
3519 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003520
3521 r = get_pointer_32(p, offset, left, S, info);
3522 if (r == nullptr)
3523 return;
3524 memset(&ml, '\0', sizeof(struct method_list32_t));
3525 if (left < sizeof(struct method_list32_t)) {
3526 memcpy(&ml, r, left);
3527 outs() << " (method_list_t entends past the end of the section)\n";
3528 } else
3529 memcpy(&ml, r, sizeof(struct method_list32_t));
3530 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3531 swapStruct(ml);
3532 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3533 outs() << indent << "\t\t count " << ml.count << "\n";
3534
3535 p += sizeof(struct method_list32_t);
3536 offset += sizeof(struct method_list32_t);
3537 for (i = 0; i < ml.count; i++) {
3538 r = get_pointer_32(p, offset, left, S, info);
3539 if (r == nullptr)
3540 return;
3541 memset(&m, '\0', sizeof(struct method32_t));
3542 if (left < sizeof(struct method32_t)) {
3543 memcpy(&ml, r, left);
3544 outs() << indent << " (method_t entends past the end of the section)\n";
3545 } else
3546 memcpy(&m, r, sizeof(struct method32_t));
3547 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3548 swapStruct(m);
3549
3550 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3551 name = get_pointer_32(m.name, xoffset, left, xS, info);
3552 if (name != nullptr)
3553 outs() << format(" %.*s", left, name);
3554 outs() << "\n";
3555
3556 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3557 name = get_pointer_32(m.types, xoffset, left, xS, info);
3558 if (name != nullptr)
3559 outs() << format(" %.*s", left, name);
3560 outs() << "\n";
3561
3562 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3563 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3564 m.imp);
3565 if (name != nullptr)
3566 outs() << " " << name;
3567 outs() << "\n";
3568
3569 p += sizeof(struct method32_t);
3570 offset += sizeof(struct method32_t);
3571 }
3572}
3573
Kevin Enderby846c0002015-04-16 17:19:59 +00003574static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3575 uint32_t offset, left, xleft;
3576 SectionRef S;
3577 struct objc_method_list_t method_list;
3578 struct objc_method_t method;
3579 const char *r, *methods, *name, *SymbolName;
3580 int32_t i;
3581
3582 r = get_pointer_32(p, offset, left, S, info, true);
3583 if (r == nullptr)
3584 return true;
3585
3586 outs() << "\n";
3587 if (left > sizeof(struct objc_method_list_t)) {
3588 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3589 } else {
3590 outs() << "\t\t objc_method_list extends past end of the section\n";
3591 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3592 memcpy(&method_list, r, left);
3593 }
3594 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3595 swapStruct(method_list);
3596
3597 outs() << "\t\t obsolete "
3598 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3599 outs() << "\t\t method_count " << method_list.method_count << "\n";
3600
3601 methods = r + sizeof(struct objc_method_list_t);
3602 for (i = 0; i < method_list.method_count; i++) {
3603 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3604 outs() << "\t\t remaining method's extend past the of the section\n";
3605 break;
3606 }
3607 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3608 sizeof(struct objc_method_t));
3609 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3610 swapStruct(method);
3611
3612 outs() << "\t\t method_name "
3613 << format("0x%08" PRIx32, method.method_name);
3614 if (info->verbose) {
3615 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3616 if (name != nullptr)
3617 outs() << format(" %.*s", xleft, name);
3618 else
3619 outs() << " (not in an __OBJC section)";
3620 }
3621 outs() << "\n";
3622
3623 outs() << "\t\t method_types "
3624 << format("0x%08" PRIx32, method.method_types);
3625 if (info->verbose) {
3626 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3627 if (name != nullptr)
3628 outs() << format(" %.*s", xleft, name);
3629 else
3630 outs() << " (not in an __OBJC section)";
3631 }
3632 outs() << "\n";
3633
3634 outs() << "\t\t method_imp "
3635 << format("0x%08" PRIx32, method.method_imp) << " ";
3636 if (info->verbose) {
3637 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3638 if (SymbolName != nullptr)
3639 outs() << SymbolName;
3640 }
3641 outs() << "\n";
3642 }
3643 return false;
3644}
3645
Kevin Enderby0fc11822015-04-01 20:57:01 +00003646static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3647 struct protocol_list64_t pl;
3648 uint64_t q, n_value;
3649 struct protocol64_t pc;
3650 const char *r;
3651 uint32_t offset, xoffset, left, i;
3652 SectionRef S, xS;
3653 const char *name, *sym_name;
3654
3655 r = get_pointer_64(p, offset, left, S, info);
3656 if (r == nullptr)
3657 return;
3658 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3659 if (left < sizeof(struct protocol_list64_t)) {
3660 memcpy(&pl, r, left);
3661 outs() << " (protocol_list_t entends past the end of the section)\n";
3662 } else
3663 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3664 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3665 swapStruct(pl);
3666 outs() << " count " << pl.count << "\n";
3667
3668 p += sizeof(struct protocol_list64_t);
3669 offset += sizeof(struct protocol_list64_t);
3670 for (i = 0; i < pl.count; i++) {
3671 r = get_pointer_64(p, offset, left, S, info);
3672 if (r == nullptr)
3673 return;
3674 q = 0;
3675 if (left < sizeof(uint64_t)) {
3676 memcpy(&q, r, left);
3677 outs() << " (protocol_t * entends past the end of the section)\n";
3678 } else
3679 memcpy(&q, r, sizeof(uint64_t));
3680 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3681 sys::swapByteOrder(q);
3682
3683 outs() << "\t\t list[" << i << "] ";
3684 sym_name = get_symbol_64(offset, S, info, n_value, q);
3685 if (n_value != 0) {
3686 if (info->verbose && sym_name != nullptr)
3687 outs() << sym_name;
3688 else
3689 outs() << format("0x%" PRIx64, n_value);
3690 if (q != 0)
3691 outs() << " + " << format("0x%" PRIx64, q);
3692 } else
3693 outs() << format("0x%" PRIx64, q);
3694 outs() << " (struct protocol_t *)\n";
3695
3696 r = get_pointer_64(q + n_value, offset, left, S, info);
3697 if (r == nullptr)
3698 return;
3699 memset(&pc, '\0', sizeof(struct protocol64_t));
3700 if (left < sizeof(struct protocol64_t)) {
3701 memcpy(&pc, r, left);
3702 outs() << " (protocol_t entends past the end of the section)\n";
3703 } else
3704 memcpy(&pc, r, sizeof(struct protocol64_t));
3705 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3706 swapStruct(pc);
3707
3708 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3709
3710 outs() << "\t\t\t name ";
3711 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3712 info, n_value, pc.name);
3713 if (n_value != 0) {
3714 if (info->verbose && sym_name != nullptr)
3715 outs() << sym_name;
3716 else
3717 outs() << format("0x%" PRIx64, n_value);
3718 if (pc.name != 0)
3719 outs() << " + " << format("0x%" PRIx64, pc.name);
3720 } else
3721 outs() << format("0x%" PRIx64, pc.name);
3722 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3723 if (name != nullptr)
3724 outs() << format(" %.*s", left, name);
3725 outs() << "\n";
3726
3727 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3728
3729 outs() << "\t\t instanceMethods ";
3730 sym_name =
3731 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3732 S, info, n_value, pc.instanceMethods);
3733 if (n_value != 0) {
3734 if (info->verbose && sym_name != nullptr)
3735 outs() << sym_name;
3736 else
3737 outs() << format("0x%" PRIx64, n_value);
3738 if (pc.instanceMethods != 0)
3739 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3740 } else
3741 outs() << format("0x%" PRIx64, pc.instanceMethods);
3742 outs() << " (struct method_list_t *)\n";
3743 if (pc.instanceMethods + n_value != 0)
3744 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3745
3746 outs() << "\t\t classMethods ";
3747 sym_name =
3748 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3749 info, n_value, pc.classMethods);
3750 if (n_value != 0) {
3751 if (info->verbose && sym_name != nullptr)
3752 outs() << sym_name;
3753 else
3754 outs() << format("0x%" PRIx64, n_value);
3755 if (pc.classMethods != 0)
3756 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3757 } else
3758 outs() << format("0x%" PRIx64, pc.classMethods);
3759 outs() << " (struct method_list_t *)\n";
3760 if (pc.classMethods + n_value != 0)
3761 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3762
3763 outs() << "\t optionalInstanceMethods "
3764 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3765 outs() << "\t optionalClassMethods "
3766 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3767 outs() << "\t instanceProperties "
3768 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3769
3770 p += sizeof(uint64_t);
3771 offset += sizeof(uint64_t);
3772 }
3773}
3774
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003775static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3776 struct protocol_list32_t pl;
3777 uint32_t q;
3778 struct protocol32_t pc;
3779 const char *r;
3780 uint32_t offset, xoffset, left, i;
3781 SectionRef S, xS;
3782 const char *name;
3783
3784 r = get_pointer_32(p, offset, left, S, info);
3785 if (r == nullptr)
3786 return;
3787 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3788 if (left < sizeof(struct protocol_list32_t)) {
3789 memcpy(&pl, r, left);
3790 outs() << " (protocol_list_t entends past the end of the section)\n";
3791 } else
3792 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3793 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3794 swapStruct(pl);
3795 outs() << " count " << pl.count << "\n";
3796
3797 p += sizeof(struct protocol_list32_t);
3798 offset += sizeof(struct protocol_list32_t);
3799 for (i = 0; i < pl.count; i++) {
3800 r = get_pointer_32(p, offset, left, S, info);
3801 if (r == nullptr)
3802 return;
3803 q = 0;
3804 if (left < sizeof(uint32_t)) {
3805 memcpy(&q, r, left);
3806 outs() << " (protocol_t * entends past the end of the section)\n";
3807 } else
3808 memcpy(&q, r, sizeof(uint32_t));
3809 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3810 sys::swapByteOrder(q);
3811 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3812 << " (struct protocol_t *)\n";
3813 r = get_pointer_32(q, offset, left, S, info);
3814 if (r == nullptr)
3815 return;
3816 memset(&pc, '\0', sizeof(struct protocol32_t));
3817 if (left < sizeof(struct protocol32_t)) {
3818 memcpy(&pc, r, left);
3819 outs() << " (protocol_t entends past the end of the section)\n";
3820 } else
3821 memcpy(&pc, r, sizeof(struct protocol32_t));
3822 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3823 swapStruct(pc);
3824 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3825 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3826 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3827 if (name != nullptr)
3828 outs() << format(" %.*s", left, name);
3829 outs() << "\n";
3830 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3831 outs() << "\t\t instanceMethods "
3832 << format("0x%" PRIx32, pc.instanceMethods)
3833 << " (struct method_list_t *)\n";
3834 if (pc.instanceMethods != 0)
3835 print_method_list32_t(pc.instanceMethods, info, "\t");
3836 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3837 << " (struct method_list_t *)\n";
3838 if (pc.classMethods != 0)
3839 print_method_list32_t(pc.classMethods, info, "\t");
3840 outs() << "\t optionalInstanceMethods "
3841 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3842 outs() << "\t optionalClassMethods "
3843 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3844 outs() << "\t instanceProperties "
3845 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3846 p += sizeof(uint32_t);
3847 offset += sizeof(uint32_t);
3848 }
3849}
3850
Kevin Enderby846c0002015-04-16 17:19:59 +00003851static void print_indent(uint32_t indent) {
3852 for (uint32_t i = 0; i < indent;) {
3853 if (indent - i >= 8) {
3854 outs() << "\t";
3855 i += 8;
3856 } else {
3857 for (uint32_t j = i; j < indent; j++)
3858 outs() << " ";
3859 return;
3860 }
3861 }
3862}
3863
3864static bool print_method_description_list(uint32_t p, uint32_t indent,
3865 struct DisassembleInfo *info) {
3866 uint32_t offset, left, xleft;
3867 SectionRef S;
3868 struct objc_method_description_list_t mdl;
3869 struct objc_method_description_t md;
3870 const char *r, *list, *name;
3871 int32_t i;
3872
3873 r = get_pointer_32(p, offset, left, S, info, true);
3874 if (r == nullptr)
3875 return true;
3876
3877 outs() << "\n";
3878 if (left > sizeof(struct objc_method_description_list_t)) {
3879 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3880 } else {
3881 print_indent(indent);
3882 outs() << " objc_method_description_list extends past end of the section\n";
3883 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3884 memcpy(&mdl, r, left);
3885 }
3886 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3887 swapStruct(mdl);
3888
3889 print_indent(indent);
3890 outs() << " count " << mdl.count << "\n";
3891
3892 list = r + sizeof(struct objc_method_description_list_t);
3893 for (i = 0; i < mdl.count; i++) {
3894 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3895 print_indent(indent);
3896 outs() << " remaining list entries extend past the of the section\n";
3897 break;
3898 }
3899 print_indent(indent);
3900 outs() << " list[" << i << "]\n";
3901 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3902 sizeof(struct objc_method_description_t));
3903 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3904 swapStruct(md);
3905
3906 print_indent(indent);
3907 outs() << " name " << format("0x%08" PRIx32, md.name);
3908 if (info->verbose) {
3909 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3910 if (name != nullptr)
3911 outs() << format(" %.*s", xleft, name);
3912 else
3913 outs() << " (not in an __OBJC section)";
3914 }
3915 outs() << "\n";
3916
3917 print_indent(indent);
3918 outs() << " types " << format("0x%08" PRIx32, md.types);
3919 if (info->verbose) {
3920 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3921 if (name != nullptr)
3922 outs() << format(" %.*s", xleft, name);
3923 else
3924 outs() << " (not in an __OBJC section)";
3925 }
3926 outs() << "\n";
3927 }
3928 return false;
3929}
3930
3931static bool print_protocol_list(uint32_t p, uint32_t indent,
3932 struct DisassembleInfo *info);
3933
3934static bool print_protocol(uint32_t p, uint32_t indent,
3935 struct DisassembleInfo *info) {
3936 uint32_t offset, left;
3937 SectionRef S;
3938 struct objc_protocol_t protocol;
3939 const char *r, *name;
3940
3941 r = get_pointer_32(p, offset, left, S, info, true);
3942 if (r == nullptr)
3943 return true;
3944
3945 outs() << "\n";
3946 if (left >= sizeof(struct objc_protocol_t)) {
3947 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3948 } else {
3949 print_indent(indent);
3950 outs() << " Protocol extends past end of the section\n";
3951 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3952 memcpy(&protocol, r, left);
3953 }
3954 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3955 swapStruct(protocol);
3956
3957 print_indent(indent);
3958 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3959 << "\n";
3960
3961 print_indent(indent);
3962 outs() << " protocol_name "
3963 << format("0x%08" PRIx32, protocol.protocol_name);
3964 if (info->verbose) {
3965 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3966 if (name != nullptr)
3967 outs() << format(" %.*s", left, name);
3968 else
3969 outs() << " (not in an __OBJC section)";
3970 }
3971 outs() << "\n";
3972
3973 print_indent(indent);
3974 outs() << " protocol_list "
3975 << format("0x%08" PRIx32, protocol.protocol_list);
3976 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3977 outs() << " (not in an __OBJC section)\n";
3978
3979 print_indent(indent);
3980 outs() << " instance_methods "
3981 << format("0x%08" PRIx32, protocol.instance_methods);
3982 if (print_method_description_list(protocol.instance_methods, indent, info))
3983 outs() << " (not in an __OBJC section)\n";
3984
3985 print_indent(indent);
3986 outs() << " class_methods "
3987 << format("0x%08" PRIx32, protocol.class_methods);
3988 if (print_method_description_list(protocol.class_methods, indent, info))
3989 outs() << " (not in an __OBJC section)\n";
3990
3991 return false;
3992}
3993
3994static bool print_protocol_list(uint32_t p, uint32_t indent,
3995 struct DisassembleInfo *info) {
3996 uint32_t offset, left, l;
3997 SectionRef S;
3998 struct objc_protocol_list_t protocol_list;
3999 const char *r, *list;
4000 int32_t i;
4001
4002 r = get_pointer_32(p, offset, left, S, info, true);
4003 if (r == nullptr)
4004 return true;
4005
4006 outs() << "\n";
4007 if (left > sizeof(struct objc_protocol_list_t)) {
4008 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4009 } else {
4010 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4011 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4012 memcpy(&protocol_list, r, left);
4013 }
4014 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4015 swapStruct(protocol_list);
4016
4017 print_indent(indent);
4018 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4019 << "\n";
4020 print_indent(indent);
4021 outs() << " count " << protocol_list.count << "\n";
4022
4023 list = r + sizeof(struct objc_protocol_list_t);
4024 for (i = 0; i < protocol_list.count; i++) {
4025 if ((i + 1) * sizeof(uint32_t) > left) {
4026 outs() << "\t\t remaining list entries extend past the of the section\n";
4027 break;
4028 }
4029 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4030 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4031 sys::swapByteOrder(l);
4032
4033 print_indent(indent);
4034 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4035 if (print_protocol(l, indent, info))
4036 outs() << "(not in an __OBJC section)\n";
4037 }
4038 return false;
4039}
4040
Kevin Enderby0fc11822015-04-01 20:57:01 +00004041static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4042 struct ivar_list64_t il;
4043 struct ivar64_t i;
4044 const char *r;
4045 uint32_t offset, xoffset, left, j;
4046 SectionRef S, xS;
4047 const char *name, *sym_name, *ivar_offset_p;
4048 uint64_t ivar_offset, n_value;
4049
4050 r = get_pointer_64(p, offset, left, S, info);
4051 if (r == nullptr)
4052 return;
4053 memset(&il, '\0', sizeof(struct ivar_list64_t));
4054 if (left < sizeof(struct ivar_list64_t)) {
4055 memcpy(&il, r, left);
4056 outs() << " (ivar_list_t entends past the end of the section)\n";
4057 } else
4058 memcpy(&il, r, sizeof(struct ivar_list64_t));
4059 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4060 swapStruct(il);
4061 outs() << " entsize " << il.entsize << "\n";
4062 outs() << " count " << il.count << "\n";
4063
4064 p += sizeof(struct ivar_list64_t);
4065 offset += sizeof(struct ivar_list64_t);
4066 for (j = 0; j < il.count; j++) {
4067 r = get_pointer_64(p, offset, left, S, info);
4068 if (r == nullptr)
4069 return;
4070 memset(&i, '\0', sizeof(struct ivar64_t));
4071 if (left < sizeof(struct ivar64_t)) {
4072 memcpy(&i, r, left);
4073 outs() << " (ivar_t entends past the end of the section)\n";
4074 } else
4075 memcpy(&i, r, sizeof(struct ivar64_t));
4076 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4077 swapStruct(i);
4078
4079 outs() << "\t\t\t offset ";
4080 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4081 info, n_value, i.offset);
4082 if (n_value != 0) {
4083 if (info->verbose && sym_name != nullptr)
4084 outs() << sym_name;
4085 else
4086 outs() << format("0x%" PRIx64, n_value);
4087 if (i.offset != 0)
4088 outs() << " + " << format("0x%" PRIx64, i.offset);
4089 } else
4090 outs() << format("0x%" PRIx64, i.offset);
4091 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4092 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4093 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4094 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4095 sys::swapByteOrder(ivar_offset);
4096 outs() << " " << ivar_offset << "\n";
4097 } else
4098 outs() << "\n";
4099
4100 outs() << "\t\t\t name ";
4101 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4102 n_value, i.name);
4103 if (n_value != 0) {
4104 if (info->verbose && sym_name != nullptr)
4105 outs() << sym_name;
4106 else
4107 outs() << format("0x%" PRIx64, n_value);
4108 if (i.name != 0)
4109 outs() << " + " << format("0x%" PRIx64, i.name);
4110 } else
4111 outs() << format("0x%" PRIx64, i.name);
4112 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4113 if (name != nullptr)
4114 outs() << format(" %.*s", left, name);
4115 outs() << "\n";
4116
4117 outs() << "\t\t\t type ";
4118 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4119 n_value, i.name);
4120 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4121 if (n_value != 0) {
4122 if (info->verbose && sym_name != nullptr)
4123 outs() << sym_name;
4124 else
4125 outs() << format("0x%" PRIx64, n_value);
4126 if (i.type != 0)
4127 outs() << " + " << format("0x%" PRIx64, i.type);
4128 } else
4129 outs() << format("0x%" PRIx64, i.type);
4130 if (name != nullptr)
4131 outs() << format(" %.*s", left, name);
4132 outs() << "\n";
4133
4134 outs() << "\t\t\talignment " << i.alignment << "\n";
4135 outs() << "\t\t\t size " << i.size << "\n";
4136
4137 p += sizeof(struct ivar64_t);
4138 offset += sizeof(struct ivar64_t);
4139 }
4140}
4141
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004142static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4143 struct ivar_list32_t il;
4144 struct ivar32_t i;
4145 const char *r;
4146 uint32_t offset, xoffset, left, j;
4147 SectionRef S, xS;
4148 const char *name, *ivar_offset_p;
4149 uint32_t ivar_offset;
4150
4151 r = get_pointer_32(p, offset, left, S, info);
4152 if (r == nullptr)
4153 return;
4154 memset(&il, '\0', sizeof(struct ivar_list32_t));
4155 if (left < sizeof(struct ivar_list32_t)) {
4156 memcpy(&il, r, left);
4157 outs() << " (ivar_list_t entends past the end of the section)\n";
4158 } else
4159 memcpy(&il, r, sizeof(struct ivar_list32_t));
4160 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4161 swapStruct(il);
4162 outs() << " entsize " << il.entsize << "\n";
4163 outs() << " count " << il.count << "\n";
4164
4165 p += sizeof(struct ivar_list32_t);
4166 offset += sizeof(struct ivar_list32_t);
4167 for (j = 0; j < il.count; j++) {
4168 r = get_pointer_32(p, offset, left, S, info);
4169 if (r == nullptr)
4170 return;
4171 memset(&i, '\0', sizeof(struct ivar32_t));
4172 if (left < sizeof(struct ivar32_t)) {
4173 memcpy(&i, r, left);
4174 outs() << " (ivar_t entends past the end of the section)\n";
4175 } else
4176 memcpy(&i, r, sizeof(struct ivar32_t));
4177 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4178 swapStruct(i);
4179
4180 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4181 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4182 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4183 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4184 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4185 sys::swapByteOrder(ivar_offset);
4186 outs() << " " << ivar_offset << "\n";
4187 } else
4188 outs() << "\n";
4189
4190 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4191 name = get_pointer_32(i.name, xoffset, left, xS, info);
4192 if (name != nullptr)
4193 outs() << format(" %.*s", left, name);
4194 outs() << "\n";
4195
4196 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4197 name = get_pointer_32(i.type, xoffset, left, xS, info);
4198 if (name != nullptr)
4199 outs() << format(" %.*s", left, name);
4200 outs() << "\n";
4201
4202 outs() << "\t\t\talignment " << i.alignment << "\n";
4203 outs() << "\t\t\t size " << i.size << "\n";
4204
4205 p += sizeof(struct ivar32_t);
4206 offset += sizeof(struct ivar32_t);
4207 }
4208}
4209
Kevin Enderby0fc11822015-04-01 20:57:01 +00004210static void print_objc_property_list64(uint64_t p,
4211 struct DisassembleInfo *info) {
4212 struct objc_property_list64 opl;
4213 struct objc_property64 op;
4214 const char *r;
4215 uint32_t offset, xoffset, left, j;
4216 SectionRef S, xS;
4217 const char *name, *sym_name;
4218 uint64_t n_value;
4219
4220 r = get_pointer_64(p, offset, left, S, info);
4221 if (r == nullptr)
4222 return;
4223 memset(&opl, '\0', sizeof(struct objc_property_list64));
4224 if (left < sizeof(struct objc_property_list64)) {
4225 memcpy(&opl, r, left);
4226 outs() << " (objc_property_list entends past the end of the section)\n";
4227 } else
4228 memcpy(&opl, r, sizeof(struct objc_property_list64));
4229 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4230 swapStruct(opl);
4231 outs() << " entsize " << opl.entsize << "\n";
4232 outs() << " count " << opl.count << "\n";
4233
4234 p += sizeof(struct objc_property_list64);
4235 offset += sizeof(struct objc_property_list64);
4236 for (j = 0; j < opl.count; j++) {
4237 r = get_pointer_64(p, offset, left, S, info);
4238 if (r == nullptr)
4239 return;
4240 memset(&op, '\0', sizeof(struct objc_property64));
4241 if (left < sizeof(struct objc_property64)) {
4242 memcpy(&op, r, left);
4243 outs() << " (objc_property entends past the end of the section)\n";
4244 } else
4245 memcpy(&op, r, sizeof(struct objc_property64));
4246 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4247 swapStruct(op);
4248
4249 outs() << "\t\t\t name ";
4250 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4251 info, n_value, op.name);
4252 if (n_value != 0) {
4253 if (info->verbose && sym_name != nullptr)
4254 outs() << sym_name;
4255 else
4256 outs() << format("0x%" PRIx64, n_value);
4257 if (op.name != 0)
4258 outs() << " + " << format("0x%" PRIx64, op.name);
4259 } else
4260 outs() << format("0x%" PRIx64, op.name);
4261 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4262 if (name != nullptr)
4263 outs() << format(" %.*s", left, name);
4264 outs() << "\n";
4265
4266 outs() << "\t\t\tattributes ";
4267 sym_name =
4268 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4269 info, n_value, op.attributes);
4270 if (n_value != 0) {
4271 if (info->verbose && sym_name != nullptr)
4272 outs() << sym_name;
4273 else
4274 outs() << format("0x%" PRIx64, n_value);
4275 if (op.attributes != 0)
4276 outs() << " + " << format("0x%" PRIx64, op.attributes);
4277 } else
4278 outs() << format("0x%" PRIx64, op.attributes);
4279 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4280 if (name != nullptr)
4281 outs() << format(" %.*s", left, name);
4282 outs() << "\n";
4283
4284 p += sizeof(struct objc_property64);
4285 offset += sizeof(struct objc_property64);
4286 }
4287}
4288
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004289static void print_objc_property_list32(uint32_t p,
4290 struct DisassembleInfo *info) {
4291 struct objc_property_list32 opl;
4292 struct objc_property32 op;
4293 const char *r;
4294 uint32_t offset, xoffset, left, j;
4295 SectionRef S, xS;
4296 const char *name;
4297
4298 r = get_pointer_32(p, offset, left, S, info);
4299 if (r == nullptr)
4300 return;
4301 memset(&opl, '\0', sizeof(struct objc_property_list32));
4302 if (left < sizeof(struct objc_property_list32)) {
4303 memcpy(&opl, r, left);
4304 outs() << " (objc_property_list entends past the end of the section)\n";
4305 } else
4306 memcpy(&opl, r, sizeof(struct objc_property_list32));
4307 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4308 swapStruct(opl);
4309 outs() << " entsize " << opl.entsize << "\n";
4310 outs() << " count " << opl.count << "\n";
4311
4312 p += sizeof(struct objc_property_list32);
4313 offset += sizeof(struct objc_property_list32);
4314 for (j = 0; j < opl.count; j++) {
4315 r = get_pointer_32(p, offset, left, S, info);
4316 if (r == nullptr)
4317 return;
4318 memset(&op, '\0', sizeof(struct objc_property32));
4319 if (left < sizeof(struct objc_property32)) {
4320 memcpy(&op, r, left);
4321 outs() << " (objc_property entends past the end of the section)\n";
4322 } else
4323 memcpy(&op, r, sizeof(struct objc_property32));
4324 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4325 swapStruct(op);
4326
4327 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4328 name = get_pointer_32(op.name, xoffset, left, xS, info);
4329 if (name != nullptr)
4330 outs() << format(" %.*s", left, name);
4331 outs() << "\n";
4332
4333 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4334 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4335 if (name != nullptr)
4336 outs() << format(" %.*s", left, name);
4337 outs() << "\n";
4338
4339 p += sizeof(struct objc_property32);
4340 offset += sizeof(struct objc_property32);
4341 }
4342}
4343
Richard Smith81ff44d2015-10-09 22:09:56 +00004344static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004345 bool &is_meta_class) {
4346 struct class_ro64_t cro;
4347 const char *r;
4348 uint32_t offset, xoffset, left;
4349 SectionRef S, xS;
4350 const char *name, *sym_name;
4351 uint64_t n_value;
4352
4353 r = get_pointer_64(p, offset, left, S, info);
4354 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004355 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004356 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004357 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4358 swapStruct(cro);
4359 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4360 if (cro.flags & RO_META)
4361 outs() << " RO_META";
4362 if (cro.flags & RO_ROOT)
4363 outs() << " RO_ROOT";
4364 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4365 outs() << " RO_HAS_CXX_STRUCTORS";
4366 outs() << "\n";
4367 outs() << " instanceStart " << cro.instanceStart << "\n";
4368 outs() << " instanceSize " << cro.instanceSize << "\n";
4369 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4370 << "\n";
4371 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4372 << "\n";
4373 print_layout_map64(cro.ivarLayout, info);
4374
4375 outs() << " name ";
4376 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4377 info, n_value, cro.name);
4378 if (n_value != 0) {
4379 if (info->verbose && sym_name != nullptr)
4380 outs() << sym_name;
4381 else
4382 outs() << format("0x%" PRIx64, n_value);
4383 if (cro.name != 0)
4384 outs() << " + " << format("0x%" PRIx64, cro.name);
4385 } else
4386 outs() << format("0x%" PRIx64, cro.name);
4387 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4388 if (name != nullptr)
4389 outs() << format(" %.*s", left, name);
4390 outs() << "\n";
4391
4392 outs() << " baseMethods ";
4393 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4394 S, info, n_value, cro.baseMethods);
4395 if (n_value != 0) {
4396 if (info->verbose && sym_name != nullptr)
4397 outs() << sym_name;
4398 else
4399 outs() << format("0x%" PRIx64, n_value);
4400 if (cro.baseMethods != 0)
4401 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4402 } else
4403 outs() << format("0x%" PRIx64, cro.baseMethods);
4404 outs() << " (struct method_list_t *)\n";
4405 if (cro.baseMethods + n_value != 0)
4406 print_method_list64_t(cro.baseMethods + n_value, info, "");
4407
4408 outs() << " baseProtocols ";
4409 sym_name =
4410 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4411 info, n_value, cro.baseProtocols);
4412 if (n_value != 0) {
4413 if (info->verbose && sym_name != nullptr)
4414 outs() << sym_name;
4415 else
4416 outs() << format("0x%" PRIx64, n_value);
4417 if (cro.baseProtocols != 0)
4418 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4419 } else
4420 outs() << format("0x%" PRIx64, cro.baseProtocols);
4421 outs() << "\n";
4422 if (cro.baseProtocols + n_value != 0)
4423 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4424
4425 outs() << " ivars ";
4426 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004427 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004428 if (n_value != 0) {
4429 if (info->verbose && sym_name != nullptr)
4430 outs() << sym_name;
4431 else
4432 outs() << format("0x%" PRIx64, n_value);
4433 if (cro.ivars != 0)
4434 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4435 } else
4436 outs() << format("0x%" PRIx64, cro.ivars);
4437 outs() << "\n";
4438 if (cro.ivars + n_value != 0)
4439 print_ivar_list64_t(cro.ivars + n_value, info);
4440
4441 outs() << " weakIvarLayout ";
4442 sym_name =
4443 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4444 info, n_value, cro.weakIvarLayout);
4445 if (n_value != 0) {
4446 if (info->verbose && sym_name != nullptr)
4447 outs() << sym_name;
4448 else
4449 outs() << format("0x%" PRIx64, n_value);
4450 if (cro.weakIvarLayout != 0)
4451 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4452 } else
4453 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4454 outs() << "\n";
4455 print_layout_map64(cro.weakIvarLayout + n_value, info);
4456
4457 outs() << " baseProperties ";
4458 sym_name =
4459 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4460 info, n_value, cro.baseProperties);
4461 if (n_value != 0) {
4462 if (info->verbose && sym_name != nullptr)
4463 outs() << sym_name;
4464 else
4465 outs() << format("0x%" PRIx64, n_value);
4466 if (cro.baseProperties != 0)
4467 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4468 } else
4469 outs() << format("0x%" PRIx64, cro.baseProperties);
4470 outs() << "\n";
4471 if (cro.baseProperties + n_value != 0)
4472 print_objc_property_list64(cro.baseProperties + n_value, info);
4473
Rafael Espindolab9091322015-10-24 23:19:10 +00004474 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004475 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004476}
4477
Richard Smith81ff44d2015-10-09 22:09:56 +00004478static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004479 bool &is_meta_class) {
4480 struct class_ro32_t cro;
4481 const char *r;
4482 uint32_t offset, xoffset, left;
4483 SectionRef S, xS;
4484 const char *name;
4485
4486 r = get_pointer_32(p, offset, left, S, info);
4487 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004488 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004489 memset(&cro, '\0', sizeof(struct class_ro32_t));
4490 if (left < sizeof(struct class_ro32_t)) {
4491 memcpy(&cro, r, left);
4492 outs() << " (class_ro_t entends past the end of the section)\n";
4493 } else
4494 memcpy(&cro, r, sizeof(struct class_ro32_t));
4495 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4496 swapStruct(cro);
4497 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4498 if (cro.flags & RO_META)
4499 outs() << " RO_META";
4500 if (cro.flags & RO_ROOT)
4501 outs() << " RO_ROOT";
4502 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4503 outs() << " RO_HAS_CXX_STRUCTORS";
4504 outs() << "\n";
4505 outs() << " instanceStart " << cro.instanceStart << "\n";
4506 outs() << " instanceSize " << cro.instanceSize << "\n";
4507 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4508 << "\n";
4509 print_layout_map32(cro.ivarLayout, info);
4510
4511 outs() << " name " << format("0x%" PRIx32, cro.name);
4512 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4513 if (name != nullptr)
4514 outs() << format(" %.*s", left, name);
4515 outs() << "\n";
4516
4517 outs() << " baseMethods "
4518 << format("0x%" PRIx32, cro.baseMethods)
4519 << " (struct method_list_t *)\n";
4520 if (cro.baseMethods != 0)
4521 print_method_list32_t(cro.baseMethods, info, "");
4522
4523 outs() << " baseProtocols "
4524 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4525 if (cro.baseProtocols != 0)
4526 print_protocol_list32_t(cro.baseProtocols, info);
4527 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4528 << "\n";
4529 if (cro.ivars != 0)
4530 print_ivar_list32_t(cro.ivars, info);
4531 outs() << " weakIvarLayout "
4532 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4533 print_layout_map32(cro.weakIvarLayout, info);
4534 outs() << " baseProperties "
4535 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4536 if (cro.baseProperties != 0)
4537 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004538 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004539 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004540}
4541
Kevin Enderby0fc11822015-04-01 20:57:01 +00004542static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4543 struct class64_t c;
4544 const char *r;
4545 uint32_t offset, left;
4546 SectionRef S;
4547 const char *name;
4548 uint64_t isa_n_value, n_value;
4549
4550 r = get_pointer_64(p, offset, left, S, info);
4551 if (r == nullptr || left < sizeof(struct class64_t))
4552 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004553 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004554 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4555 swapStruct(c);
4556
4557 outs() << " isa " << format("0x%" PRIx64, c.isa);
4558 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4559 isa_n_value, c.isa);
4560 if (name != nullptr)
4561 outs() << " " << name;
4562 outs() << "\n";
4563
4564 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4565 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4566 n_value, c.superclass);
4567 if (name != nullptr)
4568 outs() << " " << name;
4569 outs() << "\n";
4570
4571 outs() << " cache " << format("0x%" PRIx64, c.cache);
4572 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4573 n_value, c.cache);
4574 if (name != nullptr)
4575 outs() << " " << name;
4576 outs() << "\n";
4577
4578 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4579 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4580 n_value, c.vtable);
4581 if (name != nullptr)
4582 outs() << " " << name;
4583 outs() << "\n";
4584
4585 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4586 n_value, c.data);
4587 outs() << " data ";
4588 if (n_value != 0) {
4589 if (info->verbose && name != nullptr)
4590 outs() << name;
4591 else
4592 outs() << format("0x%" PRIx64, n_value);
4593 if (c.data != 0)
4594 outs() << " + " << format("0x%" PRIx64, c.data);
4595 } else
4596 outs() << format("0x%" PRIx64, c.data);
4597 outs() << " (struct class_ro_t *)";
4598
4599 // This is a Swift class if some of the low bits of the pointer are set.
4600 if ((c.data + n_value) & 0x7)
4601 outs() << " Swift class";
4602 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004603 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004604 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4605 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004606
Kevin Enderbyaac75382015-10-08 16:56:35 +00004607 if (!is_meta_class &&
4608 c.isa + isa_n_value != p &&
4609 c.isa + isa_n_value != 0 &&
4610 info->depth < 100) {
4611 info->depth++;
4612 outs() << "Meta Class\n";
4613 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004614 }
4615}
4616
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004617static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4618 struct class32_t c;
4619 const char *r;
4620 uint32_t offset, left;
4621 SectionRef S;
4622 const char *name;
4623
4624 r = get_pointer_32(p, offset, left, S, info);
4625 if (r == nullptr)
4626 return;
4627 memset(&c, '\0', sizeof(struct class32_t));
4628 if (left < sizeof(struct class32_t)) {
4629 memcpy(&c, r, left);
4630 outs() << " (class_t entends past the end of the section)\n";
4631 } else
4632 memcpy(&c, r, sizeof(struct class32_t));
4633 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4634 swapStruct(c);
4635
4636 outs() << " isa " << format("0x%" PRIx32, c.isa);
4637 name =
4638 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4639 if (name != nullptr)
4640 outs() << " " << name;
4641 outs() << "\n";
4642
4643 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4644 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4645 c.superclass);
4646 if (name != nullptr)
4647 outs() << " " << name;
4648 outs() << "\n";
4649
4650 outs() << " cache " << format("0x%" PRIx32, c.cache);
4651 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4652 c.cache);
4653 if (name != nullptr)
4654 outs() << " " << name;
4655 outs() << "\n";
4656
4657 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4658 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4659 c.vtable);
4660 if (name != nullptr)
4661 outs() << " " << name;
4662 outs() << "\n";
4663
4664 name =
4665 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4666 outs() << " data " << format("0x%" PRIx32, c.data)
4667 << " (struct class_ro_t *)";
4668
4669 // This is a Swift class if some of the low bits of the pointer are set.
4670 if (c.data & 0x3)
4671 outs() << " Swift class";
4672 outs() << "\n";
4673 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004674 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4675 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004676
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004677 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004678 outs() << "Meta Class\n";
4679 print_class32_t(c.isa, info);
4680 }
4681}
4682
Kevin Enderby846c0002015-04-16 17:19:59 +00004683static void print_objc_class_t(struct objc_class_t *objc_class,
4684 struct DisassembleInfo *info) {
4685 uint32_t offset, left, xleft;
4686 const char *name, *p, *ivar_list;
4687 SectionRef S;
4688 int32_t i;
4689 struct objc_ivar_list_t objc_ivar_list;
4690 struct objc_ivar_t ivar;
4691
4692 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4693 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4694 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4695 if (name != nullptr)
4696 outs() << format(" %.*s", left, name);
4697 else
4698 outs() << " (not in an __OBJC section)";
4699 }
4700 outs() << "\n";
4701
4702 outs() << "\t super_class "
4703 << format("0x%08" PRIx32, objc_class->super_class);
4704 if (info->verbose) {
4705 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4706 if (name != nullptr)
4707 outs() << format(" %.*s", left, name);
4708 else
4709 outs() << " (not in an __OBJC section)";
4710 }
4711 outs() << "\n";
4712
4713 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4714 if (info->verbose) {
4715 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4716 if (name != nullptr)
4717 outs() << format(" %.*s", left, name);
4718 else
4719 outs() << " (not in an __OBJC section)";
4720 }
4721 outs() << "\n";
4722
4723 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4724 << "\n";
4725
4726 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4727 if (info->verbose) {
4728 if (CLS_GETINFO(objc_class, CLS_CLASS))
4729 outs() << " CLS_CLASS";
4730 else if (CLS_GETINFO(objc_class, CLS_META))
4731 outs() << " CLS_META";
4732 }
4733 outs() << "\n";
4734
4735 outs() << "\t instance_size "
4736 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4737
4738 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4739 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4740 if (p != nullptr) {
4741 if (left > sizeof(struct objc_ivar_list_t)) {
4742 outs() << "\n";
4743 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4744 } else {
4745 outs() << " (entends past the end of the section)\n";
4746 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4747 memcpy(&objc_ivar_list, p, left);
4748 }
4749 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4750 swapStruct(objc_ivar_list);
4751 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4752 ivar_list = p + sizeof(struct objc_ivar_list_t);
4753 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4754 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4755 outs() << "\t\t remaining ivar's extend past the of the section\n";
4756 break;
4757 }
4758 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4759 sizeof(struct objc_ivar_t));
4760 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4761 swapStruct(ivar);
4762
4763 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4764 if (info->verbose) {
4765 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4766 if (name != nullptr)
4767 outs() << format(" %.*s", xleft, name);
4768 else
4769 outs() << " (not in an __OBJC section)";
4770 }
4771 outs() << "\n";
4772
4773 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4774 if (info->verbose) {
4775 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4776 if (name != nullptr)
4777 outs() << format(" %.*s", xleft, name);
4778 else
4779 outs() << " (not in an __OBJC section)";
4780 }
4781 outs() << "\n";
4782
4783 outs() << "\t\t ivar_offset "
4784 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4785 }
4786 } else {
4787 outs() << " (not in an __OBJC section)\n";
4788 }
4789
4790 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4791 if (print_method_list(objc_class->methodLists, info))
4792 outs() << " (not in an __OBJC section)\n";
4793
4794 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4795 << "\n";
4796
4797 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4798 if (print_protocol_list(objc_class->protocols, 16, info))
4799 outs() << " (not in an __OBJC section)\n";
4800}
4801
4802static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4803 struct DisassembleInfo *info) {
4804 uint32_t offset, left;
4805 const char *name;
4806 SectionRef S;
4807
4808 outs() << "\t category name "
4809 << format("0x%08" PRIx32, objc_category->category_name);
4810 if (info->verbose) {
4811 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4812 true);
4813 if (name != nullptr)
4814 outs() << format(" %.*s", left, name);
4815 else
4816 outs() << " (not in an __OBJC section)";
4817 }
4818 outs() << "\n";
4819
4820 outs() << "\t\t class name "
4821 << format("0x%08" PRIx32, objc_category->class_name);
4822 if (info->verbose) {
4823 name =
4824 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4825 if (name != nullptr)
4826 outs() << format(" %.*s", left, name);
4827 else
4828 outs() << " (not in an __OBJC section)";
4829 }
4830 outs() << "\n";
4831
4832 outs() << "\t instance methods "
4833 << format("0x%08" PRIx32, objc_category->instance_methods);
4834 if (print_method_list(objc_category->instance_methods, info))
4835 outs() << " (not in an __OBJC section)\n";
4836
4837 outs() << "\t class methods "
4838 << format("0x%08" PRIx32, objc_category->class_methods);
4839 if (print_method_list(objc_category->class_methods, info))
4840 outs() << " (not in an __OBJC section)\n";
4841}
4842
Kevin Enderby0fc11822015-04-01 20:57:01 +00004843static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4844 struct category64_t c;
4845 const char *r;
4846 uint32_t offset, xoffset, left;
4847 SectionRef S, xS;
4848 const char *name, *sym_name;
4849 uint64_t n_value;
4850
4851 r = get_pointer_64(p, offset, left, S, info);
4852 if (r == nullptr)
4853 return;
4854 memset(&c, '\0', sizeof(struct category64_t));
4855 if (left < sizeof(struct category64_t)) {
4856 memcpy(&c, r, left);
4857 outs() << " (category_t entends past the end of the section)\n";
4858 } else
4859 memcpy(&c, r, sizeof(struct category64_t));
4860 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4861 swapStruct(c);
4862
4863 outs() << " name ";
4864 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4865 info, n_value, c.name);
4866 if (n_value != 0) {
4867 if (info->verbose && sym_name != nullptr)
4868 outs() << sym_name;
4869 else
4870 outs() << format("0x%" PRIx64, n_value);
4871 if (c.name != 0)
4872 outs() << " + " << format("0x%" PRIx64, c.name);
4873 } else
4874 outs() << format("0x%" PRIx64, c.name);
4875 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4876 if (name != nullptr)
4877 outs() << format(" %.*s", left, name);
4878 outs() << "\n";
4879
4880 outs() << " cls ";
4881 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4882 n_value, c.cls);
4883 if (n_value != 0) {
4884 if (info->verbose && sym_name != nullptr)
4885 outs() << sym_name;
4886 else
4887 outs() << format("0x%" PRIx64, n_value);
4888 if (c.cls != 0)
4889 outs() << " + " << format("0x%" PRIx64, c.cls);
4890 } else
4891 outs() << format("0x%" PRIx64, c.cls);
4892 outs() << "\n";
4893 if (c.cls + n_value != 0)
4894 print_class64_t(c.cls + n_value, info);
4895
4896 outs() << " instanceMethods ";
4897 sym_name =
4898 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4899 info, n_value, c.instanceMethods);
4900 if (n_value != 0) {
4901 if (info->verbose && sym_name != nullptr)
4902 outs() << sym_name;
4903 else
4904 outs() << format("0x%" PRIx64, n_value);
4905 if (c.instanceMethods != 0)
4906 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4907 } else
4908 outs() << format("0x%" PRIx64, c.instanceMethods);
4909 outs() << "\n";
4910 if (c.instanceMethods + n_value != 0)
4911 print_method_list64_t(c.instanceMethods + n_value, info, "");
4912
4913 outs() << " classMethods ";
4914 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4915 S, info, n_value, c.classMethods);
4916 if (n_value != 0) {
4917 if (info->verbose && sym_name != nullptr)
4918 outs() << sym_name;
4919 else
4920 outs() << format("0x%" PRIx64, n_value);
4921 if (c.classMethods != 0)
4922 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4923 } else
4924 outs() << format("0x%" PRIx64, c.classMethods);
4925 outs() << "\n";
4926 if (c.classMethods + n_value != 0)
4927 print_method_list64_t(c.classMethods + n_value, info, "");
4928
4929 outs() << " protocols ";
4930 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4931 info, n_value, c.protocols);
4932 if (n_value != 0) {
4933 if (info->verbose && sym_name != nullptr)
4934 outs() << sym_name;
4935 else
4936 outs() << format("0x%" PRIx64, n_value);
4937 if (c.protocols != 0)
4938 outs() << " + " << format("0x%" PRIx64, c.protocols);
4939 } else
4940 outs() << format("0x%" PRIx64, c.protocols);
4941 outs() << "\n";
4942 if (c.protocols + n_value != 0)
4943 print_protocol_list64_t(c.protocols + n_value, info);
4944
4945 outs() << "instanceProperties ";
4946 sym_name =
4947 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4948 S, info, n_value, c.instanceProperties);
4949 if (n_value != 0) {
4950 if (info->verbose && sym_name != nullptr)
4951 outs() << sym_name;
4952 else
4953 outs() << format("0x%" PRIx64, n_value);
4954 if (c.instanceProperties != 0)
4955 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4956 } else
4957 outs() << format("0x%" PRIx64, c.instanceProperties);
4958 outs() << "\n";
4959 if (c.instanceProperties + n_value != 0)
4960 print_objc_property_list64(c.instanceProperties + n_value, info);
4961}
4962
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004963static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4964 struct category32_t c;
4965 const char *r;
4966 uint32_t offset, left;
4967 SectionRef S, xS;
4968 const char *name;
4969
4970 r = get_pointer_32(p, offset, left, S, info);
4971 if (r == nullptr)
4972 return;
4973 memset(&c, '\0', sizeof(struct category32_t));
4974 if (left < sizeof(struct category32_t)) {
4975 memcpy(&c, r, left);
4976 outs() << " (category_t entends past the end of the section)\n";
4977 } else
4978 memcpy(&c, r, sizeof(struct category32_t));
4979 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4980 swapStruct(c);
4981
4982 outs() << " name " << format("0x%" PRIx32, c.name);
4983 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4984 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004985 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004986 outs() << " " << name;
4987 outs() << "\n";
4988
4989 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4990 if (c.cls != 0)
4991 print_class32_t(c.cls, info);
4992 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4993 << "\n";
4994 if (c.instanceMethods != 0)
4995 print_method_list32_t(c.instanceMethods, info, "");
4996 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4997 << "\n";
4998 if (c.classMethods != 0)
4999 print_method_list32_t(c.classMethods, info, "");
5000 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5001 if (c.protocols != 0)
5002 print_protocol_list32_t(c.protocols, info);
5003 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5004 << "\n";
5005 if (c.instanceProperties != 0)
5006 print_objc_property_list32(c.instanceProperties, info);
5007}
5008
Kevin Enderby0fc11822015-04-01 20:57:01 +00005009static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5010 uint32_t i, left, offset, xoffset;
5011 uint64_t p, n_value;
5012 struct message_ref64 mr;
5013 const char *name, *sym_name;
5014 const char *r;
5015 SectionRef xS;
5016
5017 if (S == SectionRef())
5018 return;
5019
5020 StringRef SectName;
5021 S.getName(SectName);
5022 DataRefImpl Ref = S.getRawDataRefImpl();
5023 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5024 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5025 offset = 0;
5026 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5027 p = S.getAddress() + i;
5028 r = get_pointer_64(p, offset, left, S, info);
5029 if (r == nullptr)
5030 return;
5031 memset(&mr, '\0', sizeof(struct message_ref64));
5032 if (left < sizeof(struct message_ref64)) {
5033 memcpy(&mr, r, left);
5034 outs() << " (message_ref entends past the end of the section)\n";
5035 } else
5036 memcpy(&mr, r, sizeof(struct message_ref64));
5037 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5038 swapStruct(mr);
5039
5040 outs() << " imp ";
5041 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5042 n_value, mr.imp);
5043 if (n_value != 0) {
5044 outs() << format("0x%" PRIx64, n_value) << " ";
5045 if (mr.imp != 0)
5046 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5047 } else
5048 outs() << format("0x%" PRIx64, mr.imp) << " ";
5049 if (name != nullptr)
5050 outs() << " " << name;
5051 outs() << "\n";
5052
5053 outs() << " sel ";
5054 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5055 info, n_value, mr.sel);
5056 if (n_value != 0) {
5057 if (info->verbose && sym_name != nullptr)
5058 outs() << sym_name;
5059 else
5060 outs() << format("0x%" PRIx64, n_value);
5061 if (mr.sel != 0)
5062 outs() << " + " << format("0x%" PRIx64, mr.sel);
5063 } else
5064 outs() << format("0x%" PRIx64, mr.sel);
5065 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5066 if (name != nullptr)
5067 outs() << format(" %.*s", left, name);
5068 outs() << "\n";
5069
5070 offset += sizeof(struct message_ref64);
5071 }
5072}
5073
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005074static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5075 uint32_t i, left, offset, xoffset, p;
5076 struct message_ref32 mr;
5077 const char *name, *r;
5078 SectionRef xS;
5079
5080 if (S == SectionRef())
5081 return;
5082
5083 StringRef SectName;
5084 S.getName(SectName);
5085 DataRefImpl Ref = S.getRawDataRefImpl();
5086 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5087 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5088 offset = 0;
5089 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5090 p = S.getAddress() + i;
5091 r = get_pointer_32(p, offset, left, S, info);
5092 if (r == nullptr)
5093 return;
5094 memset(&mr, '\0', sizeof(struct message_ref32));
5095 if (left < sizeof(struct message_ref32)) {
5096 memcpy(&mr, r, left);
5097 outs() << " (message_ref entends past the end of the section)\n";
5098 } else
5099 memcpy(&mr, r, sizeof(struct message_ref32));
5100 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5101 swapStruct(mr);
5102
5103 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5104 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5105 mr.imp);
5106 if (name != nullptr)
5107 outs() << " " << name;
5108 outs() << "\n";
5109
5110 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5111 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5112 if (name != nullptr)
5113 outs() << " " << name;
5114 outs() << "\n";
5115
5116 offset += sizeof(struct message_ref32);
5117 }
5118}
5119
Kevin Enderby0fc11822015-04-01 20:57:01 +00005120static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5121 uint32_t left, offset, swift_version;
5122 uint64_t p;
5123 struct objc_image_info64 o;
5124 const char *r;
5125
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005126 if (S == SectionRef())
5127 return;
5128
Kevin Enderby0fc11822015-04-01 20:57:01 +00005129 StringRef SectName;
5130 S.getName(SectName);
5131 DataRefImpl Ref = S.getRawDataRefImpl();
5132 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5133 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5134 p = S.getAddress();
5135 r = get_pointer_64(p, offset, left, S, info);
5136 if (r == nullptr)
5137 return;
5138 memset(&o, '\0', sizeof(struct objc_image_info64));
5139 if (left < sizeof(struct objc_image_info64)) {
5140 memcpy(&o, r, left);
5141 outs() << " (objc_image_info entends past the end of the section)\n";
5142 } else
5143 memcpy(&o, r, sizeof(struct objc_image_info64));
5144 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5145 swapStruct(o);
5146 outs() << " version " << o.version << "\n";
5147 outs() << " flags " << format("0x%" PRIx32, o.flags);
5148 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5149 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5150 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5151 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5152 swift_version = (o.flags >> 8) & 0xff;
5153 if (swift_version != 0) {
5154 if (swift_version == 1)
5155 outs() << " Swift 1.0";
5156 else if (swift_version == 2)
5157 outs() << " Swift 1.1";
5158 else
5159 outs() << " unknown future Swift version (" << swift_version << ")";
5160 }
5161 outs() << "\n";
5162}
5163
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005164static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5165 uint32_t left, offset, swift_version, p;
5166 struct objc_image_info32 o;
5167 const char *r;
5168
Kevin Enderby19be2512016-04-21 19:49:29 +00005169 if (S == SectionRef())
5170 return;
5171
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005172 StringRef SectName;
5173 S.getName(SectName);
5174 DataRefImpl Ref = S.getRawDataRefImpl();
5175 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5176 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5177 p = S.getAddress();
5178 r = get_pointer_32(p, offset, left, S, info);
5179 if (r == nullptr)
5180 return;
5181 memset(&o, '\0', sizeof(struct objc_image_info32));
5182 if (left < sizeof(struct objc_image_info32)) {
5183 memcpy(&o, r, left);
5184 outs() << " (objc_image_info entends past the end of the section)\n";
5185 } else
5186 memcpy(&o, r, sizeof(struct objc_image_info32));
5187 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5188 swapStruct(o);
5189 outs() << " version " << o.version << "\n";
5190 outs() << " flags " << format("0x%" PRIx32, o.flags);
5191 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5192 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5193 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5194 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5195 swift_version = (o.flags >> 8) & 0xff;
5196 if (swift_version != 0) {
5197 if (swift_version == 1)
5198 outs() << " Swift 1.0";
5199 else if (swift_version == 2)
5200 outs() << " Swift 1.1";
5201 else
5202 outs() << " unknown future Swift version (" << swift_version << ")";
5203 }
5204 outs() << "\n";
5205}
5206
Kevin Enderby846c0002015-04-16 17:19:59 +00005207static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5208 uint32_t left, offset, p;
5209 struct imageInfo_t o;
5210 const char *r;
5211
5212 StringRef SectName;
5213 S.getName(SectName);
5214 DataRefImpl Ref = S.getRawDataRefImpl();
5215 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5216 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5217 p = S.getAddress();
5218 r = get_pointer_32(p, offset, left, S, info);
5219 if (r == nullptr)
5220 return;
5221 memset(&o, '\0', sizeof(struct imageInfo_t));
5222 if (left < sizeof(struct imageInfo_t)) {
5223 memcpy(&o, r, left);
5224 outs() << " (imageInfo entends past the end of the section)\n";
5225 } else
5226 memcpy(&o, r, sizeof(struct imageInfo_t));
5227 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5228 swapStruct(o);
5229 outs() << " version " << o.version << "\n";
5230 outs() << " flags " << format("0x%" PRIx32, o.flags);
5231 if (o.flags & 0x1)
5232 outs() << " F&C";
5233 if (o.flags & 0x2)
5234 outs() << " GC";
5235 if (o.flags & 0x4)
5236 outs() << " GC-only";
5237 else
5238 outs() << " RR";
5239 outs() << "\n";
5240}
5241
Kevin Enderby0fc11822015-04-01 20:57:01 +00005242static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5243 SymbolAddressMap AddrMap;
5244 if (verbose)
5245 CreateSymbolAddressMap(O, &AddrMap);
5246
5247 std::vector<SectionRef> Sections;
5248 for (const SectionRef &Section : O->sections()) {
5249 StringRef SectName;
5250 Section.getName(SectName);
5251 Sections.push_back(Section);
5252 }
5253
5254 struct DisassembleInfo info;
5255 // Set up the block of info used by the Symbolizer call backs.
5256 info.verbose = verbose;
5257 info.O = O;
5258 info.AddrMap = &AddrMap;
5259 info.Sections = &Sections;
5260 info.class_name = nullptr;
5261 info.selector_name = nullptr;
5262 info.method = nullptr;
5263 info.demangled_name = nullptr;
5264 info.bindtable = nullptr;
5265 info.adrp_addr = 0;
5266 info.adrp_inst = 0;
5267
Kevin Enderbyaac75382015-10-08 16:56:35 +00005268 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005269 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5270 if (CL == SectionRef())
5271 CL = get_section(O, "__DATA", "__objc_classlist");
5272 info.S = CL;
5273 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005274
Davide Italiano62507042015-12-11 22:27:59 +00005275 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5276 if (CR == SectionRef())
5277 CR = get_section(O, "__DATA", "__objc_classrefs");
5278 info.S = CR;
5279 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005280
Davide Italiano62507042015-12-11 22:27:59 +00005281 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5282 if (SR == SectionRef())
5283 SR = get_section(O, "__DATA", "__objc_superrefs");
5284 info.S = SR;
5285 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005286
Davide Italiano62507042015-12-11 22:27:59 +00005287 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5288 if (CA == SectionRef())
5289 CA = get_section(O, "__DATA", "__objc_catlist");
5290 info.S = CA;
5291 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005292
Davide Italiano62507042015-12-11 22:27:59 +00005293 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5294 if (PL == SectionRef())
5295 PL = get_section(O, "__DATA", "__objc_protolist");
5296 info.S = PL;
5297 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005298
Davide Italiano62507042015-12-11 22:27:59 +00005299 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5300 if (MR == SectionRef())
5301 MR = get_section(O, "__DATA", "__objc_msgrefs");
5302 info.S = MR;
5303 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005304
Davide Italiano62507042015-12-11 22:27:59 +00005305 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5306 if (II == SectionRef())
5307 II = get_section(O, "__DATA", "__objc_imageinfo");
5308 info.S = II;
5309 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005310}
5311
5312static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005313 SymbolAddressMap AddrMap;
5314 if (verbose)
5315 CreateSymbolAddressMap(O, &AddrMap);
5316
5317 std::vector<SectionRef> Sections;
5318 for (const SectionRef &Section : O->sections()) {
5319 StringRef SectName;
5320 Section.getName(SectName);
5321 Sections.push_back(Section);
5322 }
5323
5324 struct DisassembleInfo info;
5325 // Set up the block of info used by the Symbolizer call backs.
5326 info.verbose = verbose;
5327 info.O = O;
5328 info.AddrMap = &AddrMap;
5329 info.Sections = &Sections;
5330 info.class_name = nullptr;
5331 info.selector_name = nullptr;
5332 info.method = nullptr;
5333 info.demangled_name = nullptr;
5334 info.bindtable = nullptr;
5335 info.adrp_addr = 0;
5336 info.adrp_inst = 0;
5337
5338 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5339 if (CL != SectionRef()) {
5340 info.S = CL;
5341 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5342 } else {
5343 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5344 info.S = CL;
5345 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5346 }
5347
5348 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5349 if (CR != SectionRef()) {
5350 info.S = CR;
5351 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5352 } else {
5353 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5354 info.S = CR;
5355 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5356 }
5357
5358 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5359 if (SR != SectionRef()) {
5360 info.S = SR;
5361 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5362 } else {
5363 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5364 info.S = SR;
5365 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5366 }
5367
5368 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5369 if (CA != SectionRef()) {
5370 info.S = CA;
5371 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5372 } else {
5373 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5374 info.S = CA;
5375 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5376 }
5377
5378 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5379 if (PL != SectionRef()) {
5380 info.S = PL;
5381 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5382 } else {
5383 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5384 info.S = PL;
5385 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5386 }
5387
5388 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5389 if (MR != SectionRef()) {
5390 info.S = MR;
5391 print_message_refs32(MR, &info);
5392 } else {
5393 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5394 info.S = MR;
5395 print_message_refs32(MR, &info);
5396 }
5397
5398 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5399 if (II != SectionRef()) {
5400 info.S = II;
5401 print_image_info32(II, &info);
5402 } else {
5403 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5404 info.S = II;
5405 print_image_info32(II, &info);
5406 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005407}
5408
5409static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005410 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5411 const char *r, *name, *defs;
5412 struct objc_module_t module;
5413 SectionRef S, xS;
5414 struct objc_symtab_t symtab;
5415 struct objc_class_t objc_class;
5416 struct objc_category_t objc_category;
5417
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005418 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005419 S = get_section(O, "__OBJC", "__module_info");
5420 if (S == SectionRef())
5421 return false;
5422
5423 SymbolAddressMap AddrMap;
5424 if (verbose)
5425 CreateSymbolAddressMap(O, &AddrMap);
5426
5427 std::vector<SectionRef> Sections;
5428 for (const SectionRef &Section : O->sections()) {
5429 StringRef SectName;
5430 Section.getName(SectName);
5431 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005432 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005433
5434 struct DisassembleInfo info;
5435 // Set up the block of info used by the Symbolizer call backs.
5436 info.verbose = verbose;
5437 info.O = O;
5438 info.AddrMap = &AddrMap;
5439 info.Sections = &Sections;
5440 info.class_name = nullptr;
5441 info.selector_name = nullptr;
5442 info.method = nullptr;
5443 info.demangled_name = nullptr;
5444 info.bindtable = nullptr;
5445 info.adrp_addr = 0;
5446 info.adrp_inst = 0;
5447
5448 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5449 p = S.getAddress() + i;
5450 r = get_pointer_32(p, offset, left, S, &info, true);
5451 if (r == nullptr)
5452 return true;
5453 memset(&module, '\0', sizeof(struct objc_module_t));
5454 if (left < sizeof(struct objc_module_t)) {
5455 memcpy(&module, r, left);
5456 outs() << " (module extends past end of __module_info section)\n";
5457 } else
5458 memcpy(&module, r, sizeof(struct objc_module_t));
5459 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5460 swapStruct(module);
5461
5462 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5463 outs() << " version " << module.version << "\n";
5464 outs() << " size " << module.size << "\n";
5465 outs() << " name ";
5466 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5467 if (name != nullptr)
5468 outs() << format("%.*s", left, name);
5469 else
5470 outs() << format("0x%08" PRIx32, module.name)
5471 << "(not in an __OBJC section)";
5472 outs() << "\n";
5473
5474 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5475 if (module.symtab == 0 || r == nullptr) {
5476 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5477 << " (not in an __OBJC section)\n";
5478 continue;
5479 }
5480 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5481 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5482 defs_left = 0;
5483 defs = nullptr;
5484 if (left < sizeof(struct objc_symtab_t)) {
5485 memcpy(&symtab, r, left);
5486 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5487 } else {
5488 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5489 if (left > sizeof(struct objc_symtab_t)) {
5490 defs_left = left - sizeof(struct objc_symtab_t);
5491 defs = r + sizeof(struct objc_symtab_t);
5492 }
5493 }
5494 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5495 swapStruct(symtab);
5496
5497 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5498 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5499 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5500 if (r == nullptr)
5501 outs() << " (not in an __OBJC section)";
5502 outs() << "\n";
5503 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5504 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5505 if (symtab.cls_def_cnt > 0)
5506 outs() << "\tClass Definitions\n";
5507 for (j = 0; j < symtab.cls_def_cnt; j++) {
5508 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5509 outs() << "\t(remaining class defs entries entends past the end of the "
5510 << "section)\n";
5511 break;
5512 }
5513 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5514 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5515 sys::swapByteOrder(def);
5516
5517 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5518 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5519 if (r != nullptr) {
5520 if (left > sizeof(struct objc_class_t)) {
5521 outs() << "\n";
5522 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5523 } else {
5524 outs() << " (entends past the end of the section)\n";
5525 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5526 memcpy(&objc_class, r, left);
5527 }
5528 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5529 swapStruct(objc_class);
5530 print_objc_class_t(&objc_class, &info);
5531 } else {
5532 outs() << "(not in an __OBJC section)\n";
5533 }
5534
5535 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5536 outs() << "\tMeta Class";
5537 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5538 if (r != nullptr) {
5539 if (left > sizeof(struct objc_class_t)) {
5540 outs() << "\n";
5541 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5542 } else {
5543 outs() << " (entends past the end of the section)\n";
5544 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5545 memcpy(&objc_class, r, left);
5546 }
5547 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5548 swapStruct(objc_class);
5549 print_objc_class_t(&objc_class, &info);
5550 } else {
5551 outs() << "(not in an __OBJC section)\n";
5552 }
5553 }
5554 }
5555 if (symtab.cat_def_cnt > 0)
5556 outs() << "\tCategory Definitions\n";
5557 for (j = 0; j < symtab.cat_def_cnt; j++) {
5558 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5559 outs() << "\t(remaining category defs entries entends past the end of "
5560 << "the section)\n";
5561 break;
5562 }
5563 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5564 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 + symtab.cls_def_cnt << "] "
5570 << format("0x%08" PRIx32, def);
5571 if (r != nullptr) {
5572 if (left > sizeof(struct objc_category_t)) {
5573 outs() << "\n";
5574 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5575 } else {
5576 outs() << " (entends past the end of the section)\n";
5577 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5578 memcpy(&objc_category, r, left);
5579 }
5580 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5581 swapStruct(objc_category);
5582 print_objc_objc_category_t(&objc_category, &info);
5583 } else {
5584 outs() << "(not in an __OBJC section)\n";
5585 }
5586 }
5587 }
5588 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5589 if (II != SectionRef())
5590 print_image_info(II, &info);
5591
5592 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005593}
5594
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005595static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5596 uint32_t size, uint32_t addr) {
5597 SymbolAddressMap AddrMap;
5598 CreateSymbolAddressMap(O, &AddrMap);
5599
5600 std::vector<SectionRef> Sections;
5601 for (const SectionRef &Section : O->sections()) {
5602 StringRef SectName;
5603 Section.getName(SectName);
5604 Sections.push_back(Section);
5605 }
5606
5607 struct DisassembleInfo info;
5608 // Set up the block of info used by the Symbolizer call backs.
5609 info.verbose = true;
5610 info.O = O;
5611 info.AddrMap = &AddrMap;
5612 info.Sections = &Sections;
5613 info.class_name = nullptr;
5614 info.selector_name = nullptr;
5615 info.method = nullptr;
5616 info.demangled_name = nullptr;
5617 info.bindtable = nullptr;
5618 info.adrp_addr = 0;
5619 info.adrp_inst = 0;
5620
5621 const char *p;
5622 struct objc_protocol_t protocol;
5623 uint32_t left, paddr;
5624 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5625 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5626 left = size - (p - sect);
5627 if (left < sizeof(struct objc_protocol_t)) {
5628 outs() << "Protocol extends past end of __protocol section\n";
5629 memcpy(&protocol, p, left);
5630 } else
5631 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5632 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5633 swapStruct(protocol);
5634 paddr = addr + (p - sect);
5635 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5636 if (print_protocol(paddr, 0, &info))
5637 outs() << "(not in an __OBJC section)\n";
5638 }
5639}
5640
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005641#ifdef HAVE_LIBXAR
5642inline void swapStruct(struct xar_header &xar) {
5643 sys::swapByteOrder(xar.magic);
5644 sys::swapByteOrder(xar.size);
5645 sys::swapByteOrder(xar.version);
5646 sys::swapByteOrder(xar.toc_length_compressed);
5647 sys::swapByteOrder(xar.toc_length_uncompressed);
5648 sys::swapByteOrder(xar.cksum_alg);
5649}
5650
5651static void PrintModeVerbose(uint32_t mode) {
5652 switch(mode & S_IFMT){
5653 case S_IFDIR:
5654 outs() << "d";
5655 break;
5656 case S_IFCHR:
5657 outs() << "c";
5658 break;
5659 case S_IFBLK:
5660 outs() << "b";
5661 break;
5662 case S_IFREG:
5663 outs() << "-";
5664 break;
5665 case S_IFLNK:
5666 outs() << "l";
5667 break;
5668 case S_IFSOCK:
5669 outs() << "s";
5670 break;
5671 default:
5672 outs() << "?";
5673 break;
5674 }
5675
5676 /* owner permissions */
5677 if(mode & S_IREAD)
5678 outs() << "r";
5679 else
5680 outs() << "-";
5681 if(mode & S_IWRITE)
5682 outs() << "w";
5683 else
5684 outs() << "-";
5685 if(mode & S_ISUID)
5686 outs() << "s";
5687 else if(mode & S_IEXEC)
5688 outs() << "x";
5689 else
5690 outs() << "-";
5691
5692 /* group permissions */
5693 if(mode & (S_IREAD >> 3))
5694 outs() << "r";
5695 else
5696 outs() << "-";
5697 if(mode & (S_IWRITE >> 3))
5698 outs() << "w";
5699 else
5700 outs() << "-";
5701 if(mode & S_ISGID)
5702 outs() << "s";
5703 else if(mode & (S_IEXEC >> 3))
5704 outs() << "x";
5705 else
5706 outs() << "-";
5707
5708 /* other permissions */
5709 if(mode & (S_IREAD >> 6))
5710 outs() << "r";
5711 else
5712 outs() << "-";
5713 if(mode & (S_IWRITE >> 6))
5714 outs() << "w";
5715 else
5716 outs() << "-";
5717 if(mode & S_ISVTX)
5718 outs() << "t";
5719 else if(mode & (S_IEXEC >> 6))
5720 outs() << "x";
5721 else
5722 outs() << "-";
5723}
5724
5725static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5726 xar_iter_t xi;
5727 xar_file_t xf;
5728 xar_iter_t xp;
5729 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5730 char *endp;
5731 uint32_t mode_value;
5732
5733 xi = xar_iter_new();
5734 if (!xi) {
5735 errs() << "Can't obtain an xar iterator for xar archive "
5736 << XarFilename << "\n";
5737 return;
5738 }
5739
5740 // Go through the xar's files.
5741 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5742 xp = xar_iter_new();
5743 if(!xp){
5744 errs() << "Can't obtain an xar iterator for xar archive "
5745 << XarFilename << "\n";
5746 return;
5747 }
5748 type = nullptr;
5749 mode = nullptr;
5750 user = nullptr;
5751 group = nullptr;
5752 size = nullptr;
5753 mtime = nullptr;
5754 name = nullptr;
5755 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5756 const char *val = nullptr;
5757 xar_prop_get(xf, key, &val);
5758#if 0 // Useful for debugging.
5759 outs() << "key: " << key << " value: " << val << "\n";
5760#endif
5761 if(strcmp(key, "type") == 0)
5762 type = val;
5763 if(strcmp(key, "mode") == 0)
5764 mode = val;
5765 if(strcmp(key, "user") == 0)
5766 user = val;
5767 if(strcmp(key, "group") == 0)
5768 group = val;
5769 if(strcmp(key, "data/size") == 0)
5770 size = val;
5771 if(strcmp(key, "mtime") == 0)
5772 mtime = val;
5773 if(strcmp(key, "name") == 0)
5774 name = val;
5775 }
5776 if(mode != nullptr){
5777 mode_value = strtoul(mode, &endp, 8);
5778 if(*endp != '\0')
5779 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5780 if(strcmp(type, "file") == 0)
5781 mode_value |= S_IFREG;
5782 PrintModeVerbose(mode_value);
5783 outs() << " ";
5784 }
5785 if(user != nullptr)
5786 outs() << format("%10s/", user);
5787 if(group != nullptr)
5788 outs() << format("%-10s ", group);
5789 if(size != nullptr)
5790 outs() << format("%7s ", size);
5791 if(mtime != nullptr){
5792 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5793 outs() << *m;
5794 if(*m == 'T')
5795 m++;
5796 outs() << " ";
5797 for( ; *m != 'Z' && *m != '\0'; m++)
5798 outs() << *m;
5799 outs() << " ";
5800 }
5801 if(name != nullptr)
5802 outs() << name;
5803 outs() << "\n";
5804 }
5805}
5806
5807static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5808 uint32_t size, bool verbose,
5809 bool PrintXarHeader, bool PrintXarFileHeaders,
5810 std::string XarMemberName) {
5811 if(size < sizeof(struct xar_header)) {
5812 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5813 "of struct xar_header)\n";
5814 return;
5815 }
5816 struct xar_header XarHeader;
5817 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5818 if (sys::IsLittleEndianHost)
5819 swapStruct(XarHeader);
5820 if (PrintXarHeader) {
5821 if (!XarMemberName.empty())
5822 outs() << "In xar member " << XarMemberName << ": ";
5823 else
5824 outs() << "For (__LLVM,__bundle) section: ";
5825 outs() << "xar header\n";
5826 if (XarHeader.magic == XAR_HEADER_MAGIC)
5827 outs() << " magic XAR_HEADER_MAGIC\n";
5828 else
5829 outs() << " magic "
5830 << format_hex(XarHeader.magic, 10, true)
5831 << " (not XAR_HEADER_MAGIC)\n";
5832 outs() << " size " << XarHeader.size << "\n";
5833 outs() << " version " << XarHeader.version << "\n";
5834 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5835 << "\n";
5836 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5837 << "\n";
5838 outs() << " cksum_alg ";
5839 switch (XarHeader.cksum_alg) {
5840 case XAR_CKSUM_NONE:
5841 outs() << "XAR_CKSUM_NONE\n";
5842 break;
5843 case XAR_CKSUM_SHA1:
5844 outs() << "XAR_CKSUM_SHA1\n";
5845 break;
5846 case XAR_CKSUM_MD5:
5847 outs() << "XAR_CKSUM_MD5\n";
5848 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005849#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005850 case XAR_CKSUM_SHA256:
5851 outs() << "XAR_CKSUM_SHA256\n";
5852 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005853#endif
5854#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005855 case XAR_CKSUM_SHA512:
5856 outs() << "XAR_CKSUM_SHA512\n";
5857 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005858#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005859 default:
5860 outs() << XarHeader.cksum_alg << "\n";
5861 }
5862 }
5863
5864 SmallString<128> XarFilename;
5865 int FD;
5866 std::error_code XarEC =
5867 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5868 if (XarEC) {
5869 errs() << XarEC.message() << "\n";
5870 return;
5871 }
5872 tool_output_file XarFile(XarFilename, FD);
5873 raw_fd_ostream &XarOut = XarFile.os();
5874 StringRef XarContents(sect, size);
5875 XarOut << XarContents;
5876 XarOut.close();
5877 if (XarOut.has_error())
5878 return;
5879
5880 xar_t xar = xar_open(XarFilename.c_str(), READ);
5881 if (!xar) {
5882 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5883 return;
5884 }
5885
5886 SmallString<128> TocFilename;
5887 std::error_code TocEC =
5888 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5889 if (TocEC) {
5890 errs() << TocEC.message() << "\n";
5891 return;
5892 }
5893 xar_serialize(xar, TocFilename.c_str());
5894
5895 if (PrintXarFileHeaders) {
5896 if (!XarMemberName.empty())
5897 outs() << "In xar member " << XarMemberName << ": ";
5898 else
5899 outs() << "For (__LLVM,__bundle) section: ";
5900 outs() << "xar archive files:\n";
5901 PrintXarFilesSummary(XarFilename.c_str(), xar);
5902 }
5903
5904 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5905 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5906 if (std::error_code EC = FileOrErr.getError()) {
5907 errs() << EC.message() << "\n";
5908 return;
5909 }
5910 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5911
5912 if (!XarMemberName.empty())
5913 outs() << "In xar member " << XarMemberName << ": ";
5914 else
5915 outs() << "For (__LLVM,__bundle) section: ";
5916 outs() << "xar table of contents:\n";
5917 outs() << Buffer->getBuffer() << "\n";
5918
5919 // TODO: Go through the xar's files.
5920 xar_iter_t xi = xar_iter_new();
5921 if(!xi){
5922 errs() << "Can't obtain an xar iterator for xar archive "
5923 << XarFilename.c_str() << "\n";
5924 xar_close(xar);
5925 return;
5926 }
5927 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5928 const char *key;
5929 xar_iter_t xp;
5930 const char *member_name, *member_type, *member_size_string;
5931 size_t member_size;
5932
5933 xp = xar_iter_new();
5934 if(!xp){
5935 errs() << "Can't obtain an xar iterator for xar archive "
5936 << XarFilename.c_str() << "\n";
5937 xar_close(xar);
5938 return;
5939 }
5940 member_name = NULL;
5941 member_type = NULL;
5942 member_size_string = NULL;
5943 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5944 const char *val = nullptr;
5945 xar_prop_get(xf, key, &val);
5946#if 0 // Useful for debugging.
5947 outs() << "key: " << key << " value: " << val << "\n";
5948#endif
5949 if(strcmp(key, "name") == 0)
5950 member_name = val;
5951 if(strcmp(key, "type") == 0)
5952 member_type = val;
5953 if(strcmp(key, "data/size") == 0)
5954 member_size_string = val;
5955 }
5956 /*
5957 * If we find a file with a name, date/size and type properties
5958 * and with the type being "file" see if that is a xar file.
5959 */
5960 if (member_name != NULL && member_type != NULL &&
5961 strcmp(member_type, "file") == 0 &&
5962 member_size_string != NULL){
5963 // Extract the file into a buffer.
5964 char *endptr;
5965 member_size = strtoul(member_size_string, &endptr, 10);
5966 if (*endptr == '\0' && member_size != 0) {
5967 char *buffer = (char *) ::operator new (member_size);
5968 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
5969#if 0 // Useful for debugging.
5970 outs() << "xar member: " << member_name << " extracted\n";
5971#endif
5972 // Set the XarMemberName we want to see printed in the header.
5973 std::string OldXarMemberName;
5974 // If XarMemberName is already set this is nested. So
5975 // save the old name and create the nested name.
5976 if (!XarMemberName.empty()) {
5977 OldXarMemberName = XarMemberName;
5978 XarMemberName =
5979 (Twine("[") + XarMemberName + "]" + member_name).str();
5980 } else {
5981 OldXarMemberName = "";
5982 XarMemberName = member_name;
5983 }
5984 // See if this is could be a xar file (nested).
5985 if (member_size >= sizeof(struct xar_header)) {
5986#if 0 // Useful for debugging.
5987 outs() << "could be a xar file: " << member_name << "\n";
5988#endif
5989 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
5990 if (sys::IsLittleEndianHost)
5991 swapStruct(XarHeader);
5992 if(XarHeader.magic == XAR_HEADER_MAGIC)
5993 DumpBitcodeSection(O, buffer, member_size, verbose,
5994 PrintXarHeader, PrintXarFileHeaders,
5995 XarMemberName);
5996 }
5997 XarMemberName = OldXarMemberName;
5998 }
5999 delete buffer;
6000 }
6001 }
6002 xar_iter_free(xp);
6003 }
6004 xar_close(xar);
6005}
6006#endif // defined(HAVE_LIBXAR)
6007
Kevin Enderby0fc11822015-04-01 20:57:01 +00006008static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6009 if (O->is64Bit())
6010 printObjc2_64bit_MetaData(O, verbose);
6011 else {
6012 MachO::mach_header H;
6013 H = O->getHeader();
6014 if (H.cputype == MachO::CPU_TYPE_ARM)
6015 printObjc2_32bit_MetaData(O, verbose);
6016 else {
6017 // This is the 32-bit non-arm cputype case. Which is normally
6018 // the first Objective-C ABI. But it may be the case of a
6019 // binary for the iOS simulator which is the second Objective-C
6020 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6021 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006022 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006023 printObjc2_32bit_MetaData(O, verbose);
6024 }
6025 }
6026}
6027
Kevin Enderbybf246f52014-09-24 23:08:22 +00006028// GuessLiteralPointer returns a string which for the item in the Mach-O file
6029// for the address passed in as ReferenceValue for printing as a comment with
6030// the instruction and also returns the corresponding type of that item
6031// indirectly through ReferenceType.
6032//
6033// If ReferenceValue is an address of literal cstring then a pointer to the
6034// cstring is returned and ReferenceType is set to
6035// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6036//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006037// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6038// Class ref that name is returned and the ReferenceType is set accordingly.
6039//
6040// Lastly, literals which are Symbol address in a literal pool are looked for
6041// and if found the symbol name is returned and ReferenceType is set to
6042// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6043//
6044// If there is no item in the Mach-O file for the address passed in as
6045// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006046static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6047 uint64_t ReferencePC,
6048 uint64_t *ReferenceType,
6049 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006050 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006051 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6052 uint64_t sect_addr = info->S.getAddress();
6053 uint64_t sect_offset = ReferencePC - sect_addr;
6054 bool reloc_found = false;
6055 DataRefImpl Rel;
6056 MachO::any_relocation_info RE;
6057 bool isExtern = false;
6058 SymbolRef Symbol;
6059 for (const RelocationRef &Reloc : info->S.relocations()) {
6060 uint64_t RelocOffset = Reloc.getOffset();
6061 if (RelocOffset == sect_offset) {
6062 Rel = Reloc.getRawDataRefImpl();
6063 RE = info->O->getRelocation(Rel);
6064 if (info->O->isRelocationScattered(RE))
6065 continue;
6066 isExtern = info->O->getPlainRelocationExternal(RE);
6067 if (isExtern) {
6068 symbol_iterator RelocSym = Reloc.getSymbol();
6069 Symbol = *RelocSym;
6070 }
6071 reloc_found = true;
6072 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006073 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006074 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006075 // If there is an external relocation entry for a symbol in a section
6076 // then used that symbol's value for the value of the reference.
6077 if (reloc_found && isExtern) {
6078 if (info->O->getAnyRelocationPCRel(RE)) {
6079 unsigned Type = info->O->getAnyRelocationType(RE);
6080 if (Type == MachO::X86_64_RELOC_SIGNED) {
6081 ReferenceValue = Symbol.getValue();
6082 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006083 }
6084 }
6085 }
6086
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006087 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6088 // Message refs and Class refs.
6089 bool classref, selref, msgref, cfstring;
6090 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6091 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006092 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006093 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6094 // And the pointer_value in that section is typically zero as it will be
6095 // set by dyld as part of the "bind information".
6096 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6097 if (name != nullptr) {
6098 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006099 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006100 if (class_name != nullptr && class_name[1] == '_' &&
6101 class_name[2] != '\0') {
6102 info->class_name = class_name + 2;
6103 return name;
6104 }
6105 }
6106 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006107
David Blaikie33dd45d02015-03-23 18:39:02 +00006108 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006109 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6110 const char *name =
6111 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6112 if (name != nullptr)
6113 info->class_name = name;
6114 else
6115 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006116 return name;
6117 }
6118
David Blaikie33dd45d02015-03-23 18:39:02 +00006119 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006120 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6121 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6122 return name;
6123 }
6124
David Blaikie33dd45d02015-03-23 18:39:02 +00006125 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006126 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6127
6128 if (pointer_value != 0)
6129 ReferenceValue = pointer_value;
6130
6131 const char *name = GuessCstringPointer(ReferenceValue, info);
6132 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006133 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006134 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6135 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006136 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006137 info->class_name = nullptr;
6138 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6139 info->selector_name = name;
6140 } else
6141 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6142 return name;
6143 }
6144
6145 // Lastly look for an indirect symbol with this ReferenceValue which is in
6146 // a literal pool. If found return that symbol name.
6147 name = GuessIndirectSymbol(ReferenceValue, info);
6148 if (name) {
6149 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6150 return name;
6151 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006152
6153 return nullptr;
6154}
6155
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006156// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006157// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006158// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6159// is created and returns the symbol name that matches the ReferenceValue or
6160// nullptr if none. The ReferenceType is passed in for the IN type of
6161// reference the instruction is making from the values in defined in the header
6162// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6163// Out type and the ReferenceName will also be set which is added as a comment
6164// to the disassembled instruction.
6165//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006166// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006167// returned through ReferenceName and ReferenceType is set to
6168// LLVMDisassembler_ReferenceType_DeMangled_Name .
6169//
6170// When this is called to get a symbol name for a branch target then the
6171// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6172// SymbolValue will be looked for in the indirect symbol table to determine if
6173// it is an address for a symbol stub. If so then the symbol name for that
6174// stub is returned indirectly through ReferenceName and then ReferenceType is
6175// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6176//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006177// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006178// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6179// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6180// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006181// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006182static const char *SymbolizerSymbolLookUp(void *DisInfo,
6183 uint64_t ReferenceValue,
6184 uint64_t *ReferenceType,
6185 uint64_t ReferencePC,
6186 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006187 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006188 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006189 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006190 *ReferenceName = nullptr;
6191 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006192 return nullptr;
6193 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006194
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006195 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006196
Kevin Enderby85974882014-09-26 22:20:44 +00006197 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6198 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006199 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006200 method_reference(info, ReferenceType, ReferenceName);
6201 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6202 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006203 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006204 if (info->demangled_name != nullptr)
6205 free(info->demangled_name);
6206 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006207 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006208 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006209 if (info->demangled_name != nullptr) {
6210 *ReferenceName = info->demangled_name;
6211 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6212 } else
6213 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6214 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006215 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6216 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6217 *ReferenceName =
6218 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006219 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006220 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006221 else
6222 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006223 // If this is arm64 and the reference is an adrp instruction save the
6224 // instruction, passed in ReferenceValue and the address of the instruction
6225 // for use later if we see and add immediate instruction.
6226 } else if (info->O->getArch() == Triple::aarch64 &&
6227 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6228 info->adrp_inst = ReferenceValue;
6229 info->adrp_addr = ReferencePC;
6230 SymbolName = nullptr;
6231 *ReferenceName = nullptr;
6232 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6233 // If this is arm64 and reference is an add immediate instruction and we
6234 // have
6235 // seen an adrp instruction just before it and the adrp's Xd register
6236 // matches
6237 // this add's Xn register reconstruct the value being referenced and look to
6238 // see if it is a literal pointer. Note the add immediate instruction is
6239 // passed in ReferenceValue.
6240 } else if (info->O->getArch() == Triple::aarch64 &&
6241 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6242 ReferencePC - 4 == info->adrp_addr &&
6243 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6244 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6245 uint32_t addxri_inst;
6246 uint64_t adrp_imm, addxri_imm;
6247
6248 adrp_imm =
6249 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6250 if (info->adrp_inst & 0x0200000)
6251 adrp_imm |= 0xfffffffffc000000LL;
6252
6253 addxri_inst = ReferenceValue;
6254 addxri_imm = (addxri_inst >> 10) & 0xfff;
6255 if (((addxri_inst >> 22) & 0x3) == 1)
6256 addxri_imm <<= 12;
6257
6258 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6259 (adrp_imm << 12) + addxri_imm;
6260
6261 *ReferenceName =
6262 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6263 if (*ReferenceName == nullptr)
6264 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6265 // If this is arm64 and the reference is a load register instruction and we
6266 // have seen an adrp instruction just before it and the adrp's Xd register
6267 // matches this add's Xn register reconstruct the value being referenced and
6268 // look to see if it is a literal pointer. Note the load register
6269 // instruction is passed in ReferenceValue.
6270 } else if (info->O->getArch() == Triple::aarch64 &&
6271 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6272 ReferencePC - 4 == info->adrp_addr &&
6273 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6274 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6275 uint32_t ldrxui_inst;
6276 uint64_t adrp_imm, ldrxui_imm;
6277
6278 adrp_imm =
6279 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6280 if (info->adrp_inst & 0x0200000)
6281 adrp_imm |= 0xfffffffffc000000LL;
6282
6283 ldrxui_inst = ReferenceValue;
6284 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6285
6286 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6287 (adrp_imm << 12) + (ldrxui_imm << 3);
6288
6289 *ReferenceName =
6290 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6291 if (*ReferenceName == nullptr)
6292 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6293 }
6294 // If this arm64 and is an load register (PC-relative) instruction the
6295 // ReferenceValue is the PC plus the immediate value.
6296 else if (info->O->getArch() == Triple::aarch64 &&
6297 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6298 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6299 *ReferenceName =
6300 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6301 if (*ReferenceName == nullptr)
6302 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006303 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006304 if (info->demangled_name != nullptr)
6305 free(info->demangled_name);
6306 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006307 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006308 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006309 if (info->demangled_name != nullptr) {
6310 *ReferenceName = info->demangled_name;
6311 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6312 }
6313 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006314 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006315 *ReferenceName = nullptr;
6316 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6317 }
6318
6319 return SymbolName;
6320}
6321
Kevin Enderbybf246f52014-09-24 23:08:22 +00006322/// \brief Emits the comments that are stored in the CommentStream.
6323/// Each comment in the CommentStream must end with a newline.
6324static void emitComments(raw_svector_ostream &CommentStream,
6325 SmallString<128> &CommentsToEmit,
6326 formatted_raw_ostream &FormattedOS,
6327 const MCAsmInfo &MAI) {
6328 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006329 StringRef Comments = CommentsToEmit.str();
6330 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006331 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006332 unsigned CommentColumn = MAI.getCommentColumn();
6333 bool IsFirst = true;
6334 while (!Comments.empty()) {
6335 if (!IsFirst)
6336 FormattedOS << '\n';
6337 // Emit a line of comments.
6338 FormattedOS.PadToColumn(CommentColumn);
6339 size_t Position = Comments.find('\n');
6340 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6341 // Move after the newline character.
6342 Comments = Comments.substr(Position + 1);
6343 IsFirst = false;
6344 }
6345 FormattedOS.flush();
6346
6347 // Tell the comment stream that the vector changed underneath it.
6348 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006349}
6350
Kevin Enderby95df54c2015-02-04 01:01:38 +00006351static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6352 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006353 const char *McpuDefault = nullptr;
6354 const Target *ThumbTarget = nullptr;
6355 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006356 if (!TheTarget) {
6357 // GetTarget prints out stuff.
6358 return;
6359 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006360 if (MCPU.empty() && McpuDefault)
6361 MCPU = McpuDefault;
6362
Ahmed Charles56440fd2014-03-06 05:51:42 +00006363 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006364 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006365 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006366 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006367
Kevin Enderbyc9595622014-08-06 23:24:41 +00006368 // Package up features to be passed to target/subtarget
6369 std::string FeaturesStr;
6370 if (MAttrs.size()) {
6371 SubtargetFeatures Features;
6372 for (unsigned i = 0; i != MAttrs.size(); ++i)
6373 Features.AddFeature(MAttrs[i]);
6374 FeaturesStr = Features.getString();
6375 }
6376
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006377 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006378 std::unique_ptr<const MCRegisterInfo> MRI(
6379 TheTarget->createMCRegInfo(TripleName));
6380 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006381 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006382 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006383 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006384 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006385 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006386 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006387 std::unique_ptr<MCSymbolizer> Symbolizer;
6388 struct DisassembleInfo SymbolizerInfo;
6389 std::unique_ptr<MCRelocationInfo> RelInfo(
6390 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6391 if (RelInfo) {
6392 Symbolizer.reset(TheTarget->createMCSymbolizer(
6393 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006394 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006395 DisAsm->setSymbolizer(std::move(Symbolizer));
6396 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006397 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006398 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006399 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006400 // Set the display preference for hex vs. decimal immediates.
6401 IP->setPrintImmHex(PrintImmHex);
6402 // Comment stream and backing vector.
6403 SmallString<128> CommentsToEmit;
6404 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006405 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6406 // if it is done then arm64 comments for string literals don't get printed
6407 // and some constant get printed instead and not setting it causes intel
6408 // (32-bit and 64-bit) comments printed with different spacing before the
6409 // comment causing different diffs with the 'C' disassembler library API.
6410 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006411
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006412 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006413 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006414 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006415 return;
6416 }
6417
Tim Northover09ca33e2016-04-22 23:23:31 +00006418 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006419 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6420 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6421 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006422 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006423 std::unique_ptr<MCInstPrinter> ThumbIP;
6424 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006425 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6426 struct DisassembleInfo ThumbSymbolizerInfo;
6427 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006428 if (ThumbTarget) {
6429 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6430 ThumbAsmInfo.reset(
6431 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6432 ThumbSTI.reset(
6433 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6434 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6435 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006436 MCContext *PtrThumbCtx = ThumbCtx.get();
6437 ThumbRelInfo.reset(
6438 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6439 if (ThumbRelInfo) {
6440 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6441 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006442 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006443 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6444 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006445 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6446 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006447 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6448 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006449 // Set the display preference for hex vs. decimal immediates.
6450 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006451 }
6452
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006453 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006454 errs() << "error: couldn't initialize disassembler for target "
6455 << ThumbTripleName << '\n';
6456 return;
6457 }
6458
Charles Davis8bdfafd2013-09-01 04:28:48 +00006459 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006460
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006461 // FIXME: Using the -cfg command line option, this code used to be able to
6462 // annotate relocations with the referenced symbol's name, and if this was
6463 // inside a __[cf]string section, the data it points to. This is now replaced
6464 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006465 std::vector<SectionRef> Sections;
6466 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006467 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006468 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006469
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006470 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006471 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006472
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006473 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006474 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006475
Kevin Enderby273ae012013-06-06 17:20:50 +00006476 // Build a data in code table that is sorted on by the address of each entry.
6477 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006478 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006479 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006480 else
6481 BaseAddress = BaseSegmentAddress;
6482 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006483 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006484 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006485 uint32_t Offset;
6486 DI->getOffset(Offset);
6487 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6488 }
6489 array_pod_sort(Dices.begin(), Dices.end());
6490
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006491#ifndef NDEBUG
6492 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6493#else
6494 raw_ostream &DebugOut = nulls();
6495#endif
6496
Ahmed Charles56440fd2014-03-06 05:51:42 +00006497 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006498 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006499 // Try to find debug info and set up the DIContext for it.
6500 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006501 // A separate DSym file path was specified, parse it as a macho file,
6502 // get the sections and supply it to the section name parsing machinery.
6503 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006504 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006505 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006506 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006507 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006508 return;
6509 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006510 DbgObj =
6511 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6512 .get()
6513 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006514 }
6515
Eric Christopher7370b552012-11-12 21:40:38 +00006516 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006517 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006518 }
6519
Colin LeMahieufcc32762015-07-29 19:08:10 +00006520 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006521 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006522
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006523 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006524 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006525 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6526 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006527
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006528 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006529
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006530 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006531 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006532 continue;
6533
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006534 StringRef BytesStr;
6535 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006536 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6537 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006538 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006539
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006540 bool symbolTableWorked = false;
6541
Kevin Enderbybf246f52014-09-24 23:08:22 +00006542 // Create a map of symbol addresses to symbol names for use by
6543 // the SymbolizerSymbolLookUp() routine.
6544 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006545 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006546 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006547 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006548 if (!STOrErr)
6549 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006550 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006551 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6552 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006553 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006554 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006555 if (!SymNameOrErr)
6556 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006557 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006558 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006559 if (!DisSymName.empty() && DisSymName == SymName)
6560 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006561 }
6562 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006563 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006564 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6565 return;
6566 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006567 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006568 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006569 SymbolizerInfo.O = MachOOF;
6570 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006571 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006572 SymbolizerInfo.Sections = &Sections;
6573 SymbolizerInfo.class_name = nullptr;
6574 SymbolizerInfo.selector_name = nullptr;
6575 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006576 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006577 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006578 SymbolizerInfo.adrp_addr = 0;
6579 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006580 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006581 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006582 ThumbSymbolizerInfo.O = MachOOF;
6583 ThumbSymbolizerInfo.S = Sections[SectIdx];
6584 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6585 ThumbSymbolizerInfo.Sections = &Sections;
6586 ThumbSymbolizerInfo.class_name = nullptr;
6587 ThumbSymbolizerInfo.selector_name = nullptr;
6588 ThumbSymbolizerInfo.method = nullptr;
6589 ThumbSymbolizerInfo.demangled_name = nullptr;
6590 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006591 ThumbSymbolizerInfo.adrp_addr = 0;
6592 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006593
Kevin Enderby4b627be2016-04-28 20:14:13 +00006594 unsigned int Arch = MachOOF->getArch();
6595
Tim Northoverf203ab52016-07-14 22:13:32 +00006596 // Skip all symbols if this is a stubs file.
6597 if (Bytes.size() == 0)
6598 return;
6599
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006600 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006601 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006602 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006603 if (!SymNameOrErr)
6604 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006605 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006606
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006607 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006608 if (!STOrErr)
6609 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006610 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006611 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006612 continue;
6613
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006614 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006615 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006616 if (!containsSym) {
6617 if (!DisSymName.empty() && DisSymName == SymName) {
6618 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6619 return;
6620 }
6621 continue;
6622 }
6623 // The __mh_execute_header is special and we need to deal with that fact
6624 // this symbol is before the start of the (__TEXT,__text) section and at the
6625 // address of the start of the __TEXT segment. This is because this symbol
6626 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6627 // start of the section in a standard MH_EXECUTE filetype.
6628 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6629 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6630 return;
6631 }
Tim Northoverfbefee32016-07-14 23:13:03 +00006632 // When this code is trying to disassemble a symbol at a time and in the
6633 // case there is only the __mh_execute_header symbol left as in a stripped
6634 // executable, we need to deal with this by ignoring this symbol so the
6635 // whole section is disassembled and this symbol is then not displayed.
6636 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6637 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6638 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006639 continue;
6640
Kevin Enderby6a221752015-03-17 17:10:57 +00006641 // If we are only disassembling one symbol see if this is that symbol.
6642 if (!DisSymName.empty() && DisSymName != SymName)
6643 continue;
6644
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006645 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00006646 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00006647 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006648 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006649 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006650
Tim Northoverf203ab52016-07-14 22:13:32 +00006651 if (Start > SectSize) {
6652 outs() << "section data ends, " << SymName
6653 << " lies outside valid range\n";
6654 return;
6655 }
6656
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006657 // Stop disassembling either at the beginning of the next symbol or at
6658 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006659 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006660 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006661 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006662 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006663 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006664 if (!STOrErr)
6665 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006666 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006667 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006668 containsNextSym =
6669 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006670 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006671 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006672 break;
6673 }
6674 ++NextSymIdx;
6675 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006676
Tim Northoverf203ab52016-07-14 22:13:32 +00006677 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006678 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006679
6680 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006681
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006682 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006683 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6684
6685 // We only need the dedicated Thumb target if there's a real choice
6686 // (i.e. we're not targeting M-class) and the function is Thumb.
6687 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006688
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006689 outs() << SymName << ":\n";
6690 DILineInfo lastLine;
6691 for (uint64_t Index = Start; Index < End; Index += Size) {
6692 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006693
Kevin Enderbybf246f52014-09-24 23:08:22 +00006694 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006695 if (!NoLeadingAddr) {
6696 if (FullLeadingAddr) {
6697 if (MachOOF->is64Bit())
6698 outs() << format("%016" PRIx64, PC);
6699 else
6700 outs() << format("%08" PRIx64, PC);
6701 } else {
6702 outs() << format("%8" PRIx64 ":", PC);
6703 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006704 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006705 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006706 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006707
6708 // Check the data in code table here to see if this is data not an
6709 // instruction to be disassembled.
6710 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006711 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006712 dice_table_iterator DTI =
6713 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6714 compareDiceTableEntries);
6715 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006716 uint16_t Length;
6717 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006718 uint16_t Kind;
6719 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006720 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006721 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6722 (PC == (DTI->first + Length - 1)) && (Length & 1))
6723 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006724 continue;
6725 }
6726
Kevin Enderbybf246f52014-09-24 23:08:22 +00006727 SmallVector<char, 64> AnnotationsBytes;
6728 raw_svector_ostream Annotations(AnnotationsBytes);
6729
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006730 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006731 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006732 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006733 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006734 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006735 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006736 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006737 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006738 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006739 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006740 }
6741 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006742 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006743 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006744 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006745 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006746 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006747 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006748
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006749 // Print debug info.
6750 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006751 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006752 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006753 if (dli != lastLine && dli.Line != 0)
6754 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6755 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006756 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006757 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006758 outs() << "\n";
6759 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006760 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006761 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006762 outs() << format("\t.byte 0x%02x #bad opcode\n",
6763 *(Bytes.data() + Index) & 0xff);
6764 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006765 } else if (Arch == Triple::aarch64 ||
6766 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006767 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6768 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6769 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6770 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6771 outs() << format("\t.long\t0x%08x\n", opcode);
6772 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006773 } else if (Arch == Triple::arm) {
6774 assert(IsThumb && "ARM mode should have been dealt with above");
6775 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6776 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6777 outs() << format("\t.short\t0x%04x\n", opcode);
6778 Size = 2;
6779 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006780 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6781 if (Size == 0)
6782 Size = 1; // skip illegible bytes
6783 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006784 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006785 }
6786 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006787 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006788 // Reading the symbol table didn't work, disassemble the whole section.
6789 uint64_t SectAddress = Sections[SectIdx].getAddress();
6790 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006791 uint64_t InstSize;
6792 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006793 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006794
Kevin Enderbybf246f52014-09-24 23:08:22 +00006795 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006796 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6797 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006798 if (!NoLeadingAddr) {
6799 if (FullLeadingAddr) {
6800 if (MachOOF->is64Bit())
6801 outs() << format("%016" PRIx64, PC);
6802 else
6803 outs() << format("%08" PRIx64, PC);
6804 } else {
6805 outs() << format("%8" PRIx64 ":", PC);
6806 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006807 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006808 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006809 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006810 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006811 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006812 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006813 outs() << "\n";
6814 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006815 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006816 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006817 outs() << format("\t.byte 0x%02x #bad opcode\n",
6818 *(Bytes.data() + Index) & 0xff);
6819 InstSize = 1; // skip exactly one illegible byte and move on.
6820 } else {
6821 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6822 if (InstSize == 0)
6823 InstSize = 1; // skip illegible bytes
6824 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006825 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006826 }
6827 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006828 // The TripleName's need to be reset if we are called again for a different
6829 // archtecture.
6830 TripleName = "";
6831 ThumbTripleName = "";
6832
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006833 if (SymbolizerInfo.method != nullptr)
6834 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006835 if (SymbolizerInfo.demangled_name != nullptr)
6836 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006837 if (ThumbSymbolizerInfo.method != nullptr)
6838 free(ThumbSymbolizerInfo.method);
6839 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6840 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006841 }
6842}
Tim Northover4bd286a2014-08-01 13:07:19 +00006843
Tim Northover39c70bb2014-08-12 11:52:59 +00006844//===----------------------------------------------------------------------===//
6845// __compact_unwind section dumping
6846//===----------------------------------------------------------------------===//
6847
Tim Northover4bd286a2014-08-01 13:07:19 +00006848namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006849
6850template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006851 using llvm::support::little;
6852 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006853
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006854 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6855 Buf += sizeof(T);
6856 return Val;
6857}
Tim Northover39c70bb2014-08-12 11:52:59 +00006858
Tim Northover4bd286a2014-08-01 13:07:19 +00006859struct CompactUnwindEntry {
6860 uint32_t OffsetInSection;
6861
6862 uint64_t FunctionAddr;
6863 uint32_t Length;
6864 uint32_t CompactEncoding;
6865 uint64_t PersonalityAddr;
6866 uint64_t LSDAAddr;
6867
6868 RelocationRef FunctionReloc;
6869 RelocationRef PersonalityReloc;
6870 RelocationRef LSDAReloc;
6871
6872 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006873 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006874 if (Is64)
6875 read<uint64_t>(Contents.data() + Offset);
6876 else
6877 read<uint32_t>(Contents.data() + Offset);
6878 }
6879
6880private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006881 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006882 FunctionAddr = readNext<UIntPtr>(Buf);
6883 Length = readNext<uint32_t>(Buf);
6884 CompactEncoding = readNext<uint32_t>(Buf);
6885 PersonalityAddr = readNext<UIntPtr>(Buf);
6886 LSDAAddr = readNext<UIntPtr>(Buf);
6887 }
6888};
6889}
6890
6891/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6892/// and data being relocated, determine the best base Name and Addend to use for
6893/// display purposes.
6894///
6895/// 1. An Extern relocation will directly reference a symbol (and the data is
6896/// then already an addend), so use that.
6897/// 2. Otherwise the data is an offset in the object file's layout; try to find
6898// a symbol before it in the same section, and use the offset from there.
6899/// 3. Finally, if all that fails, fall back to an offset from the start of the
6900/// referenced section.
6901static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6902 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006903 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006904 StringRef &Name, uint64_t &Addend) {
6905 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006906 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006907 if (!NameOrErr)
6908 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006909 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006910 Addend = Addr;
6911 return;
6912 }
6913
6914 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006915 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006916
Rafael Espindola80291272014-10-08 15:28:58 +00006917 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006918
6919 auto Sym = Symbols.upper_bound(Addr);
6920 if (Sym == Symbols.begin()) {
6921 // The first symbol in the object is after this reference, the best we can
6922 // do is section-relative notation.
6923 RelocSection.getName(Name);
6924 Addend = Addr - SectionAddr;
6925 return;
6926 }
6927
6928 // Go back one so that SymbolAddress <= Addr.
6929 --Sym;
6930
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006931 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006932 if (!SectOrErr)
6933 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006934 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006935 if (RelocSection == *SymSection) {
6936 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006937 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006938 if (!NameOrErr)
6939 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006940 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006941 Addend = Addr - Sym->first;
6942 return;
6943 }
6944
6945 // There is a symbol before this reference, but it's in a different
6946 // section. Probably not helpful to mention it, so use the section name.
6947 RelocSection.getName(Name);
6948 Addend = Addr - SectionAddr;
6949}
6950
6951static void printUnwindRelocDest(const MachOObjectFile *Obj,
6952 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006953 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006954 StringRef Name;
6955 uint64_t Addend;
6956
Rafael Espindola854038e2015-06-26 14:51:16 +00006957 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006958 return;
6959
Tim Northover4bd286a2014-08-01 13:07:19 +00006960 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6961
6962 outs() << Name;
6963 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006964 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006965}
6966
6967static void
6968printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6969 std::map<uint64_t, SymbolRef> &Symbols,
6970 const SectionRef &CompactUnwind) {
6971
Tim Northoverbf55f7e2016-11-15 20:26:01 +00006972 if (!Obj->isLittleEndian()) {
6973 outs() << "Skipping big-endian __compact_unwind section\n";
6974 return;
6975 }
Tim Northover4bd286a2014-08-01 13:07:19 +00006976
6977 bool Is64 = Obj->is64Bit();
6978 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6979 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6980
6981 StringRef Contents;
6982 CompactUnwind.getContents(Contents);
6983
6984 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6985
6986 // First populate the initial raw offsets, encodings and so on from the entry.
6987 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6988 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6989 CompactUnwinds.push_back(Entry);
6990 }
6991
6992 // Next we need to look at the relocations to find out what objects are
6993 // actually being referred to.
6994 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006995 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006996
6997 uint32_t EntryIdx = RelocAddress / EntrySize;
6998 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6999 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7000
7001 if (OffsetInEntry == 0)
7002 Entry.FunctionReloc = Reloc;
7003 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7004 Entry.PersonalityReloc = Reloc;
7005 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7006 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007007 else {
7008 outs() << "Invalid relocation in __compact_unwind section\n";
7009 return;
7010 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007011 }
7012
7013 // Finally, we're ready to print the data we've gathered.
7014 outs() << "Contents of __compact_unwind section:\n";
7015 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007016 outs() << " Entry at offset "
7017 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007018
7019 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007020 outs() << " start: " << format("0x%" PRIx64,
7021 Entry.FunctionAddr) << ' ';
7022 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007023 outs() << '\n';
7024
7025 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007026 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7027 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007028 // 3. The 32-bit compact encoding.
7029 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007030 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007031
7032 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007033 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007034 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007035 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007036 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7037 Entry.PersonalityAddr);
7038 outs() << '\n';
7039 }
7040
7041 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007042 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007043 outs() << " LSDA: " << format("0x%" PRIx64,
7044 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007045 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7046 outs() << '\n';
7047 }
7048 }
7049}
7050
Tim Northover39c70bb2014-08-12 11:52:59 +00007051//===----------------------------------------------------------------------===//
7052// __unwind_info section dumping
7053//===----------------------------------------------------------------------===//
7054
7055static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7056 const char *Pos = PageStart;
7057 uint32_t Kind = readNext<uint32_t>(Pos);
7058 (void)Kind;
7059 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7060
7061 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7062 uint16_t NumEntries = readNext<uint16_t>(Pos);
7063
7064 Pos = PageStart + EntriesStart;
7065 for (unsigned i = 0; i < NumEntries; ++i) {
7066 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7067 uint32_t Encoding = readNext<uint32_t>(Pos);
7068
7069 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007070 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7071 << ", "
7072 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007073 }
7074}
7075
7076static void printCompressedSecondLevelUnwindPage(
7077 const char *PageStart, uint32_t FunctionBase,
7078 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7079 const char *Pos = PageStart;
7080 uint32_t Kind = readNext<uint32_t>(Pos);
7081 (void)Kind;
7082 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7083
7084 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7085 uint16_t NumEntries = readNext<uint16_t>(Pos);
7086
7087 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7088 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007089 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7090 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007091
7092 Pos = PageStart + EntriesStart;
7093 for (unsigned i = 0; i < NumEntries; ++i) {
7094 uint32_t Entry = readNext<uint32_t>(Pos);
7095 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7096 uint32_t EncodingIdx = Entry >> 24;
7097
7098 uint32_t Encoding;
7099 if (EncodingIdx < CommonEncodings.size())
7100 Encoding = CommonEncodings[EncodingIdx];
7101 else
7102 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7103
7104 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007105 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7106 << ", "
7107 << "encoding[" << EncodingIdx
7108 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007109 }
7110}
7111
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007112static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7113 std::map<uint64_t, SymbolRef> &Symbols,
7114 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007115
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007116 if (!Obj->isLittleEndian()) {
7117 outs() << "Skipping big-endian __unwind_info section\n";
7118 return;
7119 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007120
7121 outs() << "Contents of __unwind_info section:\n";
7122
7123 StringRef Contents;
7124 UnwindInfo.getContents(Contents);
7125 const char *Pos = Contents.data();
7126
7127 //===----------------------------------
7128 // Section header
7129 //===----------------------------------
7130
7131 uint32_t Version = readNext<uint32_t>(Pos);
7132 outs() << " Version: "
7133 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007134 if (Version != 1) {
7135 outs() << " Skipping section with unknown version\n";
7136 return;
7137 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007138
7139 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7140 outs() << " Common encodings array section offset: "
7141 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7142 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7143 outs() << " Number of common encodings in array: "
7144 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7145
7146 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7147 outs() << " Personality function array section offset: "
7148 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7149 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7150 outs() << " Number of personality functions in array: "
7151 << format("0x%" PRIx32, NumPersonalities) << '\n';
7152
7153 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7154 outs() << " Index array section offset: "
7155 << format("0x%" PRIx32, IndicesStart) << '\n';
7156 uint32_t NumIndices = readNext<uint32_t>(Pos);
7157 outs() << " Number of indices in array: "
7158 << format("0x%" PRIx32, NumIndices) << '\n';
7159
7160 //===----------------------------------
7161 // A shared list of common encodings
7162 //===----------------------------------
7163
7164 // These occupy indices in the range [0, N] whenever an encoding is referenced
7165 // from a compressed 2nd level index table. In practice the linker only
7166 // creates ~128 of these, so that indices are available to embed encodings in
7167 // the 2nd level index.
7168
7169 SmallVector<uint32_t, 64> CommonEncodings;
7170 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7171 Pos = Contents.data() + CommonEncodingsStart;
7172 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7173 uint32_t Encoding = readNext<uint32_t>(Pos);
7174 CommonEncodings.push_back(Encoding);
7175
7176 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7177 << '\n';
7178 }
7179
Tim Northover39c70bb2014-08-12 11:52:59 +00007180 //===----------------------------------
7181 // Personality functions used in this executable
7182 //===----------------------------------
7183
7184 // There should be only a handful of these (one per source language,
7185 // roughly). Particularly since they only get 2 bits in the compact encoding.
7186
7187 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7188 Pos = Contents.data() + PersonalitiesStart;
7189 for (unsigned i = 0; i < NumPersonalities; ++i) {
7190 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7191 outs() << " personality[" << i + 1
7192 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7193 }
7194
7195 //===----------------------------------
7196 // The level 1 index entries
7197 //===----------------------------------
7198
7199 // These specify an approximate place to start searching for the more detailed
7200 // information, sorted by PC.
7201
7202 struct IndexEntry {
7203 uint32_t FunctionOffset;
7204 uint32_t SecondLevelPageStart;
7205 uint32_t LSDAStart;
7206 };
7207
7208 SmallVector<IndexEntry, 4> IndexEntries;
7209
7210 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7211 Pos = Contents.data() + IndicesStart;
7212 for (unsigned i = 0; i < NumIndices; ++i) {
7213 IndexEntry Entry;
7214
7215 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7216 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7217 Entry.LSDAStart = readNext<uint32_t>(Pos);
7218 IndexEntries.push_back(Entry);
7219
7220 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007221 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7222 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007223 << "2nd level page offset="
7224 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007225 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007226 }
7227
Tim Northover39c70bb2014-08-12 11:52:59 +00007228 //===----------------------------------
7229 // Next come the LSDA tables
7230 //===----------------------------------
7231
7232 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7233 // the first top-level index's LSDAOffset to the last (sentinel).
7234
7235 outs() << " LSDA descriptors:\n";
7236 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7237 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7238 (2 * sizeof(uint32_t));
7239 for (int i = 0; i < NumLSDAs; ++i) {
7240 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7241 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7242 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007243 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7244 << ", "
7245 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007246 }
7247
7248 //===----------------------------------
7249 // Finally, the 2nd level indices
7250 //===----------------------------------
7251
7252 // Generally these are 4K in size, and have 2 possible forms:
7253 // + Regular stores up to 511 entries with disparate encodings
7254 // + Compressed stores up to 1021 entries if few enough compact encoding
7255 // values are used.
7256 outs() << " Second level indices:\n";
7257 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7258 // The final sentinel top-level index has no associated 2nd level page
7259 if (IndexEntries[i].SecondLevelPageStart == 0)
7260 break;
7261
7262 outs() << " Second level index[" << i << "]: "
7263 << "offset in section="
7264 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7265 << ", "
7266 << "base function offset="
7267 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7268
7269 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007270 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007271 if (Kind == 2)
7272 printRegularSecondLevelUnwindPage(Pos);
7273 else if (Kind == 3)
7274 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7275 CommonEncodings);
7276 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007277 outs() << " Skipping 2nd level page with unknown kind " << Kind
7278 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007279 }
7280}
7281
Tim Northover4bd286a2014-08-01 13:07:19 +00007282void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7283 std::map<uint64_t, SymbolRef> Symbols;
7284 for (const SymbolRef &SymRef : Obj->symbols()) {
7285 // Discard any undefined or absolute symbols. They're not going to take part
7286 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007287 auto SectOrErr = SymRef.getSection();
7288 if (!SectOrErr) {
7289 // TODO: Actually report errors helpfully.
7290 consumeError(SectOrErr.takeError());
7291 continue;
7292 }
7293 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007294 if (Section == Obj->section_end())
7295 continue;
7296
Rafael Espindoladea00162015-07-03 17:44:18 +00007297 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007298 Symbols.insert(std::make_pair(Addr, SymRef));
7299 }
7300
7301 for (const SectionRef &Section : Obj->sections()) {
7302 StringRef SectName;
7303 Section.getName(SectName);
7304 if (SectName == "__compact_unwind")
7305 printMachOCompactUnwindSection(Obj, Symbols, Section);
7306 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007307 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007308 }
7309}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007310
7311static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7312 uint32_t cpusubtype, uint32_t filetype,
7313 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7314 bool verbose) {
7315 outs() << "Mach header\n";
7316 outs() << " magic cputype cpusubtype caps filetype ncmds "
7317 "sizeofcmds flags\n";
7318 if (verbose) {
7319 if (magic == MachO::MH_MAGIC)
7320 outs() << " MH_MAGIC";
7321 else if (magic == MachO::MH_MAGIC_64)
7322 outs() << "MH_MAGIC_64";
7323 else
7324 outs() << format(" 0x%08" PRIx32, magic);
7325 switch (cputype) {
7326 case MachO::CPU_TYPE_I386:
7327 outs() << " I386";
7328 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7329 case MachO::CPU_SUBTYPE_I386_ALL:
7330 outs() << " ALL";
7331 break;
7332 default:
7333 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7334 break;
7335 }
7336 break;
7337 case MachO::CPU_TYPE_X86_64:
7338 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007339 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7340 case MachO::CPU_SUBTYPE_X86_64_ALL:
7341 outs() << " ALL";
7342 break;
7343 case MachO::CPU_SUBTYPE_X86_64_H:
7344 outs() << " Haswell";
7345 break;
7346 default:
7347 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7348 break;
7349 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007350 break;
7351 case MachO::CPU_TYPE_ARM:
7352 outs() << " ARM";
7353 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7354 case MachO::CPU_SUBTYPE_ARM_ALL:
7355 outs() << " ALL";
7356 break;
7357 case MachO::CPU_SUBTYPE_ARM_V4T:
7358 outs() << " V4T";
7359 break;
7360 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7361 outs() << " V5TEJ";
7362 break;
7363 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7364 outs() << " XSCALE";
7365 break;
7366 case MachO::CPU_SUBTYPE_ARM_V6:
7367 outs() << " V6";
7368 break;
7369 case MachO::CPU_SUBTYPE_ARM_V6M:
7370 outs() << " V6M";
7371 break;
7372 case MachO::CPU_SUBTYPE_ARM_V7:
7373 outs() << " V7";
7374 break;
7375 case MachO::CPU_SUBTYPE_ARM_V7EM:
7376 outs() << " V7EM";
7377 break;
7378 case MachO::CPU_SUBTYPE_ARM_V7K:
7379 outs() << " V7K";
7380 break;
7381 case MachO::CPU_SUBTYPE_ARM_V7M:
7382 outs() << " V7M";
7383 break;
7384 case MachO::CPU_SUBTYPE_ARM_V7S:
7385 outs() << " V7S";
7386 break;
7387 default:
7388 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7389 break;
7390 }
7391 break;
7392 case MachO::CPU_TYPE_ARM64:
7393 outs() << " ARM64";
7394 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7395 case MachO::CPU_SUBTYPE_ARM64_ALL:
7396 outs() << " ALL";
7397 break;
7398 default:
7399 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7400 break;
7401 }
7402 break;
7403 case MachO::CPU_TYPE_POWERPC:
7404 outs() << " PPC";
7405 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7406 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7407 outs() << " ALL";
7408 break;
7409 default:
7410 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7411 break;
7412 }
7413 break;
7414 case MachO::CPU_TYPE_POWERPC64:
7415 outs() << " PPC64";
7416 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7417 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7418 outs() << " ALL";
7419 break;
7420 default:
7421 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7422 break;
7423 }
7424 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007425 default:
7426 outs() << format(" %7d", cputype);
7427 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7428 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007429 }
7430 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007431 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007432 } else {
7433 outs() << format(" 0x%02" PRIx32,
7434 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7435 }
7436 switch (filetype) {
7437 case MachO::MH_OBJECT:
7438 outs() << " OBJECT";
7439 break;
7440 case MachO::MH_EXECUTE:
7441 outs() << " EXECUTE";
7442 break;
7443 case MachO::MH_FVMLIB:
7444 outs() << " FVMLIB";
7445 break;
7446 case MachO::MH_CORE:
7447 outs() << " CORE";
7448 break;
7449 case MachO::MH_PRELOAD:
7450 outs() << " PRELOAD";
7451 break;
7452 case MachO::MH_DYLIB:
7453 outs() << " DYLIB";
7454 break;
7455 case MachO::MH_DYLIB_STUB:
7456 outs() << " DYLIB_STUB";
7457 break;
7458 case MachO::MH_DYLINKER:
7459 outs() << " DYLINKER";
7460 break;
7461 case MachO::MH_BUNDLE:
7462 outs() << " BUNDLE";
7463 break;
7464 case MachO::MH_DSYM:
7465 outs() << " DSYM";
7466 break;
7467 case MachO::MH_KEXT_BUNDLE:
7468 outs() << " KEXTBUNDLE";
7469 break;
7470 default:
7471 outs() << format(" %10u", filetype);
7472 break;
7473 }
7474 outs() << format(" %5u", ncmds);
7475 outs() << format(" %10u", sizeofcmds);
7476 uint32_t f = flags;
7477 if (f & MachO::MH_NOUNDEFS) {
7478 outs() << " NOUNDEFS";
7479 f &= ~MachO::MH_NOUNDEFS;
7480 }
7481 if (f & MachO::MH_INCRLINK) {
7482 outs() << " INCRLINK";
7483 f &= ~MachO::MH_INCRLINK;
7484 }
7485 if (f & MachO::MH_DYLDLINK) {
7486 outs() << " DYLDLINK";
7487 f &= ~MachO::MH_DYLDLINK;
7488 }
7489 if (f & MachO::MH_BINDATLOAD) {
7490 outs() << " BINDATLOAD";
7491 f &= ~MachO::MH_BINDATLOAD;
7492 }
7493 if (f & MachO::MH_PREBOUND) {
7494 outs() << " PREBOUND";
7495 f &= ~MachO::MH_PREBOUND;
7496 }
7497 if (f & MachO::MH_SPLIT_SEGS) {
7498 outs() << " SPLIT_SEGS";
7499 f &= ~MachO::MH_SPLIT_SEGS;
7500 }
7501 if (f & MachO::MH_LAZY_INIT) {
7502 outs() << " LAZY_INIT";
7503 f &= ~MachO::MH_LAZY_INIT;
7504 }
7505 if (f & MachO::MH_TWOLEVEL) {
7506 outs() << " TWOLEVEL";
7507 f &= ~MachO::MH_TWOLEVEL;
7508 }
7509 if (f & MachO::MH_FORCE_FLAT) {
7510 outs() << " FORCE_FLAT";
7511 f &= ~MachO::MH_FORCE_FLAT;
7512 }
7513 if (f & MachO::MH_NOMULTIDEFS) {
7514 outs() << " NOMULTIDEFS";
7515 f &= ~MachO::MH_NOMULTIDEFS;
7516 }
7517 if (f & MachO::MH_NOFIXPREBINDING) {
7518 outs() << " NOFIXPREBINDING";
7519 f &= ~MachO::MH_NOFIXPREBINDING;
7520 }
7521 if (f & MachO::MH_PREBINDABLE) {
7522 outs() << " PREBINDABLE";
7523 f &= ~MachO::MH_PREBINDABLE;
7524 }
7525 if (f & MachO::MH_ALLMODSBOUND) {
7526 outs() << " ALLMODSBOUND";
7527 f &= ~MachO::MH_ALLMODSBOUND;
7528 }
7529 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7530 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7531 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7532 }
7533 if (f & MachO::MH_CANONICAL) {
7534 outs() << " CANONICAL";
7535 f &= ~MachO::MH_CANONICAL;
7536 }
7537 if (f & MachO::MH_WEAK_DEFINES) {
7538 outs() << " WEAK_DEFINES";
7539 f &= ~MachO::MH_WEAK_DEFINES;
7540 }
7541 if (f & MachO::MH_BINDS_TO_WEAK) {
7542 outs() << " BINDS_TO_WEAK";
7543 f &= ~MachO::MH_BINDS_TO_WEAK;
7544 }
7545 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7546 outs() << " ALLOW_STACK_EXECUTION";
7547 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7548 }
7549 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7550 outs() << " DEAD_STRIPPABLE_DYLIB";
7551 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7552 }
7553 if (f & MachO::MH_PIE) {
7554 outs() << " PIE";
7555 f &= ~MachO::MH_PIE;
7556 }
7557 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7558 outs() << " NO_REEXPORTED_DYLIBS";
7559 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7560 }
7561 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7562 outs() << " MH_HAS_TLV_DESCRIPTORS";
7563 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7564 }
7565 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7566 outs() << " MH_NO_HEAP_EXECUTION";
7567 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7568 }
7569 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7570 outs() << " APP_EXTENSION_SAFE";
7571 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7572 }
7573 if (f != 0 || flags == 0)
7574 outs() << format(" 0x%08" PRIx32, f);
7575 } else {
7576 outs() << format(" 0x%08" PRIx32, magic);
7577 outs() << format(" %7d", cputype);
7578 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7579 outs() << format(" 0x%02" PRIx32,
7580 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7581 outs() << format(" %10u", filetype);
7582 outs() << format(" %5u", ncmds);
7583 outs() << format(" %10u", sizeofcmds);
7584 outs() << format(" 0x%08" PRIx32, flags);
7585 }
7586 outs() << "\n";
7587}
7588
Kevin Enderby956366c2014-08-29 22:30:52 +00007589static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7590 StringRef SegName, uint64_t vmaddr,
7591 uint64_t vmsize, uint64_t fileoff,
7592 uint64_t filesize, uint32_t maxprot,
7593 uint32_t initprot, uint32_t nsects,
7594 uint32_t flags, uint32_t object_size,
7595 bool verbose) {
7596 uint64_t expected_cmdsize;
7597 if (cmd == MachO::LC_SEGMENT) {
7598 outs() << " cmd LC_SEGMENT\n";
7599 expected_cmdsize = nsects;
7600 expected_cmdsize *= sizeof(struct MachO::section);
7601 expected_cmdsize += sizeof(struct MachO::segment_command);
7602 } else {
7603 outs() << " cmd LC_SEGMENT_64\n";
7604 expected_cmdsize = nsects;
7605 expected_cmdsize *= sizeof(struct MachO::section_64);
7606 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7607 }
7608 outs() << " cmdsize " << cmdsize;
7609 if (cmdsize != expected_cmdsize)
7610 outs() << " Inconsistent size\n";
7611 else
7612 outs() << "\n";
7613 outs() << " segname " << SegName << "\n";
7614 if (cmd == MachO::LC_SEGMENT_64) {
7615 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7616 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7617 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007618 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7619 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007620 }
7621 outs() << " fileoff " << fileoff;
7622 if (fileoff > object_size)
7623 outs() << " (past end of file)\n";
7624 else
7625 outs() << "\n";
7626 outs() << " filesize " << filesize;
7627 if (fileoff + filesize > object_size)
7628 outs() << " (past end of file)\n";
7629 else
7630 outs() << "\n";
7631 if (verbose) {
7632 if ((maxprot &
7633 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7634 MachO::VM_PROT_EXECUTE)) != 0)
7635 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7636 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007637 outs() << " maxprot ";
7638 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7639 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7640 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007641 }
7642 if ((initprot &
7643 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7644 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00007645 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007646 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00007647 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00007648 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7649 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7650 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007651 }
7652 } else {
7653 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7654 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7655 }
7656 outs() << " nsects " << nsects << "\n";
7657 if (verbose) {
7658 outs() << " flags";
7659 if (flags == 0)
7660 outs() << " (none)\n";
7661 else {
7662 if (flags & MachO::SG_HIGHVM) {
7663 outs() << " HIGHVM";
7664 flags &= ~MachO::SG_HIGHVM;
7665 }
7666 if (flags & MachO::SG_FVMLIB) {
7667 outs() << " FVMLIB";
7668 flags &= ~MachO::SG_FVMLIB;
7669 }
7670 if (flags & MachO::SG_NORELOC) {
7671 outs() << " NORELOC";
7672 flags &= ~MachO::SG_NORELOC;
7673 }
7674 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7675 outs() << " PROTECTED_VERSION_1";
7676 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7677 }
7678 if (flags)
7679 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7680 else
7681 outs() << "\n";
7682 }
7683 } else {
7684 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7685 }
7686}
7687
7688static void PrintSection(const char *sectname, const char *segname,
7689 uint64_t addr, uint64_t size, uint32_t offset,
7690 uint32_t align, uint32_t reloff, uint32_t nreloc,
7691 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7692 uint32_t cmd, const char *sg_segname,
7693 uint32_t filetype, uint32_t object_size,
7694 bool verbose) {
7695 outs() << "Section\n";
7696 outs() << " sectname " << format("%.16s\n", sectname);
7697 outs() << " segname " << format("%.16s", segname);
7698 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7699 outs() << " (does not match segment)\n";
7700 else
7701 outs() << "\n";
7702 if (cmd == MachO::LC_SEGMENT_64) {
7703 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7704 outs() << " size " << format("0x%016" PRIx64, size);
7705 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007706 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7707 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007708 }
7709 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7710 outs() << " (past end of file)\n";
7711 else
7712 outs() << "\n";
7713 outs() << " offset " << offset;
7714 if (offset > object_size)
7715 outs() << " (past end of file)\n";
7716 else
7717 outs() << "\n";
7718 uint32_t align_shifted = 1 << align;
7719 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7720 outs() << " reloff " << reloff;
7721 if (reloff > object_size)
7722 outs() << " (past end of file)\n";
7723 else
7724 outs() << "\n";
7725 outs() << " nreloc " << nreloc;
7726 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7727 outs() << " (past end of file)\n";
7728 else
7729 outs() << "\n";
7730 uint32_t section_type = flags & MachO::SECTION_TYPE;
7731 if (verbose) {
7732 outs() << " type";
7733 if (section_type == MachO::S_REGULAR)
7734 outs() << " S_REGULAR\n";
7735 else if (section_type == MachO::S_ZEROFILL)
7736 outs() << " S_ZEROFILL\n";
7737 else if (section_type == MachO::S_CSTRING_LITERALS)
7738 outs() << " S_CSTRING_LITERALS\n";
7739 else if (section_type == MachO::S_4BYTE_LITERALS)
7740 outs() << " S_4BYTE_LITERALS\n";
7741 else if (section_type == MachO::S_8BYTE_LITERALS)
7742 outs() << " S_8BYTE_LITERALS\n";
7743 else if (section_type == MachO::S_16BYTE_LITERALS)
7744 outs() << " S_16BYTE_LITERALS\n";
7745 else if (section_type == MachO::S_LITERAL_POINTERS)
7746 outs() << " S_LITERAL_POINTERS\n";
7747 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7748 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7749 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7750 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7751 else if (section_type == MachO::S_SYMBOL_STUBS)
7752 outs() << " S_SYMBOL_STUBS\n";
7753 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7754 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7755 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7756 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7757 else if (section_type == MachO::S_COALESCED)
7758 outs() << " S_COALESCED\n";
7759 else if (section_type == MachO::S_INTERPOSING)
7760 outs() << " S_INTERPOSING\n";
7761 else if (section_type == MachO::S_DTRACE_DOF)
7762 outs() << " S_DTRACE_DOF\n";
7763 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7764 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7765 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7766 outs() << " S_THREAD_LOCAL_REGULAR\n";
7767 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7768 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7769 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7770 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7771 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7772 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7773 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7774 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7775 else
7776 outs() << format("0x%08" PRIx32, section_type) << "\n";
7777 outs() << "attributes";
7778 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7779 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7780 outs() << " PURE_INSTRUCTIONS";
7781 if (section_attributes & MachO::S_ATTR_NO_TOC)
7782 outs() << " NO_TOC";
7783 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7784 outs() << " STRIP_STATIC_SYMS";
7785 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7786 outs() << " NO_DEAD_STRIP";
7787 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7788 outs() << " LIVE_SUPPORT";
7789 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7790 outs() << " SELF_MODIFYING_CODE";
7791 if (section_attributes & MachO::S_ATTR_DEBUG)
7792 outs() << " DEBUG";
7793 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7794 outs() << " SOME_INSTRUCTIONS";
7795 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7796 outs() << " EXT_RELOC";
7797 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7798 outs() << " LOC_RELOC";
7799 if (section_attributes == 0)
7800 outs() << " (none)";
7801 outs() << "\n";
7802 } else
7803 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7804 outs() << " reserved1 " << reserved1;
7805 if (section_type == MachO::S_SYMBOL_STUBS ||
7806 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7807 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7808 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7809 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7810 outs() << " (index into indirect symbol table)\n";
7811 else
7812 outs() << "\n";
7813 outs() << " reserved2 " << reserved2;
7814 if (section_type == MachO::S_SYMBOL_STUBS)
7815 outs() << " (size of stubs)\n";
7816 else
7817 outs() << "\n";
7818}
7819
David Majnemer73cc6ff2014-11-13 19:48:56 +00007820static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007821 uint32_t object_size) {
7822 outs() << " cmd LC_SYMTAB\n";
7823 outs() << " cmdsize " << st.cmdsize;
7824 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7825 outs() << " Incorrect size\n";
7826 else
7827 outs() << "\n";
7828 outs() << " symoff " << st.symoff;
7829 if (st.symoff > object_size)
7830 outs() << " (past end of file)\n";
7831 else
7832 outs() << "\n";
7833 outs() << " nsyms " << st.nsyms;
7834 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007835 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007836 big_size = st.nsyms;
7837 big_size *= sizeof(struct MachO::nlist_64);
7838 big_size += st.symoff;
7839 if (big_size > object_size)
7840 outs() << " (past end of file)\n";
7841 else
7842 outs() << "\n";
7843 } else {
7844 big_size = st.nsyms;
7845 big_size *= sizeof(struct MachO::nlist);
7846 big_size += st.symoff;
7847 if (big_size > object_size)
7848 outs() << " (past end of file)\n";
7849 else
7850 outs() << "\n";
7851 }
7852 outs() << " stroff " << st.stroff;
7853 if (st.stroff > object_size)
7854 outs() << " (past end of file)\n";
7855 else
7856 outs() << "\n";
7857 outs() << " strsize " << st.strsize;
7858 big_size = st.stroff;
7859 big_size += st.strsize;
7860 if (big_size > object_size)
7861 outs() << " (past end of file)\n";
7862 else
7863 outs() << "\n";
7864}
7865
7866static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7867 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007868 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007869 outs() << " cmd LC_DYSYMTAB\n";
7870 outs() << " cmdsize " << dyst.cmdsize;
7871 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7872 outs() << " Incorrect size\n";
7873 else
7874 outs() << "\n";
7875 outs() << " ilocalsym " << dyst.ilocalsym;
7876 if (dyst.ilocalsym > nsyms)
7877 outs() << " (greater than the number of symbols)\n";
7878 else
7879 outs() << "\n";
7880 outs() << " nlocalsym " << dyst.nlocalsym;
7881 uint64_t big_size;
7882 big_size = dyst.ilocalsym;
7883 big_size += dyst.nlocalsym;
7884 if (big_size > nsyms)
7885 outs() << " (past the end of the symbol table)\n";
7886 else
7887 outs() << "\n";
7888 outs() << " iextdefsym " << dyst.iextdefsym;
7889 if (dyst.iextdefsym > nsyms)
7890 outs() << " (greater than the number of symbols)\n";
7891 else
7892 outs() << "\n";
7893 outs() << " nextdefsym " << dyst.nextdefsym;
7894 big_size = dyst.iextdefsym;
7895 big_size += dyst.nextdefsym;
7896 if (big_size > nsyms)
7897 outs() << " (past the end of the symbol table)\n";
7898 else
7899 outs() << "\n";
7900 outs() << " iundefsym " << dyst.iundefsym;
7901 if (dyst.iundefsym > nsyms)
7902 outs() << " (greater than the number of symbols)\n";
7903 else
7904 outs() << "\n";
7905 outs() << " nundefsym " << dyst.nundefsym;
7906 big_size = dyst.iundefsym;
7907 big_size += dyst.nundefsym;
7908 if (big_size > nsyms)
7909 outs() << " (past the end of the symbol table)\n";
7910 else
7911 outs() << "\n";
7912 outs() << " tocoff " << dyst.tocoff;
7913 if (dyst.tocoff > object_size)
7914 outs() << " (past end of file)\n";
7915 else
7916 outs() << "\n";
7917 outs() << " ntoc " << dyst.ntoc;
7918 big_size = dyst.ntoc;
7919 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7920 big_size += dyst.tocoff;
7921 if (big_size > object_size)
7922 outs() << " (past end of file)\n";
7923 else
7924 outs() << "\n";
7925 outs() << " modtaboff " << dyst.modtaboff;
7926 if (dyst.modtaboff > object_size)
7927 outs() << " (past end of file)\n";
7928 else
7929 outs() << "\n";
7930 outs() << " nmodtab " << dyst.nmodtab;
7931 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007932 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007933 modtabend = dyst.nmodtab;
7934 modtabend *= sizeof(struct MachO::dylib_module_64);
7935 modtabend += dyst.modtaboff;
7936 } else {
7937 modtabend = dyst.nmodtab;
7938 modtabend *= sizeof(struct MachO::dylib_module);
7939 modtabend += dyst.modtaboff;
7940 }
7941 if (modtabend > object_size)
7942 outs() << " (past end of file)\n";
7943 else
7944 outs() << "\n";
7945 outs() << " extrefsymoff " << dyst.extrefsymoff;
7946 if (dyst.extrefsymoff > object_size)
7947 outs() << " (past end of file)\n";
7948 else
7949 outs() << "\n";
7950 outs() << " nextrefsyms " << dyst.nextrefsyms;
7951 big_size = dyst.nextrefsyms;
7952 big_size *= sizeof(struct MachO::dylib_reference);
7953 big_size += dyst.extrefsymoff;
7954 if (big_size > object_size)
7955 outs() << " (past end of file)\n";
7956 else
7957 outs() << "\n";
7958 outs() << " indirectsymoff " << dyst.indirectsymoff;
7959 if (dyst.indirectsymoff > object_size)
7960 outs() << " (past end of file)\n";
7961 else
7962 outs() << "\n";
7963 outs() << " nindirectsyms " << dyst.nindirectsyms;
7964 big_size = dyst.nindirectsyms;
7965 big_size *= sizeof(uint32_t);
7966 big_size += dyst.indirectsymoff;
7967 if (big_size > object_size)
7968 outs() << " (past end of file)\n";
7969 else
7970 outs() << "\n";
7971 outs() << " extreloff " << dyst.extreloff;
7972 if (dyst.extreloff > object_size)
7973 outs() << " (past end of file)\n";
7974 else
7975 outs() << "\n";
7976 outs() << " nextrel " << dyst.nextrel;
7977 big_size = dyst.nextrel;
7978 big_size *= sizeof(struct MachO::relocation_info);
7979 big_size += dyst.extreloff;
7980 if (big_size > object_size)
7981 outs() << " (past end of file)\n";
7982 else
7983 outs() << "\n";
7984 outs() << " locreloff " << dyst.locreloff;
7985 if (dyst.locreloff > object_size)
7986 outs() << " (past end of file)\n";
7987 else
7988 outs() << "\n";
7989 outs() << " nlocrel " << dyst.nlocrel;
7990 big_size = dyst.nlocrel;
7991 big_size *= sizeof(struct MachO::relocation_info);
7992 big_size += dyst.locreloff;
7993 if (big_size > object_size)
7994 outs() << " (past end of file)\n";
7995 else
7996 outs() << "\n";
7997}
7998
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007999static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8000 uint32_t object_size) {
8001 if (dc.cmd == MachO::LC_DYLD_INFO)
8002 outs() << " cmd LC_DYLD_INFO\n";
8003 else
8004 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8005 outs() << " cmdsize " << dc.cmdsize;
8006 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8007 outs() << " Incorrect size\n";
8008 else
8009 outs() << "\n";
8010 outs() << " rebase_off " << dc.rebase_off;
8011 if (dc.rebase_off > object_size)
8012 outs() << " (past end of file)\n";
8013 else
8014 outs() << "\n";
8015 outs() << " rebase_size " << dc.rebase_size;
8016 uint64_t big_size;
8017 big_size = dc.rebase_off;
8018 big_size += dc.rebase_size;
8019 if (big_size > object_size)
8020 outs() << " (past end of file)\n";
8021 else
8022 outs() << "\n";
8023 outs() << " bind_off " << dc.bind_off;
8024 if (dc.bind_off > object_size)
8025 outs() << " (past end of file)\n";
8026 else
8027 outs() << "\n";
8028 outs() << " bind_size " << dc.bind_size;
8029 big_size = dc.bind_off;
8030 big_size += dc.bind_size;
8031 if (big_size > object_size)
8032 outs() << " (past end of file)\n";
8033 else
8034 outs() << "\n";
8035 outs() << " weak_bind_off " << dc.weak_bind_off;
8036 if (dc.weak_bind_off > object_size)
8037 outs() << " (past end of file)\n";
8038 else
8039 outs() << "\n";
8040 outs() << " weak_bind_size " << dc.weak_bind_size;
8041 big_size = dc.weak_bind_off;
8042 big_size += dc.weak_bind_size;
8043 if (big_size > object_size)
8044 outs() << " (past end of file)\n";
8045 else
8046 outs() << "\n";
8047 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8048 if (dc.lazy_bind_off > object_size)
8049 outs() << " (past end of file)\n";
8050 else
8051 outs() << "\n";
8052 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8053 big_size = dc.lazy_bind_off;
8054 big_size += dc.lazy_bind_size;
8055 if (big_size > object_size)
8056 outs() << " (past end of file)\n";
8057 else
8058 outs() << "\n";
8059 outs() << " export_off " << dc.export_off;
8060 if (dc.export_off > object_size)
8061 outs() << " (past end of file)\n";
8062 else
8063 outs() << "\n";
8064 outs() << " export_size " << dc.export_size;
8065 big_size = dc.export_off;
8066 big_size += dc.export_size;
8067 if (big_size > object_size)
8068 outs() << " (past end of file)\n";
8069 else
8070 outs() << "\n";
8071}
8072
8073static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8074 const char *Ptr) {
8075 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8076 outs() << " cmd LC_ID_DYLINKER\n";
8077 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8078 outs() << " cmd LC_LOAD_DYLINKER\n";
8079 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8080 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8081 else
8082 outs() << " cmd ?(" << dyld.cmd << ")\n";
8083 outs() << " cmdsize " << dyld.cmdsize;
8084 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8085 outs() << " Incorrect size\n";
8086 else
8087 outs() << "\n";
8088 if (dyld.name >= dyld.cmdsize)
8089 outs() << " name ?(bad offset " << dyld.name << ")\n";
8090 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008091 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008092 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8093 }
8094}
8095
8096static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8097 outs() << " cmd LC_UUID\n";
8098 outs() << " cmdsize " << uuid.cmdsize;
8099 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8100 outs() << " Incorrect size\n";
8101 else
8102 outs() << "\n";
8103 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008104 for (int i = 0; i < 16; ++i) {
8105 outs() << format("%02" PRIX32, uuid.uuid[i]);
8106 if (i == 3 || i == 5 || i == 7 || i == 9)
8107 outs() << "-";
8108 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008109 outs() << "\n";
8110}
8111
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008112static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008113 outs() << " cmd LC_RPATH\n";
8114 outs() << " cmdsize " << rpath.cmdsize;
8115 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8116 outs() << " Incorrect size\n";
8117 else
8118 outs() << "\n";
8119 if (rpath.path >= rpath.cmdsize)
8120 outs() << " path ?(bad offset " << rpath.path << ")\n";
8121 else {
8122 const char *P = (const char *)(Ptr) + rpath.path;
8123 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8124 }
8125}
8126
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008127static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008128 StringRef LoadCmdName;
8129 switch (vd.cmd) {
8130 case MachO::LC_VERSION_MIN_MACOSX:
8131 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8132 break;
8133 case MachO::LC_VERSION_MIN_IPHONEOS:
8134 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8135 break;
8136 case MachO::LC_VERSION_MIN_TVOS:
8137 LoadCmdName = "LC_VERSION_MIN_TVOS";
8138 break;
8139 case MachO::LC_VERSION_MIN_WATCHOS:
8140 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8141 break;
8142 default:
8143 llvm_unreachable("Unknown version min load command");
8144 }
8145
8146 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008147 outs() << " cmdsize " << vd.cmdsize;
8148 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8149 outs() << " Incorrect size\n";
8150 else
8151 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008152 outs() << " version "
8153 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8154 << MachOObjectFile::getVersionMinMinor(vd, false);
8155 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8156 if (Update != 0)
8157 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008158 outs() << "\n";
8159 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008160 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008161 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008162 outs() << " sdk "
8163 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8164 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008165 }
Davide Italiano56baef32015-08-26 12:26:11 +00008166 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8167 if (Update != 0)
8168 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008169 outs() << "\n";
8170}
8171
Kevin Enderbya4579c42017-01-19 17:36:31 +00008172static void PrintNoteLoadCommand(MachO::note_command Nt) {
8173 outs() << " cmd LC_NOTE\n";
8174 outs() << " cmdsize " << Nt.cmdsize;
8175 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8176 outs() << " Incorrect size\n";
8177 else
8178 outs() << "\n";
8179 const char *d = Nt.data_owner;
8180 outs() << "data_owner " << format("%.16s\n", d);
8181 outs() << " offset " << Nt.offset << "\n";
8182 outs() << " size " << Nt.size << "\n";
8183}
8184
Steven Wu5b54a422017-01-23 20:07:55 +00008185static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8186 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8187 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8188 << "\n";
8189}
8190
8191static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8192 MachO::build_version_command bd) {
8193 outs() << " cmd LC_BUILD_VERSION\n";
8194 outs() << " cmdsize " << bd.cmdsize;
8195 if (bd.cmdsize !=
8196 sizeof(struct MachO::build_version_command) +
8197 bd.ntools * sizeof(struct MachO::build_tool_version))
8198 outs() << " Incorrect size\n";
8199 else
8200 outs() << "\n";
8201 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8202 << "\n";
8203 if (bd.sdk)
8204 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8205 << "\n";
8206 else
8207 outs() << " sdk n/a\n";
8208 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8209 << "\n";
8210 outs() << " ntools " << bd.ntools << "\n";
8211 for (unsigned i = 0; i < bd.ntools; ++i) {
8212 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8213 PrintBuildToolVersion(bv);
8214 }
8215}
8216
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008217static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8218 outs() << " cmd LC_SOURCE_VERSION\n";
8219 outs() << " cmdsize " << sd.cmdsize;
8220 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8221 outs() << " Incorrect size\n";
8222 else
8223 outs() << "\n";
8224 uint64_t a = (sd.version >> 40) & 0xffffff;
8225 uint64_t b = (sd.version >> 30) & 0x3ff;
8226 uint64_t c = (sd.version >> 20) & 0x3ff;
8227 uint64_t d = (sd.version >> 10) & 0x3ff;
8228 uint64_t e = sd.version & 0x3ff;
8229 outs() << " version " << a << "." << b;
8230 if (e != 0)
8231 outs() << "." << c << "." << d << "." << e;
8232 else if (d != 0)
8233 outs() << "." << c << "." << d;
8234 else if (c != 0)
8235 outs() << "." << c;
8236 outs() << "\n";
8237}
8238
8239static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8240 outs() << " cmd LC_MAIN\n";
8241 outs() << " cmdsize " << ep.cmdsize;
8242 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8243 outs() << " Incorrect size\n";
8244 else
8245 outs() << "\n";
8246 outs() << " entryoff " << ep.entryoff << "\n";
8247 outs() << " stacksize " << ep.stacksize << "\n";
8248}
8249
Kevin Enderby0804f4672014-12-16 23:25:52 +00008250static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8251 uint32_t object_size) {
8252 outs() << " cmd LC_ENCRYPTION_INFO\n";
8253 outs() << " cmdsize " << ec.cmdsize;
8254 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8255 outs() << " Incorrect size\n";
8256 else
8257 outs() << "\n";
8258 outs() << " cryptoff " << ec.cryptoff;
8259 if (ec.cryptoff > object_size)
8260 outs() << " (past end of file)\n";
8261 else
8262 outs() << "\n";
8263 outs() << " cryptsize " << ec.cryptsize;
8264 if (ec.cryptsize > object_size)
8265 outs() << " (past end of file)\n";
8266 else
8267 outs() << "\n";
8268 outs() << " cryptid " << ec.cryptid << "\n";
8269}
8270
Kevin Enderby57538292014-12-17 01:01:30 +00008271static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008272 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008273 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8274 outs() << " cmdsize " << ec.cmdsize;
8275 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8276 outs() << " Incorrect size\n";
8277 else
8278 outs() << "\n";
8279 outs() << " cryptoff " << ec.cryptoff;
8280 if (ec.cryptoff > object_size)
8281 outs() << " (past end of file)\n";
8282 else
8283 outs() << "\n";
8284 outs() << " cryptsize " << ec.cryptsize;
8285 if (ec.cryptsize > object_size)
8286 outs() << " (past end of file)\n";
8287 else
8288 outs() << "\n";
8289 outs() << " cryptid " << ec.cryptid << "\n";
8290 outs() << " pad " << ec.pad << "\n";
8291}
8292
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008293static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8294 const char *Ptr) {
8295 outs() << " cmd LC_LINKER_OPTION\n";
8296 outs() << " cmdsize " << lo.cmdsize;
8297 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8298 outs() << " Incorrect size\n";
8299 else
8300 outs() << "\n";
8301 outs() << " count " << lo.count << "\n";
8302 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8303 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8304 uint32_t i = 0;
8305 while (left > 0) {
8306 while (*string == '\0' && left > 0) {
8307 string++;
8308 left--;
8309 }
8310 if (left > 0) {
8311 i++;
8312 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008313 uint32_t NullPos = StringRef(string, left).find('\0');
8314 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008315 string += len;
8316 left -= len;
8317 }
8318 }
8319 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008320 outs() << " count " << lo.count << " does not match number of strings "
8321 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008322}
8323
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008324static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8325 const char *Ptr) {
8326 outs() << " cmd LC_SUB_FRAMEWORK\n";
8327 outs() << " cmdsize " << sub.cmdsize;
8328 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8329 outs() << " Incorrect size\n";
8330 else
8331 outs() << "\n";
8332 if (sub.umbrella < sub.cmdsize) {
8333 const char *P = Ptr + sub.umbrella;
8334 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8335 } else {
8336 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8337 }
8338}
8339
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008340static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8341 const char *Ptr) {
8342 outs() << " cmd LC_SUB_UMBRELLA\n";
8343 outs() << " cmdsize " << sub.cmdsize;
8344 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8345 outs() << " Incorrect size\n";
8346 else
8347 outs() << "\n";
8348 if (sub.sub_umbrella < sub.cmdsize) {
8349 const char *P = Ptr + sub.sub_umbrella;
8350 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8351 } else {
8352 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8353 }
8354}
8355
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008356static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008357 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008358 outs() << " cmd LC_SUB_LIBRARY\n";
8359 outs() << " cmdsize " << sub.cmdsize;
8360 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8361 outs() << " Incorrect size\n";
8362 else
8363 outs() << "\n";
8364 if (sub.sub_library < sub.cmdsize) {
8365 const char *P = Ptr + sub.sub_library;
8366 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8367 } else {
8368 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8369 }
8370}
8371
Kevin Enderby186eac32014-12-19 21:06:24 +00008372static void PrintSubClientCommand(MachO::sub_client_command sub,
8373 const char *Ptr) {
8374 outs() << " cmd LC_SUB_CLIENT\n";
8375 outs() << " cmdsize " << sub.cmdsize;
8376 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8377 outs() << " Incorrect size\n";
8378 else
8379 outs() << "\n";
8380 if (sub.client < sub.cmdsize) {
8381 const char *P = Ptr + sub.client;
8382 outs() << " client " << P << " (offset " << sub.client << ")\n";
8383 } else {
8384 outs() << " client ?(bad offset " << sub.client << ")\n";
8385 }
8386}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008387
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008388static void PrintRoutinesCommand(MachO::routines_command r) {
8389 outs() << " cmd LC_ROUTINES\n";
8390 outs() << " cmdsize " << r.cmdsize;
8391 if (r.cmdsize != sizeof(struct MachO::routines_command))
8392 outs() << " Incorrect size\n";
8393 else
8394 outs() << "\n";
8395 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8396 outs() << " init_module " << r.init_module << "\n";
8397 outs() << " reserved1 " << r.reserved1 << "\n";
8398 outs() << " reserved2 " << r.reserved2 << "\n";
8399 outs() << " reserved3 " << r.reserved3 << "\n";
8400 outs() << " reserved4 " << r.reserved4 << "\n";
8401 outs() << " reserved5 " << r.reserved5 << "\n";
8402 outs() << " reserved6 " << r.reserved6 << "\n";
8403}
8404
8405static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8406 outs() << " cmd LC_ROUTINES_64\n";
8407 outs() << " cmdsize " << r.cmdsize;
8408 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8409 outs() << " Incorrect size\n";
8410 else
8411 outs() << "\n";
8412 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8413 outs() << " init_module " << r.init_module << "\n";
8414 outs() << " reserved1 " << r.reserved1 << "\n";
8415 outs() << " reserved2 " << r.reserved2 << "\n";
8416 outs() << " reserved3 " << r.reserved3 << "\n";
8417 outs() << " reserved4 " << r.reserved4 << "\n";
8418 outs() << " reserved5 " << r.reserved5 << "\n";
8419 outs() << " reserved6 " << r.reserved6 << "\n";
8420}
8421
Kevin Enderby48ef5342014-12-23 22:56:39 +00008422static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8423 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8424 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8425 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8426 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8427 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8428 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8429 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8430 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8431 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8432 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8433 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8434 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8435 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8436 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8437 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8438 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8439 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8440 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8441 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8442 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8443 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8444}
8445
Kevin Enderby227df342014-12-23 23:43:59 +00008446static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008447 uint32_t f;
8448 outs() << "\t mmst_reg ";
8449 for (f = 0; f < 10; f++)
8450 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8451 outs() << "\n";
8452 outs() << "\t mmst_rsrv ";
8453 for (f = 0; f < 6; f++)
8454 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8455 outs() << "\n";
8456}
8457
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008458static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008459 uint32_t f;
8460 outs() << "\t xmm_reg ";
8461 for (f = 0; f < 16; f++)
8462 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8463 outs() << "\n";
8464}
8465
8466static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8467 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8468 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8469 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8470 outs() << " denorm " << fpu.fpu_fcw.denorm;
8471 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8472 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8473 outs() << " undfl " << fpu.fpu_fcw.undfl;
8474 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8475 outs() << "\t\t pc ";
8476 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8477 outs() << "FP_PREC_24B ";
8478 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8479 outs() << "FP_PREC_53B ";
8480 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8481 outs() << "FP_PREC_64B ";
8482 else
8483 outs() << fpu.fpu_fcw.pc << " ";
8484 outs() << "rc ";
8485 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8486 outs() << "FP_RND_NEAR ";
8487 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8488 outs() << "FP_RND_DOWN ";
8489 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8490 outs() << "FP_RND_UP ";
8491 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008492 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008493 outs() << "\n";
8494 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8495 outs() << " denorm " << fpu.fpu_fsw.denorm;
8496 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8497 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8498 outs() << " undfl " << fpu.fpu_fsw.undfl;
8499 outs() << " precis " << fpu.fpu_fsw.precis;
8500 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8501 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8502 outs() << " c0 " << fpu.fpu_fsw.c0;
8503 outs() << " c1 " << fpu.fpu_fsw.c1;
8504 outs() << " c2 " << fpu.fpu_fsw.c2;
8505 outs() << " tos " << fpu.fpu_fsw.tos;
8506 outs() << " c3 " << fpu.fpu_fsw.c3;
8507 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8508 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8509 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8510 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8511 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8512 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8513 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8514 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8515 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8516 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8517 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8518 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8519 outs() << "\n";
8520 outs() << "\t fpu_stmm0:\n";
8521 Print_mmst_reg(fpu.fpu_stmm0);
8522 outs() << "\t fpu_stmm1:\n";
8523 Print_mmst_reg(fpu.fpu_stmm1);
8524 outs() << "\t fpu_stmm2:\n";
8525 Print_mmst_reg(fpu.fpu_stmm2);
8526 outs() << "\t fpu_stmm3:\n";
8527 Print_mmst_reg(fpu.fpu_stmm3);
8528 outs() << "\t fpu_stmm4:\n";
8529 Print_mmst_reg(fpu.fpu_stmm4);
8530 outs() << "\t fpu_stmm5:\n";
8531 Print_mmst_reg(fpu.fpu_stmm5);
8532 outs() << "\t fpu_stmm6:\n";
8533 Print_mmst_reg(fpu.fpu_stmm6);
8534 outs() << "\t fpu_stmm7:\n";
8535 Print_mmst_reg(fpu.fpu_stmm7);
8536 outs() << "\t fpu_xmm0:\n";
8537 Print_xmm_reg(fpu.fpu_xmm0);
8538 outs() << "\t fpu_xmm1:\n";
8539 Print_xmm_reg(fpu.fpu_xmm1);
8540 outs() << "\t fpu_xmm2:\n";
8541 Print_xmm_reg(fpu.fpu_xmm2);
8542 outs() << "\t fpu_xmm3:\n";
8543 Print_xmm_reg(fpu.fpu_xmm3);
8544 outs() << "\t fpu_xmm4:\n";
8545 Print_xmm_reg(fpu.fpu_xmm4);
8546 outs() << "\t fpu_xmm5:\n";
8547 Print_xmm_reg(fpu.fpu_xmm5);
8548 outs() << "\t fpu_xmm6:\n";
8549 Print_xmm_reg(fpu.fpu_xmm6);
8550 outs() << "\t fpu_xmm7:\n";
8551 Print_xmm_reg(fpu.fpu_xmm7);
8552 outs() << "\t fpu_xmm8:\n";
8553 Print_xmm_reg(fpu.fpu_xmm8);
8554 outs() << "\t fpu_xmm9:\n";
8555 Print_xmm_reg(fpu.fpu_xmm9);
8556 outs() << "\t fpu_xmm10:\n";
8557 Print_xmm_reg(fpu.fpu_xmm10);
8558 outs() << "\t fpu_xmm11:\n";
8559 Print_xmm_reg(fpu.fpu_xmm11);
8560 outs() << "\t fpu_xmm12:\n";
8561 Print_xmm_reg(fpu.fpu_xmm12);
8562 outs() << "\t fpu_xmm13:\n";
8563 Print_xmm_reg(fpu.fpu_xmm13);
8564 outs() << "\t fpu_xmm14:\n";
8565 Print_xmm_reg(fpu.fpu_xmm14);
8566 outs() << "\t fpu_xmm15:\n";
8567 Print_xmm_reg(fpu.fpu_xmm15);
8568 outs() << "\t fpu_rsrv4:\n";
8569 for (uint32_t f = 0; f < 6; f++) {
8570 outs() << "\t ";
8571 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008572 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008573 outs() << "\n";
8574 }
8575 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8576 outs() << "\n";
8577}
8578
8579static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8580 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8581 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8582 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8583}
8584
Kevin Enderby41c9c002016-10-21 18:22:35 +00008585static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
8586 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
8587 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
8588 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
8589 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
8590 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
8591 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
8592 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
8593 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
8594 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
8595 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
8596 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
8597 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
8598 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
8599 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
8600 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
8601 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
8602 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
8603}
8604
Kevin Enderby7747cb52016-11-03 20:51:28 +00008605static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
8606 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
8607 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
8608 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
8609 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
8610 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
8611 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
8612 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
8613 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
8614 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
8615 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
8616 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
8617 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
8618 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
8619 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
8620 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
8621 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
8622 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
8623 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
8624 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
8625 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
8626 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
8627 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
8628 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
8629 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
8630 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
8631 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
8632 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
8633 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
8634 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
8635 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
8636 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
8637 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
8638 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
8639 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
8640}
8641
Kevin Enderby48ef5342014-12-23 22:56:39 +00008642static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8643 bool isLittleEndian, uint32_t cputype) {
8644 if (t.cmd == MachO::LC_THREAD)
8645 outs() << " cmd LC_THREAD\n";
8646 else if (t.cmd == MachO::LC_UNIXTHREAD)
8647 outs() << " cmd LC_UNIXTHREAD\n";
8648 else
8649 outs() << " cmd " << t.cmd << " (unknown)\n";
8650 outs() << " cmdsize " << t.cmdsize;
8651 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8652 outs() << " Incorrect size\n";
8653 else
8654 outs() << "\n";
8655
8656 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8657 const char *end = Ptr + t.cmdsize;
8658 uint32_t flavor, count, left;
8659 if (cputype == MachO::CPU_TYPE_X86_64) {
8660 while (begin < end) {
8661 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8662 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8663 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008664 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008665 flavor = 0;
8666 begin = end;
8667 }
8668 if (isLittleEndian != sys::IsLittleEndianHost)
8669 sys::swapByteOrder(flavor);
8670 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8671 memcpy((char *)&count, begin, sizeof(uint32_t));
8672 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008673 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008674 count = 0;
8675 begin = end;
8676 }
8677 if (isLittleEndian != sys::IsLittleEndianHost)
8678 sys::swapByteOrder(count);
8679 if (flavor == MachO::x86_THREAD_STATE64) {
8680 outs() << " flavor x86_THREAD_STATE64\n";
8681 if (count == MachO::x86_THREAD_STATE64_COUNT)
8682 outs() << " count x86_THREAD_STATE64_COUNT\n";
8683 else
8684 outs() << " count " << count
8685 << " (not x86_THREAD_STATE64_COUNT)\n";
8686 MachO::x86_thread_state64_t cpu64;
8687 left = end - begin;
8688 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8689 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8690 begin += sizeof(MachO::x86_thread_state64_t);
8691 } else {
8692 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8693 memcpy(&cpu64, begin, left);
8694 begin += left;
8695 }
8696 if (isLittleEndian != sys::IsLittleEndianHost)
8697 swapStruct(cpu64);
8698 Print_x86_thread_state64_t(cpu64);
8699 } else if (flavor == MachO::x86_THREAD_STATE) {
8700 outs() << " flavor x86_THREAD_STATE\n";
8701 if (count == MachO::x86_THREAD_STATE_COUNT)
8702 outs() << " count x86_THREAD_STATE_COUNT\n";
8703 else
8704 outs() << " count " << count
8705 << " (not x86_THREAD_STATE_COUNT)\n";
8706 struct MachO::x86_thread_state_t ts;
8707 left = end - begin;
8708 if (left >= sizeof(MachO::x86_thread_state_t)) {
8709 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8710 begin += sizeof(MachO::x86_thread_state_t);
8711 } else {
8712 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8713 memcpy(&ts, begin, left);
8714 begin += left;
8715 }
8716 if (isLittleEndian != sys::IsLittleEndianHost)
8717 swapStruct(ts);
8718 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8719 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8720 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8721 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8722 else
8723 outs() << "tsh.count " << ts.tsh.count
8724 << " (not x86_THREAD_STATE64_COUNT\n";
8725 Print_x86_thread_state64_t(ts.uts.ts64);
8726 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008727 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8728 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008729 }
8730 } else if (flavor == MachO::x86_FLOAT_STATE) {
8731 outs() << " flavor x86_FLOAT_STATE\n";
8732 if (count == MachO::x86_FLOAT_STATE_COUNT)
8733 outs() << " count x86_FLOAT_STATE_COUNT\n";
8734 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008735 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008736 struct MachO::x86_float_state_t fs;
8737 left = end - begin;
8738 if (left >= sizeof(MachO::x86_float_state_t)) {
8739 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8740 begin += sizeof(MachO::x86_float_state_t);
8741 } else {
8742 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8743 memcpy(&fs, begin, left);
8744 begin += left;
8745 }
8746 if (isLittleEndian != sys::IsLittleEndianHost)
8747 swapStruct(fs);
8748 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8749 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008750 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008751 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8752 else
8753 outs() << "fsh.count " << fs.fsh.count
8754 << " (not x86_FLOAT_STATE64_COUNT\n";
8755 Print_x86_float_state_t(fs.ufs.fs64);
8756 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008757 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8758 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008759 }
8760 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8761 outs() << " flavor x86_EXCEPTION_STATE\n";
8762 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8763 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8764 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008765 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008766 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8767 struct MachO::x86_exception_state_t es;
8768 left = end - begin;
8769 if (left >= sizeof(MachO::x86_exception_state_t)) {
8770 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8771 begin += sizeof(MachO::x86_exception_state_t);
8772 } else {
8773 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8774 memcpy(&es, begin, left);
8775 begin += left;
8776 }
8777 if (isLittleEndian != sys::IsLittleEndianHost)
8778 swapStruct(es);
8779 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8780 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008781 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008782 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8783 else
8784 outs() << "\t esh.count " << es.esh.count
8785 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8786 Print_x86_exception_state_t(es.ues.es64);
8787 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008788 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8789 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008790 }
8791 } else {
8792 outs() << " flavor " << flavor << " (unknown)\n";
8793 outs() << " count " << count << "\n";
8794 outs() << " state (unknown)\n";
8795 begin += count * sizeof(uint32_t);
8796 }
8797 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00008798 } else if (cputype == MachO::CPU_TYPE_ARM) {
8799 while (begin < end) {
8800 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8801 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8802 begin += sizeof(uint32_t);
8803 } else {
8804 flavor = 0;
8805 begin = end;
8806 }
8807 if (isLittleEndian != sys::IsLittleEndianHost)
8808 sys::swapByteOrder(flavor);
8809 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8810 memcpy((char *)&count, begin, sizeof(uint32_t));
8811 begin += sizeof(uint32_t);
8812 } else {
8813 count = 0;
8814 begin = end;
8815 }
8816 if (isLittleEndian != sys::IsLittleEndianHost)
8817 sys::swapByteOrder(count);
8818 if (flavor == MachO::ARM_THREAD_STATE) {
8819 outs() << " flavor ARM_THREAD_STATE\n";
8820 if (count == MachO::ARM_THREAD_STATE_COUNT)
8821 outs() << " count ARM_THREAD_STATE_COUNT\n";
8822 else
8823 outs() << " count " << count
8824 << " (not ARM_THREAD_STATE_COUNT)\n";
8825 MachO::arm_thread_state32_t cpu32;
8826 left = end - begin;
8827 if (left >= sizeof(MachO::arm_thread_state32_t)) {
8828 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
8829 begin += sizeof(MachO::arm_thread_state32_t);
8830 } else {
8831 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
8832 memcpy(&cpu32, begin, left);
8833 begin += left;
8834 }
8835 if (isLittleEndian != sys::IsLittleEndianHost)
8836 swapStruct(cpu32);
8837 Print_arm_thread_state32_t(cpu32);
8838 } else {
8839 outs() << " flavor " << flavor << " (unknown)\n";
8840 outs() << " count " << count << "\n";
8841 outs() << " state (unknown)\n";
8842 begin += count * sizeof(uint32_t);
8843 }
8844 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00008845 } else if (cputype == MachO::CPU_TYPE_ARM64) {
8846 while (begin < end) {
8847 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8848 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8849 begin += sizeof(uint32_t);
8850 } else {
8851 flavor = 0;
8852 begin = end;
8853 }
8854 if (isLittleEndian != sys::IsLittleEndianHost)
8855 sys::swapByteOrder(flavor);
8856 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8857 memcpy((char *)&count, begin, sizeof(uint32_t));
8858 begin += sizeof(uint32_t);
8859 } else {
8860 count = 0;
8861 begin = end;
8862 }
8863 if (isLittleEndian != sys::IsLittleEndianHost)
8864 sys::swapByteOrder(count);
8865 if (flavor == MachO::ARM_THREAD_STATE64) {
8866 outs() << " flavor ARM_THREAD_STATE64\n";
8867 if (count == MachO::ARM_THREAD_STATE64_COUNT)
8868 outs() << " count ARM_THREAD_STATE64_COUNT\n";
8869 else
8870 outs() << " count " << count
8871 << " (not ARM_THREAD_STATE64_COUNT)\n";
8872 MachO::arm_thread_state64_t cpu64;
8873 left = end - begin;
8874 if (left >= sizeof(MachO::arm_thread_state64_t)) {
8875 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
8876 begin += sizeof(MachO::arm_thread_state64_t);
8877 } else {
8878 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
8879 memcpy(&cpu64, begin, left);
8880 begin += left;
8881 }
8882 if (isLittleEndian != sys::IsLittleEndianHost)
8883 swapStruct(cpu64);
8884 Print_arm_thread_state64_t(cpu64);
8885 } else {
8886 outs() << " flavor " << flavor << " (unknown)\n";
8887 outs() << " count " << count << "\n";
8888 outs() << " state (unknown)\n";
8889 begin += count * sizeof(uint32_t);
8890 }
8891 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00008892 } else {
8893 while (begin < end) {
8894 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8895 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8896 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008897 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008898 flavor = 0;
8899 begin = end;
8900 }
8901 if (isLittleEndian != sys::IsLittleEndianHost)
8902 sys::swapByteOrder(flavor);
8903 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8904 memcpy((char *)&count, begin, sizeof(uint32_t));
8905 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008906 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008907 count = 0;
8908 begin = end;
8909 }
8910 if (isLittleEndian != sys::IsLittleEndianHost)
8911 sys::swapByteOrder(count);
8912 outs() << " flavor " << flavor << "\n";
8913 outs() << " count " << count << "\n";
8914 outs() << " state (Unknown cputype/cpusubtype)\n";
8915 begin += count * sizeof(uint32_t);
8916 }
8917 }
8918}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008919
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008920static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8921 if (dl.cmd == MachO::LC_ID_DYLIB)
8922 outs() << " cmd LC_ID_DYLIB\n";
8923 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8924 outs() << " cmd LC_LOAD_DYLIB\n";
8925 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8926 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8927 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8928 outs() << " cmd LC_REEXPORT_DYLIB\n";
8929 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8930 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8931 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8932 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8933 else
8934 outs() << " cmd " << dl.cmd << " (unknown)\n";
8935 outs() << " cmdsize " << dl.cmdsize;
8936 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8937 outs() << " Incorrect size\n";
8938 else
8939 outs() << "\n";
8940 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008941 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008942 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8943 } else {
8944 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8945 }
8946 outs() << " time stamp " << dl.dylib.timestamp << " ";
8947 time_t t = dl.dylib.timestamp;
8948 outs() << ctime(&t);
8949 outs() << " current version ";
8950 if (dl.dylib.current_version == 0xffffffff)
8951 outs() << "n/a\n";
8952 else
8953 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8954 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8955 << (dl.dylib.current_version & 0xff) << "\n";
8956 outs() << "compatibility version ";
8957 if (dl.dylib.compatibility_version == 0xffffffff)
8958 outs() << "n/a\n";
8959 else
8960 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8961 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8962 << (dl.dylib.compatibility_version & 0xff) << "\n";
8963}
8964
8965static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8966 uint32_t object_size) {
8967 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00008968 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008969 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8970 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8971 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8972 outs() << " cmd LC_FUNCTION_STARTS\n";
8973 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8974 outs() << " cmd LC_DATA_IN_CODE\n";
8975 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8976 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8977 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8978 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8979 else
8980 outs() << " cmd " << ld.cmd << " (?)\n";
8981 outs() << " cmdsize " << ld.cmdsize;
8982 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8983 outs() << " Incorrect size\n";
8984 else
8985 outs() << "\n";
8986 outs() << " dataoff " << ld.dataoff;
8987 if (ld.dataoff > object_size)
8988 outs() << " (past end of file)\n";
8989 else
8990 outs() << "\n";
8991 outs() << " datasize " << ld.datasize;
8992 uint64_t big_size = ld.dataoff;
8993 big_size += ld.datasize;
8994 if (big_size > object_size)
8995 outs() << " (past end of file)\n";
8996 else
8997 outs() << "\n";
8998}
8999
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009000static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9001 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009002 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009003 unsigned Index = 0;
9004 for (const auto &Command : Obj->load_commands()) {
9005 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009006 if (Command.C.cmd == MachO::LC_SEGMENT) {
9007 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9008 const char *sg_segname = SLC.segname;
9009 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9010 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9011 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9012 verbose);
9013 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009014 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009015 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9016 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9017 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9018 }
9019 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9020 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9021 const char *sg_segname = SLC_64.segname;
9022 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9023 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9024 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9025 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9026 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9027 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9028 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9029 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9030 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9031 sg_segname, filetype, Buf.size(), verbose);
9032 }
9033 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9034 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009035 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009036 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9037 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9038 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009039 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9040 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009041 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9042 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9043 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9044 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9045 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9046 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9047 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9048 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9049 PrintDyldLoadCommand(Dyld, Command.Ptr);
9050 } else if (Command.C.cmd == MachO::LC_UUID) {
9051 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9052 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009053 } else if (Command.C.cmd == MachO::LC_RPATH) {
9054 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9055 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009056 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009057 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9058 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9059 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009060 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9061 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009062 } else if (Command.C.cmd == MachO::LC_NOTE) {
9063 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9064 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009065 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9066 MachO::build_version_command Bv =
9067 Obj->getBuildVersionLoadCommand(Command);
9068 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009069 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9070 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9071 PrintSourceVersionCommand(Sd);
9072 } else if (Command.C.cmd == MachO::LC_MAIN) {
9073 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9074 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009075 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009076 MachO::encryption_info_command Ei =
9077 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009078 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009079 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009080 MachO::encryption_info_command_64 Ei =
9081 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009082 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009083 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009084 MachO::linker_option_command Lo =
9085 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009086 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009087 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9088 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9089 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009090 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9091 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9092 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009093 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9094 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9095 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009096 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9097 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9098 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009099 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9100 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9101 PrintRoutinesCommand(Rc);
9102 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9103 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9104 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009105 } else if (Command.C.cmd == MachO::LC_THREAD ||
9106 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9107 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9108 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009109 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9110 Command.C.cmd == MachO::LC_ID_DYLIB ||
9111 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9112 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9113 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9114 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009115 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9116 PrintDylibCommand(Dl, Command.Ptr);
9117 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9118 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9119 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9120 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9121 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9122 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9123 MachO::linkedit_data_command Ld =
9124 Obj->getLinkeditDataLoadCommand(Command);
9125 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009126 } else {
9127 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9128 << ")\n";
9129 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9130 // TODO: get and print the raw bytes of the load command.
9131 }
9132 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009133 }
9134}
9135
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009136static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009137 if (Obj->is64Bit()) {
9138 MachO::mach_header_64 H_64;
9139 H_64 = Obj->getHeader64();
9140 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9141 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9142 } else {
9143 MachO::mach_header H;
9144 H = Obj->getHeader();
9145 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9146 H.sizeofcmds, H.flags, verbose);
9147 }
9148}
9149
9150void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9151 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009152 PrintMachHeader(file, !NonVerbose);
9153}
9154
9155void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9156 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009157 uint32_t filetype = 0;
9158 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009159 if (file->is64Bit()) {
9160 MachO::mach_header_64 H_64;
9161 H_64 = file->getHeader64();
9162 filetype = H_64.filetype;
9163 cputype = H_64.cputype;
9164 } else {
9165 MachO::mach_header H;
9166 H = file->getHeader();
9167 filetype = H.filetype;
9168 cputype = H.cputype;
9169 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009170 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009171}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009172
9173//===----------------------------------------------------------------------===//
9174// export trie dumping
9175//===----------------------------------------------------------------------===//
9176
9177void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009178 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9179 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009180 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9181 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9182 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9183 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9184 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9185 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9186 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9187 if (ReExport)
9188 outs() << "[re-export] ";
9189 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009190 outs() << format("0x%08llX ",
9191 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009192 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009193 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009194 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009195 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009196 if (WeakDef) {
9197 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009198 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009199 }
9200 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009201 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009202 outs() << ", ";
9203 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009204 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009205 }
9206 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009207 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009208 outs() << ", ";
9209 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009210 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009211 }
9212 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009213 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009214 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009215 outs() << format("resolver=0x%08llX", Entry.other());
9216 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009217 }
9218 outs() << "]";
9219 }
9220 if (ReExport) {
9221 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009222 int Ordinal = Entry.other() - 1;
9223 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9224 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009225 outs() << " (from " << DylibName << ")";
9226 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009227 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009228 }
9229 outs() << "\n";
9230 }
9231}
Nick Kledzikac431442014-09-12 21:34:15 +00009232
Nick Kledzikac431442014-09-12 21:34:15 +00009233//===----------------------------------------------------------------------===//
9234// rebase table dumping
9235//===----------------------------------------------------------------------===//
9236
9237namespace {
9238class SegInfo {
9239public:
9240 SegInfo(const object::MachOObjectFile *Obj);
9241
9242 StringRef segmentName(uint32_t SegIndex);
9243 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9244 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009245 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00009246
9247private:
9248 struct SectionInfo {
9249 uint64_t Address;
9250 uint64_t Size;
9251 StringRef SectionName;
9252 StringRef SegmentName;
9253 uint64_t OffsetInSegment;
9254 uint64_t SegmentStartAddress;
9255 uint32_t SegmentIndex;
9256 };
9257 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9258 SmallVector<SectionInfo, 32> Sections;
9259};
9260}
9261
9262SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9263 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00009264 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00009265 StringRef CurSegName;
9266 uint64_t CurSegAddress;
9267 for (const SectionRef &Section : Obj->sections()) {
9268 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00009269 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00009270 Info.Address = Section.getAddress();
9271 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00009272 Info.SegmentName =
9273 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9274 if (!Info.SegmentName.equals(CurSegName)) {
9275 ++CurSegIndex;
9276 CurSegName = Info.SegmentName;
9277 CurSegAddress = Info.Address;
9278 }
9279 Info.SegmentIndex = CurSegIndex - 1;
9280 Info.OffsetInSegment = Info.Address - CurSegAddress;
9281 Info.SegmentStartAddress = CurSegAddress;
9282 Sections.push_back(Info);
9283 }
9284}
9285
9286StringRef SegInfo::segmentName(uint32_t SegIndex) {
9287 for (const SectionInfo &SI : Sections) {
9288 if (SI.SegmentIndex == SegIndex)
9289 return SI.SegmentName;
9290 }
9291 llvm_unreachable("invalid segIndex");
9292}
9293
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009294bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9295 uint64_t OffsetInSeg) {
9296 for (const SectionInfo &SI : Sections) {
9297 if (SI.SegmentIndex != SegIndex)
9298 continue;
9299 if (SI.OffsetInSegment > OffsetInSeg)
9300 continue;
9301 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9302 continue;
9303 return true;
9304 }
9305 return false;
9306}
9307
Nick Kledzikac431442014-09-12 21:34:15 +00009308const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9309 uint64_t OffsetInSeg) {
9310 for (const SectionInfo &SI : Sections) {
9311 if (SI.SegmentIndex != SegIndex)
9312 continue;
9313 if (SI.OffsetInSegment > OffsetInSeg)
9314 continue;
9315 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9316 continue;
9317 return SI;
9318 }
9319 llvm_unreachable("segIndex and offset not in any section");
9320}
9321
9322StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9323 return findSection(SegIndex, OffsetInSeg).SectionName;
9324}
9325
9326uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9327 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9328 return SI.SegmentStartAddress + OffsetInSeg;
9329}
9330
9331void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9332 // Build table of sections so names can used in final output.
9333 SegInfo sectionTable(Obj);
9334
9335 outs() << "segment section address type\n";
9336 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9337 uint32_t SegIndex = Entry.segmentIndex();
9338 uint64_t OffsetInSeg = Entry.segmentOffset();
9339 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9340 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9341 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9342
9343 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009344 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9345 SegmentName.str().c_str(), SectionName.str().c_str(),
9346 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009347 }
9348}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009349
9350static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9351 StringRef DylibName;
9352 switch (Ordinal) {
9353 case MachO::BIND_SPECIAL_DYLIB_SELF:
9354 return "this-image";
9355 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9356 return "main-executable";
9357 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9358 return "flat-namespace";
9359 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009360 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009361 std::error_code EC =
9362 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009363 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009364 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009365 return DylibName;
9366 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009367 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009368 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009369}
9370
9371//===----------------------------------------------------------------------===//
9372// bind table dumping
9373//===----------------------------------------------------------------------===//
9374
9375void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9376 // Build table of sections so names can used in final output.
9377 SegInfo sectionTable(Obj);
9378
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009379 outs() << "segment section address type "
9380 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009381 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9382 uint32_t SegIndex = Entry.segmentIndex();
9383 uint64_t OffsetInSeg = Entry.segmentOffset();
9384 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9385 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9386 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9387
9388 // Table lines look like:
9389 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009390 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009391 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009392 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009393 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009394 << left_justify(SectionName, 18) << " "
9395 << format_hex(Address, 10, true) << " "
9396 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009397 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009398 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009399 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009400 }
9401}
9402
9403//===----------------------------------------------------------------------===//
9404// lazy bind table dumping
9405//===----------------------------------------------------------------------===//
9406
9407void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9408 // Build table of sections so names can used in final output.
9409 SegInfo sectionTable(Obj);
9410
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009411 outs() << "segment section address "
9412 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009413 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9414 uint32_t SegIndex = Entry.segmentIndex();
9415 uint64_t OffsetInSeg = Entry.segmentOffset();
9416 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9417 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9418 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9419
9420 // Table lines look like:
9421 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009422 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009423 << left_justify(SectionName, 18) << " "
9424 << format_hex(Address, 10, true) << " "
9425 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009426 << Entry.symbolName() << "\n";
9427 }
9428}
9429
Nick Kledzik56ebef42014-09-16 01:41:51 +00009430//===----------------------------------------------------------------------===//
9431// weak bind table dumping
9432//===----------------------------------------------------------------------===//
9433
9434void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9435 // Build table of sections so names can used in final output.
9436 SegInfo sectionTable(Obj);
9437
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009438 outs() << "segment section address "
9439 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009440 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9441 // Strong symbols don't have a location to update.
9442 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009443 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009444 << Entry.symbolName() << "\n";
9445 continue;
9446 }
9447 uint32_t SegIndex = Entry.segmentIndex();
9448 uint64_t OffsetInSeg = Entry.segmentOffset();
9449 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9450 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9451 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9452
9453 // Table lines look like:
9454 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009455 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009456 << left_justify(SectionName, 18) << " "
9457 << format_hex(Address, 10, true) << " "
9458 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009459 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9460 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009461 }
9462}
9463
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009464// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9465// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9466// information for that address. If the address is found its binding symbol
9467// name is returned. If not nullptr is returned.
9468static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9469 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009470 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009471 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009472 SegInfo sectionTable(info->O);
9473 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9474 uint32_t SegIndex = Entry.segmentIndex();
9475 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009476 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
9477 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009478 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009479 StringRef name = Entry.symbolName();
9480 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009481 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009482 }
9483 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009484 auto name = info->bindtable->lookup(ReferenceValue);
9485 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009486}