blob: df1b74400ab2a8c98d66ced1ea27e036c716b43b [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());
Kevin Enderby418659f2017-02-06 21:01:08 +00001145 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001146 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);
Kevin Enderby98898f22017-01-30 20:53:17 +00001569 if (!BinaryOrErr) {
1570 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1571 report_error(Filename, std::move(E));
1572 else
1573 outs() << Filename << ": is not an object file\n";
1574 return;
1575 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001576 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001577
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001578 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1579 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001580 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001581 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1582
Mehdi Amini41af4302016-11-11 04:28:40 +00001583 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001584 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001585 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1586 if (!ChildOrErr) {
1587 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1588 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001589 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001590 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001591 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1592 if (!checkMachOAndArchFlags(O, Filename))
1593 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001594 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001595 }
1596 }
Lang Hamesfc209622016-07-14 02:24:01 +00001597 if (Err)
1598 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001599 return;
1600 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001601 if (UniversalHeaders) {
1602 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001603 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001604 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001605 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1606 // If we have a list of architecture flags specified dump only those.
1607 if (!ArchAll && ArchFlags.size() != 0) {
1608 // Look for a slice in the universal binary that matches each ArchFlag.
1609 bool ArchFound;
1610 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1611 ArchFound = false;
1612 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1613 E = UB->end_objects();
1614 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001615 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001616 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001617 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001618 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001619 std::string ArchitectureName = "";
1620 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +00001621 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001622 if (ObjOrErr) {
1623 ObjectFile &O = *ObjOrErr.get();
1624 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001625 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001626 } else if (auto E = isNotObjectErrorInvalidFileType(
1627 ObjOrErr.takeError())) {
1628 report_error(Filename, StringRef(), std::move(E),
1629 ArchitectureName);
1630 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001631 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001632 I->getAsArchive()) {
1633 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001634 outs() << "Archive : " << Filename;
1635 if (!ArchitectureName.empty())
1636 outs() << " (architecture " << ArchitectureName << ")";
1637 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001638 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001639 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1640 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001641 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001642 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001643 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1644 if (!ChildOrErr) {
1645 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001646 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001647 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001648 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001649 if (MachOObjectFile *O =
1650 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001651 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001652 }
Lang Hamesfc209622016-07-14 02:24:01 +00001653 if (Err)
1654 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001655 } else {
1656 consumeError(AOrErr.takeError());
1657 error("Mach-O universal file: " + Filename + " for " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001658 "architecture " + StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001659 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001660 }
1661 }
1662 }
1663 if (!ArchFound) {
1664 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1665 << "architecture: " + ArchFlags[i] + "\n";
1666 return;
1667 }
1668 }
1669 return;
1670 }
1671 // No architecture flags were specified so if this contains a slice that
1672 // matches the host architecture dump only that.
1673 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001674 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1675 E = UB->end_objects();
1676 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001677 if (MachOObjectFile::getHostArch().getArchName() ==
Kevin Enderby59343a92016-12-16 22:54:02 +00001678 I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001679 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001680 std::string ArchiveName;
1681 ArchiveName.clear();
1682 if (ObjOrErr) {
1683 ObjectFile &O = *ObjOrErr.get();
1684 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001685 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001686 } else if (auto E = isNotObjectErrorInvalidFileType(
1687 ObjOrErr.takeError())) {
1688 report_error(Filename, std::move(E));
1689 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001690 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001691 I->getAsArchive()) {
1692 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001693 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001694 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001695 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1696 ArchiveMemberOffsets);
Mehdi Amini41af4302016-11-11 04:28:40 +00001697 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001698 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001699 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1700 if (!ChildOrErr) {
1701 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1702 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001703 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001704 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001705 if (MachOObjectFile *O =
1706 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001707 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001708 }
Lang Hamesfc209622016-07-14 02:24:01 +00001709 if (Err)
1710 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001711 } else {
1712 consumeError(AOrErr.takeError());
1713 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001714 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001715 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001716 }
1717 return;
1718 }
1719 }
1720 }
1721 // Either all architectures have been specified or none have been specified
1722 // and this does not contain the host architecture so dump all the slices.
1723 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1724 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1725 E = UB->end_objects();
1726 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001727 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001728 std::string ArchitectureName = "";
1729 if (moreThanOneArch)
Kevin Enderby59343a92016-12-16 22:54:02 +00001730 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001731 if (ObjOrErr) {
1732 ObjectFile &Obj = *ObjOrErr.get();
1733 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001734 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001735 } else if (auto E = isNotObjectErrorInvalidFileType(
1736 ObjOrErr.takeError())) {
1737 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1738 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001739 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1740 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001741 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001742 outs() << "Archive : " << Filename;
1743 if (!ArchitectureName.empty())
1744 outs() << " (architecture " << ArchitectureName << ")";
1745 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001746 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001747 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1748 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001749 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001750 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001751 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1752 if (!ChildOrErr) {
1753 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001754 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001755 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001756 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001757 if (MachOObjectFile *O =
1758 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1759 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001760 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1761 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001762 }
1763 }
Lang Hamesfc209622016-07-14 02:24:01 +00001764 if (Err)
1765 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001766 } else {
1767 consumeError(AOrErr.takeError());
1768 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001769 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001770 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001771 }
1772 }
1773 return;
1774 }
1775 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1776 if (!checkMachOAndArchFlags(O, Filename))
1777 return;
1778 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001779 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001780 } else
1781 errs() << "llvm-objdump: '" << Filename << "': "
1782 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001783 return;
1784 }
1785 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001786}
1787
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001788// The block of info used by the Symbolizer call backs.
1789struct DisassembleInfo {
1790 bool verbose;
1791 MachOObjectFile *O;
1792 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001793 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001794 std::vector<SectionRef> *Sections;
1795 const char *class_name;
1796 const char *selector_name;
1797 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001798 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001799 uint64_t adrp_addr;
1800 uint32_t adrp_inst;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00001801 std::unique_ptr<SymbolAddressMap> bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001802 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001803};
1804
1805// SymbolizerGetOpInfo() is the operand information call back function.
1806// This is called to get the symbolic information for operand(s) of an
1807// instruction when it is being done. This routine does this from
1808// the relocation information, symbol table, etc. That block of information
1809// is a pointer to the struct DisassembleInfo that was passed when the
1810// disassembler context was created and passed to back to here when
1811// called back by the disassembler for instruction operands that could have
1812// relocation information. The address of the instruction containing operand is
1813// at the Pc parameter. The immediate value the operand has is passed in
1814// op_info->Value and is at Offset past the start of the instruction and has a
1815// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1816// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1817// names and addends of the symbolic expression to add for the operand. The
1818// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1819// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001820static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1821 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001822 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1823 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001824 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001825
1826 // Make sure all fields returned are zero if we don't set them.
1827 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1828 op_info->Value = value;
1829
1830 // If the TagType is not the value 1 which it code knows about or if no
1831 // verbose symbolic information is wanted then just return 0, indicating no
1832 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001833 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001834 return 0;
1835
1836 unsigned int Arch = info->O->getArch();
1837 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001838 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1839 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001840 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1841 // TODO:
1842 // Search the external relocation entries of a fully linked image
1843 // (if any) for an entry that matches this segment offset.
1844 // uint32_t seg_offset = (Pc + Offset);
1845 return 0;
1846 }
1847 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1848 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001849 uint32_t sect_addr = info->S.getAddress();
1850 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1851 bool reloc_found = false;
1852 DataRefImpl Rel;
1853 MachO::any_relocation_info RE;
1854 bool isExtern = false;
1855 SymbolRef Symbol;
1856 bool r_scattered = false;
1857 uint32_t r_value, pair_r_value, r_type;
1858 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001859 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001860 if (RelocOffset == sect_offset) {
1861 Rel = Reloc.getRawDataRefImpl();
1862 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001863 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001864 r_scattered = info->O->isRelocationScattered(RE);
1865 if (r_scattered) {
1866 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001867 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1868 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1869 DataRefImpl RelNext = Rel;
1870 info->O->moveRelocationNext(RelNext);
1871 MachO::any_relocation_info RENext;
1872 RENext = info->O->getRelocation(RelNext);
1873 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001874 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001875 else
1876 return 0;
1877 }
1878 } else {
1879 isExtern = info->O->getPlainRelocationExternal(RE);
1880 if (isExtern) {
1881 symbol_iterator RelocSym = Reloc.getSymbol();
1882 Symbol = *RelocSym;
1883 }
1884 }
1885 reloc_found = true;
1886 break;
1887 }
1888 }
1889 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001890 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001891 if (!SymName)
1892 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001893 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001894 op_info->AddSymbol.Present = 1;
1895 op_info->AddSymbol.Name = name;
1896 // For i386 extern relocation entries the value in the instruction is
1897 // the offset from the symbol, and value is already set in op_info->Value.
1898 return 1;
1899 }
1900 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1901 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001902 const char *add = GuessSymbolName(r_value, info->AddrMap);
1903 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001904 uint32_t offset = value - (r_value - pair_r_value);
1905 op_info->AddSymbol.Present = 1;
1906 if (add != nullptr)
1907 op_info->AddSymbol.Name = add;
1908 else
1909 op_info->AddSymbol.Value = r_value;
1910 op_info->SubtractSymbol.Present = 1;
1911 if (sub != nullptr)
1912 op_info->SubtractSymbol.Name = sub;
1913 else
1914 op_info->SubtractSymbol.Value = pair_r_value;
1915 op_info->Value = offset;
1916 return 1;
1917 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001918 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001919 }
1920 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001921 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1922 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001923 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1924 // TODO:
1925 // Search the external relocation entries of a fully linked image
1926 // (if any) for an entry that matches this segment offset.
1927 // uint64_t seg_offset = (Pc + Offset);
1928 return 0;
1929 }
1930 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1931 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001932 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001933 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1934 bool reloc_found = false;
1935 DataRefImpl Rel;
1936 MachO::any_relocation_info RE;
1937 bool isExtern = false;
1938 SymbolRef Symbol;
1939 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001940 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001941 if (RelocOffset == sect_offset) {
1942 Rel = Reloc.getRawDataRefImpl();
1943 RE = info->O->getRelocation(Rel);
1944 // NOTE: Scattered relocations don't exist on x86_64.
1945 isExtern = info->O->getPlainRelocationExternal(RE);
1946 if (isExtern) {
1947 symbol_iterator RelocSym = Reloc.getSymbol();
1948 Symbol = *RelocSym;
1949 }
1950 reloc_found = true;
1951 break;
1952 }
1953 }
1954 if (reloc_found && isExtern) {
1955 // The Value passed in will be adjusted by the Pc if the instruction
1956 // adds the Pc. But for x86_64 external relocation entries the Value
1957 // is the offset from the external symbol.
1958 if (info->O->getAnyRelocationPCRel(RE))
1959 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001960 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001961 if (!SymName)
1962 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001963 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001964 unsigned Type = info->O->getAnyRelocationType(RE);
1965 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1966 DataRefImpl RelNext = Rel;
1967 info->O->moveRelocationNext(RelNext);
1968 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1969 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1970 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1971 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1972 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1973 op_info->SubtractSymbol.Present = 1;
1974 op_info->SubtractSymbol.Name = name;
1975 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1976 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001977 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001978 if (!SymNameNext)
1979 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001980 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001981 }
1982 }
1983 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1984 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1985 op_info->AddSymbol.Present = 1;
1986 op_info->AddSymbol.Name = name;
1987 return 1;
1988 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001989 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001990 }
1991 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001992 if (Offset != 0 || (Size != 4 && Size != 2))
1993 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001994 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1995 // TODO:
1996 // Search the external relocation entries of a fully linked image
1997 // (if any) for an entry that matches this segment offset.
1998 // uint32_t seg_offset = (Pc + Offset);
1999 return 0;
2000 }
2001 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2002 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002003 uint32_t sect_addr = info->S.getAddress();
2004 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002005 DataRefImpl Rel;
2006 MachO::any_relocation_info RE;
2007 bool isExtern = false;
2008 SymbolRef Symbol;
2009 bool r_scattered = false;
2010 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002011 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002012 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2013 uint64_t RelocOffset = Reloc.getOffset();
2014 return RelocOffset == sect_offset;
2015 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002016
2017 if (Reloc == info->S.relocations().end())
2018 return 0;
2019
2020 Rel = Reloc->getRawDataRefImpl();
2021 RE = info->O->getRelocation(Rel);
2022 r_length = info->O->getAnyRelocationLength(RE);
2023 r_scattered = info->O->isRelocationScattered(RE);
2024 if (r_scattered) {
2025 r_value = info->O->getScatteredRelocationValue(RE);
2026 r_type = info->O->getScatteredRelocationType(RE);
2027 } else {
2028 r_type = info->O->getAnyRelocationType(RE);
2029 isExtern = info->O->getPlainRelocationExternal(RE);
2030 if (isExtern) {
2031 symbol_iterator RelocSym = Reloc->getSymbol();
2032 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002033 }
2034 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002035 if (r_type == MachO::ARM_RELOC_HALF ||
2036 r_type == MachO::ARM_RELOC_SECTDIFF ||
2037 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2038 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2039 DataRefImpl RelNext = Rel;
2040 info->O->moveRelocationNext(RelNext);
2041 MachO::any_relocation_info RENext;
2042 RENext = info->O->getRelocation(RelNext);
2043 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2044 if (info->O->isRelocationScattered(RENext))
2045 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2046 }
2047
2048 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002049 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002050 if (!SymName)
2051 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002052 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002053 op_info->AddSymbol.Present = 1;
2054 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002055 switch (r_type) {
2056 case MachO::ARM_RELOC_HALF:
2057 if ((r_length & 0x1) == 1) {
2058 op_info->Value = value << 16 | other_half;
2059 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2060 } else {
2061 op_info->Value = other_half << 16 | value;
2062 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002063 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002064 break;
2065 default:
2066 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002067 }
2068 return 1;
2069 }
2070 // If we have a branch that is not an external relocation entry then
2071 // return 0 so the code in tryAddingSymbolicOperand() can use the
2072 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002073 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002074 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2075 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002076 return 0;
2077
2078 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002079 if (r_type == MachO::ARM_RELOC_HALF ||
2080 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2081 if ((r_length & 0x1) == 1)
2082 value = value << 16 | other_half;
2083 else
2084 value = other_half << 16 | value;
2085 }
2086 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2087 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2088 offset = value - r_value;
2089 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002090 }
2091
David Blaikie33dd45d02015-03-23 18:39:02 +00002092 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002093 if ((r_length & 0x1) == 1)
2094 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2095 else
2096 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002097 const char *add = GuessSymbolName(r_value, info->AddrMap);
2098 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002099 int32_t offset = value - (r_value - pair_r_value);
2100 op_info->AddSymbol.Present = 1;
2101 if (add != nullptr)
2102 op_info->AddSymbol.Name = add;
2103 else
2104 op_info->AddSymbol.Value = r_value;
2105 op_info->SubtractSymbol.Present = 1;
2106 if (sub != nullptr)
2107 op_info->SubtractSymbol.Name = sub;
2108 else
2109 op_info->SubtractSymbol.Value = pair_r_value;
2110 op_info->Value = offset;
2111 return 1;
2112 }
2113
Kevin Enderby930fdc72014-11-06 19:00:13 +00002114 op_info->AddSymbol.Present = 1;
2115 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002116 if (r_type == MachO::ARM_RELOC_HALF) {
2117 if ((r_length & 0x1) == 1)
2118 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2119 else
2120 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002121 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002122 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002123 if (add != nullptr) {
2124 op_info->AddSymbol.Name = add;
2125 return 1;
2126 }
2127 op_info->AddSymbol.Value = value;
2128 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002129 }
2130 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002131 if (Offset != 0 || Size != 4)
2132 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002133 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2134 // TODO:
2135 // Search the external relocation entries of a fully linked image
2136 // (if any) for an entry that matches this segment offset.
2137 // uint64_t seg_offset = (Pc + Offset);
2138 return 0;
2139 }
2140 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2141 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002142 uint64_t sect_addr = info->S.getAddress();
2143 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002144 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002145 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2146 uint64_t RelocOffset = Reloc.getOffset();
2147 return RelocOffset == sect_offset;
2148 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002149
David Blaikie33dd45d02015-03-23 18:39:02 +00002150 if (Reloc == info->S.relocations().end())
2151 return 0;
2152
2153 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2154 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2155 uint32_t r_type = info->O->getAnyRelocationType(RE);
2156 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2157 DataRefImpl RelNext = Rel;
2158 info->O->moveRelocationNext(RelNext);
2159 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2160 if (value == 0) {
2161 value = info->O->getPlainRelocationSymbolNum(RENext);
2162 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002163 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002164 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002165 // NOTE: Scattered relocations don't exist on arm64.
2166 if (!info->O->getPlainRelocationExternal(RE))
2167 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002168 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002169 if (!SymName)
2170 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002171 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002172 op_info->AddSymbol.Present = 1;
2173 op_info->AddSymbol.Name = name;
2174
2175 switch (r_type) {
2176 case MachO::ARM64_RELOC_PAGE21:
2177 /* @page */
2178 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2179 break;
2180 case MachO::ARM64_RELOC_PAGEOFF12:
2181 /* @pageoff */
2182 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2183 break;
2184 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2185 /* @gotpage */
2186 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2187 break;
2188 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2189 /* @gotpageoff */
2190 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2191 break;
2192 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2193 /* @tvlppage is not implemented in llvm-mc */
2194 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2195 break;
2196 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2197 /* @tvlppageoff is not implemented in llvm-mc */
2198 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2199 break;
2200 default:
2201 case MachO::ARM64_RELOC_BRANCH26:
2202 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2203 break;
2204 }
2205 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002206 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002207 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002208}
2209
Kevin Enderbybf246f52014-09-24 23:08:22 +00002210// GuessCstringPointer is passed the address of what might be a pointer to a
2211// literal string in a cstring section. If that address is in a cstring section
2212// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002213static const char *GuessCstringPointer(uint64_t ReferenceValue,
2214 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002215 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002216 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2217 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2218 for (unsigned J = 0; J < Seg.nsects; ++J) {
2219 MachO::section_64 Sec = info->O->getSection64(Load, J);
2220 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2221 if (section_type == MachO::S_CSTRING_LITERALS &&
2222 ReferenceValue >= Sec.addr &&
2223 ReferenceValue < Sec.addr + Sec.size) {
2224 uint64_t sect_offset = ReferenceValue - Sec.addr;
2225 uint64_t object_offset = Sec.offset + sect_offset;
2226 StringRef MachOContents = info->O->getData();
2227 uint64_t object_size = MachOContents.size();
2228 const char *object_addr = (const char *)MachOContents.data();
2229 if (object_offset < object_size) {
2230 const char *name = object_addr + object_offset;
2231 return name;
2232 } else {
2233 return nullptr;
2234 }
2235 }
2236 }
2237 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2238 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2239 for (unsigned J = 0; J < Seg.nsects; ++J) {
2240 MachO::section Sec = info->O->getSection(Load, J);
2241 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2242 if (section_type == MachO::S_CSTRING_LITERALS &&
2243 ReferenceValue >= Sec.addr &&
2244 ReferenceValue < Sec.addr + Sec.size) {
2245 uint64_t sect_offset = ReferenceValue - Sec.addr;
2246 uint64_t object_offset = Sec.offset + sect_offset;
2247 StringRef MachOContents = info->O->getData();
2248 uint64_t object_size = MachOContents.size();
2249 const char *object_addr = (const char *)MachOContents.data();
2250 if (object_offset < object_size) {
2251 const char *name = object_addr + object_offset;
2252 return name;
2253 } else {
2254 return nullptr;
2255 }
2256 }
2257 }
2258 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002259 }
2260 return nullptr;
2261}
2262
Kevin Enderby85974882014-09-26 22:20:44 +00002263// GuessIndirectSymbol returns the name of the indirect symbol for the
2264// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2265// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2266// symbol name being referenced by the stub or pointer.
2267static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2268 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002269 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2270 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002271 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002272 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2273 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2274 for (unsigned J = 0; J < Seg.nsects; ++J) {
2275 MachO::section_64 Sec = info->O->getSection64(Load, J);
2276 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2277 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2278 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2279 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2280 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2281 section_type == MachO::S_SYMBOL_STUBS) &&
2282 ReferenceValue >= Sec.addr &&
2283 ReferenceValue < Sec.addr + Sec.size) {
2284 uint32_t stride;
2285 if (section_type == MachO::S_SYMBOL_STUBS)
2286 stride = Sec.reserved2;
2287 else
2288 stride = 8;
2289 if (stride == 0)
2290 return nullptr;
2291 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2292 if (index < Dysymtab.nindirectsyms) {
2293 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002294 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002295 if (indirect_symbol < Symtab.nsyms) {
2296 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2297 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002298 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002299 if (!SymName)
2300 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002301 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002302 return name;
2303 }
2304 }
2305 }
2306 }
2307 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2308 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2309 for (unsigned J = 0; J < Seg.nsects; ++J) {
2310 MachO::section Sec = info->O->getSection(Load, J);
2311 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2312 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2313 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2314 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2315 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2316 section_type == MachO::S_SYMBOL_STUBS) &&
2317 ReferenceValue >= Sec.addr &&
2318 ReferenceValue < Sec.addr + Sec.size) {
2319 uint32_t stride;
2320 if (section_type == MachO::S_SYMBOL_STUBS)
2321 stride = Sec.reserved2;
2322 else
2323 stride = 4;
2324 if (stride == 0)
2325 return nullptr;
2326 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2327 if (index < Dysymtab.nindirectsyms) {
2328 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002329 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002330 if (indirect_symbol < Symtab.nsyms) {
2331 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2332 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002333 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002334 if (!SymName)
2335 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002336 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002337 return name;
2338 }
2339 }
2340 }
2341 }
2342 }
Kevin Enderby85974882014-09-26 22:20:44 +00002343 }
2344 return nullptr;
2345}
2346
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002347// method_reference() is called passing it the ReferenceName that might be
2348// a reference it to an Objective-C method call. If so then it allocates and
2349// assembles a method call string with the values last seen and saved in
2350// the DisassembleInfo's class_name and selector_name fields. This is saved
2351// into the method field of the info and any previous string is free'ed.
2352// Then the class_name field in the info is set to nullptr. The method call
2353// string is set into ReferenceName and ReferenceType is set to
2354// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2355// then both ReferenceType and ReferenceName are left unchanged.
2356static void method_reference(struct DisassembleInfo *info,
2357 uint64_t *ReferenceType,
2358 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002359 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002360 if (*ReferenceName != nullptr) {
2361 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002362 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002363 if (info->method != nullptr)
2364 free(info->method);
2365 if (info->class_name != nullptr) {
2366 info->method = (char *)malloc(5 + strlen(info->class_name) +
2367 strlen(info->selector_name));
2368 if (info->method != nullptr) {
2369 strcpy(info->method, "+[");
2370 strcat(info->method, info->class_name);
2371 strcat(info->method, " ");
2372 strcat(info->method, info->selector_name);
2373 strcat(info->method, "]");
2374 *ReferenceName = info->method;
2375 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2376 }
2377 } else {
2378 info->method = (char *)malloc(9 + strlen(info->selector_name));
2379 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002380 if (Arch == Triple::x86_64)
2381 strcpy(info->method, "-[%rdi ");
2382 else if (Arch == Triple::aarch64)
2383 strcpy(info->method, "-[x0 ");
2384 else
2385 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002386 strcat(info->method, info->selector_name);
2387 strcat(info->method, "]");
2388 *ReferenceName = info->method;
2389 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2390 }
2391 }
2392 info->class_name = nullptr;
2393 }
2394 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002395 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002396 if (info->method != nullptr)
2397 free(info->method);
2398 info->method = (char *)malloc(17 + strlen(info->selector_name));
2399 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002400 if (Arch == Triple::x86_64)
2401 strcpy(info->method, "-[[%rdi super] ");
2402 else if (Arch == Triple::aarch64)
2403 strcpy(info->method, "-[[x0 super] ");
2404 else
2405 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002406 strcat(info->method, info->selector_name);
2407 strcat(info->method, "]");
2408 *ReferenceName = info->method;
2409 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2410 }
2411 info->class_name = nullptr;
2412 }
2413 }
2414 }
2415}
2416
2417// GuessPointerPointer() is passed the address of what might be a pointer to
2418// a reference to an Objective-C class, selector, message ref or cfstring.
2419// If so the value of the pointer is returned and one of the booleans are set
2420// to true. If not zero is returned and all the booleans are set to false.
2421static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2422 struct DisassembleInfo *info,
2423 bool &classref, bool &selref, bool &msgref,
2424 bool &cfstring) {
2425 classref = false;
2426 selref = false;
2427 msgref = false;
2428 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002429 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002430 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2431 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2432 for (unsigned J = 0; J < Seg.nsects; ++J) {
2433 MachO::section_64 Sec = info->O->getSection64(Load, J);
2434 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2435 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2436 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2437 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2438 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2439 ReferenceValue >= Sec.addr &&
2440 ReferenceValue < Sec.addr + Sec.size) {
2441 uint64_t sect_offset = ReferenceValue - Sec.addr;
2442 uint64_t object_offset = Sec.offset + sect_offset;
2443 StringRef MachOContents = info->O->getData();
2444 uint64_t object_size = MachOContents.size();
2445 const char *object_addr = (const char *)MachOContents.data();
2446 if (object_offset < object_size) {
2447 uint64_t pointer_value;
2448 memcpy(&pointer_value, object_addr + object_offset,
2449 sizeof(uint64_t));
2450 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2451 sys::swapByteOrder(pointer_value);
2452 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2453 selref = true;
2454 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2455 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2456 classref = true;
2457 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2458 ReferenceValue + 8 < Sec.addr + Sec.size) {
2459 msgref = true;
2460 memcpy(&pointer_value, object_addr + object_offset + 8,
2461 sizeof(uint64_t));
2462 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2463 sys::swapByteOrder(pointer_value);
2464 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2465 cfstring = true;
2466 return pointer_value;
2467 } else {
2468 return 0;
2469 }
2470 }
2471 }
2472 }
2473 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002474 }
2475 return 0;
2476}
2477
2478// get_pointer_64 returns a pointer to the bytes in the object file at the
2479// Address from a section in the Mach-O file. And indirectly returns the
2480// offset into the section, number of bytes left in the section past the offset
2481// and which section is was being referenced. If the Address is not in a
2482// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002483static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2484 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002485 DisassembleInfo *info,
2486 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002487 offset = 0;
2488 left = 0;
2489 S = SectionRef();
2490 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2491 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2492 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002493 if (SectSize == 0)
2494 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002495 if (objc_only) {
2496 StringRef SectName;
2497 ((*(info->Sections))[SectIdx]).getName(SectName);
2498 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2499 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2500 if (SegName != "__OBJC" && SectName != "__cstring")
2501 continue;
2502 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002503 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2504 S = (*(info->Sections))[SectIdx];
2505 offset = Address - SectAddress;
2506 left = SectSize - offset;
2507 StringRef SectContents;
2508 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2509 return SectContents.data() + offset;
2510 }
2511 }
2512 return nullptr;
2513}
2514
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002515static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2516 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002517 DisassembleInfo *info,
2518 bool objc_only = false) {
2519 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002520}
2521
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002522// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2523// the symbol indirectly through n_value. Based on the relocation information
2524// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002525// If no relocation information is found and a non-zero ReferenceValue for the
2526// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002527static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2528 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002529 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002530 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002531 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002532 return nullptr;
2533
2534 // See if there is an external relocation entry at the sect_offset.
2535 bool reloc_found = false;
2536 DataRefImpl Rel;
2537 MachO::any_relocation_info RE;
2538 bool isExtern = false;
2539 SymbolRef Symbol;
2540 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002541 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002542 if (RelocOffset == sect_offset) {
2543 Rel = Reloc.getRawDataRefImpl();
2544 RE = info->O->getRelocation(Rel);
2545 if (info->O->isRelocationScattered(RE))
2546 continue;
2547 isExtern = info->O->getPlainRelocationExternal(RE);
2548 if (isExtern) {
2549 symbol_iterator RelocSym = Reloc.getSymbol();
2550 Symbol = *RelocSym;
2551 }
2552 reloc_found = true;
2553 break;
2554 }
2555 }
2556 // If there is an external relocation entry for a symbol in this section
2557 // at this section_offset then use that symbol's value for the n_value
2558 // and return its name.
2559 const char *SymbolName = nullptr;
2560 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002561 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002562 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002563 if (!NameOrError)
2564 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002565 StringRef Name = *NameOrError;
2566 if (!Name.empty()) {
2567 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002568 return SymbolName;
2569 }
2570 }
2571
2572 // TODO: For fully linked images, look through the external relocation
2573 // entries off the dynamic symtab command. For these the r_offset is from the
2574 // start of the first writeable segment in the Mach-O file. So the offset
2575 // to this section from that segment is passed to this routine by the caller,
2576 // as the database_offset. Which is the difference of the section's starting
2577 // address and the first writable segment.
2578 //
2579 // NOTE: need add passing the database_offset to this routine.
2580
Kevin Enderby0fc11822015-04-01 20:57:01 +00002581 // We did not find an external relocation entry so look up the ReferenceValue
2582 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002583 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002584
2585 return SymbolName;
2586}
2587
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002588static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2589 DisassembleInfo *info,
2590 uint32_t ReferenceValue) {
2591 uint64_t n_value64;
2592 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2593}
2594
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002595// These are structs in the Objective-C meta data and read to produce the
2596// comments for disassembly. While these are part of the ABI they are no
2597// public defintions. So the are here not in include/llvm/Support/MachO.h .
2598
2599// The cfstring object in a 64-bit Mach-O file.
2600struct cfstring64_t {
2601 uint64_t isa; // class64_t * (64-bit pointer)
2602 uint64_t flags; // flag bits
2603 uint64_t characters; // char * (64-bit pointer)
2604 uint64_t length; // number of non-NULL characters in above
2605};
2606
2607// The class object in a 64-bit Mach-O file.
2608struct class64_t {
2609 uint64_t isa; // class64_t * (64-bit pointer)
2610 uint64_t superclass; // class64_t * (64-bit pointer)
2611 uint64_t cache; // Cache (64-bit pointer)
2612 uint64_t vtable; // IMP * (64-bit pointer)
2613 uint64_t data; // class_ro64_t * (64-bit pointer)
2614};
2615
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002616struct class32_t {
2617 uint32_t isa; /* class32_t * (32-bit pointer) */
2618 uint32_t superclass; /* class32_t * (32-bit pointer) */
2619 uint32_t cache; /* Cache (32-bit pointer) */
2620 uint32_t vtable; /* IMP * (32-bit pointer) */
2621 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2622};
2623
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002624struct class_ro64_t {
2625 uint32_t flags;
2626 uint32_t instanceStart;
2627 uint32_t instanceSize;
2628 uint32_t reserved;
2629 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2630 uint64_t name; // const char * (64-bit pointer)
2631 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2632 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2633 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2634 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2635 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2636};
2637
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002638struct class_ro32_t {
2639 uint32_t flags;
2640 uint32_t instanceStart;
2641 uint32_t instanceSize;
2642 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2643 uint32_t name; /* const char * (32-bit pointer) */
2644 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2645 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2646 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2647 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2648 uint32_t baseProperties; /* const struct objc_property_list *
2649 (32-bit pointer) */
2650};
2651
2652/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002653#define RO_META (1 << 0)
2654#define RO_ROOT (1 << 1)
2655#define RO_HAS_CXX_STRUCTORS (1 << 2)
2656
2657struct method_list64_t {
2658 uint32_t entsize;
2659 uint32_t count;
2660 /* struct method64_t first; These structures follow inline */
2661};
2662
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002663struct method_list32_t {
2664 uint32_t entsize;
2665 uint32_t count;
2666 /* struct method32_t first; These structures follow inline */
2667};
2668
Kevin Enderby0fc11822015-04-01 20:57:01 +00002669struct method64_t {
2670 uint64_t name; /* SEL (64-bit pointer) */
2671 uint64_t types; /* const char * (64-bit pointer) */
2672 uint64_t imp; /* IMP (64-bit pointer) */
2673};
2674
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002675struct method32_t {
2676 uint32_t name; /* SEL (32-bit pointer) */
2677 uint32_t types; /* const char * (32-bit pointer) */
2678 uint32_t imp; /* IMP (32-bit pointer) */
2679};
2680
Kevin Enderby0fc11822015-04-01 20:57:01 +00002681struct protocol_list64_t {
2682 uint64_t count; /* uintptr_t (a 64-bit value) */
2683 /* struct protocol64_t * list[0]; These pointers follow inline */
2684};
2685
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002686struct protocol_list32_t {
2687 uint32_t count; /* uintptr_t (a 32-bit value) */
2688 /* struct protocol32_t * list[0]; These pointers follow inline */
2689};
2690
Kevin Enderby0fc11822015-04-01 20:57:01 +00002691struct protocol64_t {
2692 uint64_t isa; /* id * (64-bit pointer) */
2693 uint64_t name; /* const char * (64-bit pointer) */
2694 uint64_t protocols; /* struct protocol_list64_t *
2695 (64-bit pointer) */
2696 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2697 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2698 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2699 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2700 uint64_t instanceProperties; /* struct objc_property_list *
2701 (64-bit pointer) */
2702};
2703
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002704struct protocol32_t {
2705 uint32_t isa; /* id * (32-bit pointer) */
2706 uint32_t name; /* const char * (32-bit pointer) */
2707 uint32_t protocols; /* struct protocol_list_t *
2708 (32-bit pointer) */
2709 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2710 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2711 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2712 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2713 uint32_t instanceProperties; /* struct objc_property_list *
2714 (32-bit pointer) */
2715};
2716
Kevin Enderby0fc11822015-04-01 20:57:01 +00002717struct ivar_list64_t {
2718 uint32_t entsize;
2719 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002720 /* struct ivar64_t first; These structures follow inline */
2721};
2722
2723struct ivar_list32_t {
2724 uint32_t entsize;
2725 uint32_t count;
2726 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002727};
2728
2729struct ivar64_t {
2730 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2731 uint64_t name; /* const char * (64-bit pointer) */
2732 uint64_t type; /* const char * (64-bit pointer) */
2733 uint32_t alignment;
2734 uint32_t size;
2735};
2736
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002737struct ivar32_t {
2738 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2739 uint32_t name; /* const char * (32-bit pointer) */
2740 uint32_t type; /* const char * (32-bit pointer) */
2741 uint32_t alignment;
2742 uint32_t size;
2743};
2744
Kevin Enderby0fc11822015-04-01 20:57:01 +00002745struct objc_property_list64 {
2746 uint32_t entsize;
2747 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002748 /* struct objc_property64 first; These structures follow inline */
2749};
2750
2751struct objc_property_list32 {
2752 uint32_t entsize;
2753 uint32_t count;
2754 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002755};
2756
2757struct objc_property64 {
2758 uint64_t name; /* const char * (64-bit pointer) */
2759 uint64_t attributes; /* const char * (64-bit pointer) */
2760};
2761
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002762struct objc_property32 {
2763 uint32_t name; /* const char * (32-bit pointer) */
2764 uint32_t attributes; /* const char * (32-bit pointer) */
2765};
2766
Kevin Enderby0fc11822015-04-01 20:57:01 +00002767struct category64_t {
2768 uint64_t name; /* const char * (64-bit pointer) */
2769 uint64_t cls; /* struct class_t * (64-bit pointer) */
2770 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2771 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2772 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2773 uint64_t instanceProperties; /* struct objc_property_list *
2774 (64-bit pointer) */
2775};
2776
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002777struct category32_t {
2778 uint32_t name; /* const char * (32-bit pointer) */
2779 uint32_t cls; /* struct class_t * (32-bit pointer) */
2780 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2781 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2782 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2783 uint32_t instanceProperties; /* struct objc_property_list *
2784 (32-bit pointer) */
2785};
2786
Kevin Enderby0fc11822015-04-01 20:57:01 +00002787struct objc_image_info64 {
2788 uint32_t version;
2789 uint32_t flags;
2790};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002791struct objc_image_info32 {
2792 uint32_t version;
2793 uint32_t flags;
2794};
Kevin Enderby846c0002015-04-16 17:19:59 +00002795struct imageInfo_t {
2796 uint32_t version;
2797 uint32_t flags;
2798};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002799/* masks for objc_image_info.flags */
2800#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2801#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2802
2803struct message_ref64 {
2804 uint64_t imp; /* IMP (64-bit pointer) */
2805 uint64_t sel; /* SEL (64-bit pointer) */
2806};
2807
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002808struct message_ref32 {
2809 uint32_t imp; /* IMP (32-bit pointer) */
2810 uint32_t sel; /* SEL (32-bit pointer) */
2811};
2812
Kevin Enderby846c0002015-04-16 17:19:59 +00002813// Objective-C 1 (32-bit only) meta data structs.
2814
2815struct objc_module_t {
2816 uint32_t version;
2817 uint32_t size;
2818 uint32_t name; /* char * (32-bit pointer) */
2819 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2820};
2821
2822struct objc_symtab_t {
2823 uint32_t sel_ref_cnt;
2824 uint32_t refs; /* SEL * (32-bit pointer) */
2825 uint16_t cls_def_cnt;
2826 uint16_t cat_def_cnt;
2827 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2828};
2829
2830struct objc_class_t {
2831 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2832 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2833 uint32_t name; /* const char * (32-bit pointer) */
2834 int32_t version;
2835 int32_t info;
2836 int32_t instance_size;
2837 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2838 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2839 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2840 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2841};
2842
2843#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2844// class is not a metaclass
2845#define CLS_CLASS 0x1
2846// class is a metaclass
2847#define CLS_META 0x2
2848
2849struct objc_category_t {
2850 uint32_t category_name; /* char * (32-bit pointer) */
2851 uint32_t class_name; /* char * (32-bit pointer) */
2852 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2853 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2854 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2855};
2856
2857struct objc_ivar_t {
2858 uint32_t ivar_name; /* char * (32-bit pointer) */
2859 uint32_t ivar_type; /* char * (32-bit pointer) */
2860 int32_t ivar_offset;
2861};
2862
2863struct objc_ivar_list_t {
2864 int32_t ivar_count;
2865 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2866};
2867
2868struct objc_method_list_t {
2869 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2870 int32_t method_count;
2871 // struct objc_method_t method_list[1]; /* variable length structure */
2872};
2873
2874struct objc_method_t {
2875 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2876 uint32_t method_types; /* char * (32-bit pointer) */
2877 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2878 (32-bit pointer) */
2879};
2880
2881struct objc_protocol_list_t {
2882 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2883 int32_t count;
2884 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2885 // (32-bit pointer) */
2886};
2887
2888struct objc_protocol_t {
2889 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2890 uint32_t protocol_name; /* char * (32-bit pointer) */
2891 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2892 uint32_t instance_methods; /* struct objc_method_description_list *
2893 (32-bit pointer) */
2894 uint32_t class_methods; /* struct objc_method_description_list *
2895 (32-bit pointer) */
2896};
2897
2898struct objc_method_description_list_t {
2899 int32_t count;
2900 // struct objc_method_description_t list[1];
2901};
2902
2903struct objc_method_description_t {
2904 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2905 uint32_t types; /* char * (32-bit pointer) */
2906};
2907
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002908inline void swapStruct(struct cfstring64_t &cfs) {
2909 sys::swapByteOrder(cfs.isa);
2910 sys::swapByteOrder(cfs.flags);
2911 sys::swapByteOrder(cfs.characters);
2912 sys::swapByteOrder(cfs.length);
2913}
2914
2915inline void swapStruct(struct class64_t &c) {
2916 sys::swapByteOrder(c.isa);
2917 sys::swapByteOrder(c.superclass);
2918 sys::swapByteOrder(c.cache);
2919 sys::swapByteOrder(c.vtable);
2920 sys::swapByteOrder(c.data);
2921}
2922
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002923inline void swapStruct(struct class32_t &c) {
2924 sys::swapByteOrder(c.isa);
2925 sys::swapByteOrder(c.superclass);
2926 sys::swapByteOrder(c.cache);
2927 sys::swapByteOrder(c.vtable);
2928 sys::swapByteOrder(c.data);
2929}
2930
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002931inline void swapStruct(struct class_ro64_t &cro) {
2932 sys::swapByteOrder(cro.flags);
2933 sys::swapByteOrder(cro.instanceStart);
2934 sys::swapByteOrder(cro.instanceSize);
2935 sys::swapByteOrder(cro.reserved);
2936 sys::swapByteOrder(cro.ivarLayout);
2937 sys::swapByteOrder(cro.name);
2938 sys::swapByteOrder(cro.baseMethods);
2939 sys::swapByteOrder(cro.baseProtocols);
2940 sys::swapByteOrder(cro.ivars);
2941 sys::swapByteOrder(cro.weakIvarLayout);
2942 sys::swapByteOrder(cro.baseProperties);
2943}
2944
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002945inline void swapStruct(struct class_ro32_t &cro) {
2946 sys::swapByteOrder(cro.flags);
2947 sys::swapByteOrder(cro.instanceStart);
2948 sys::swapByteOrder(cro.instanceSize);
2949 sys::swapByteOrder(cro.ivarLayout);
2950 sys::swapByteOrder(cro.name);
2951 sys::swapByteOrder(cro.baseMethods);
2952 sys::swapByteOrder(cro.baseProtocols);
2953 sys::swapByteOrder(cro.ivars);
2954 sys::swapByteOrder(cro.weakIvarLayout);
2955 sys::swapByteOrder(cro.baseProperties);
2956}
2957
Kevin Enderby0fc11822015-04-01 20:57:01 +00002958inline void swapStruct(struct method_list64_t &ml) {
2959 sys::swapByteOrder(ml.entsize);
2960 sys::swapByteOrder(ml.count);
2961}
2962
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002963inline void swapStruct(struct method_list32_t &ml) {
2964 sys::swapByteOrder(ml.entsize);
2965 sys::swapByteOrder(ml.count);
2966}
2967
Kevin Enderby0fc11822015-04-01 20:57:01 +00002968inline void swapStruct(struct method64_t &m) {
2969 sys::swapByteOrder(m.name);
2970 sys::swapByteOrder(m.types);
2971 sys::swapByteOrder(m.imp);
2972}
2973
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002974inline void swapStruct(struct method32_t &m) {
2975 sys::swapByteOrder(m.name);
2976 sys::swapByteOrder(m.types);
2977 sys::swapByteOrder(m.imp);
2978}
2979
Kevin Enderby0fc11822015-04-01 20:57:01 +00002980inline void swapStruct(struct protocol_list64_t &pl) {
2981 sys::swapByteOrder(pl.count);
2982}
2983
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002984inline void swapStruct(struct protocol_list32_t &pl) {
2985 sys::swapByteOrder(pl.count);
2986}
2987
Kevin Enderby0fc11822015-04-01 20:57:01 +00002988inline void swapStruct(struct protocol64_t &p) {
2989 sys::swapByteOrder(p.isa);
2990 sys::swapByteOrder(p.name);
2991 sys::swapByteOrder(p.protocols);
2992 sys::swapByteOrder(p.instanceMethods);
2993 sys::swapByteOrder(p.classMethods);
2994 sys::swapByteOrder(p.optionalInstanceMethods);
2995 sys::swapByteOrder(p.optionalClassMethods);
2996 sys::swapByteOrder(p.instanceProperties);
2997}
2998
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002999inline void swapStruct(struct protocol32_t &p) {
3000 sys::swapByteOrder(p.isa);
3001 sys::swapByteOrder(p.name);
3002 sys::swapByteOrder(p.protocols);
3003 sys::swapByteOrder(p.instanceMethods);
3004 sys::swapByteOrder(p.classMethods);
3005 sys::swapByteOrder(p.optionalInstanceMethods);
3006 sys::swapByteOrder(p.optionalClassMethods);
3007 sys::swapByteOrder(p.instanceProperties);
3008}
3009
Kevin Enderby0fc11822015-04-01 20:57:01 +00003010inline void swapStruct(struct ivar_list64_t &il) {
3011 sys::swapByteOrder(il.entsize);
3012 sys::swapByteOrder(il.count);
3013}
3014
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003015inline void swapStruct(struct ivar_list32_t &il) {
3016 sys::swapByteOrder(il.entsize);
3017 sys::swapByteOrder(il.count);
3018}
3019
Kevin Enderby0fc11822015-04-01 20:57:01 +00003020inline void swapStruct(struct ivar64_t &i) {
3021 sys::swapByteOrder(i.offset);
3022 sys::swapByteOrder(i.name);
3023 sys::swapByteOrder(i.type);
3024 sys::swapByteOrder(i.alignment);
3025 sys::swapByteOrder(i.size);
3026}
3027
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003028inline void swapStruct(struct ivar32_t &i) {
3029 sys::swapByteOrder(i.offset);
3030 sys::swapByteOrder(i.name);
3031 sys::swapByteOrder(i.type);
3032 sys::swapByteOrder(i.alignment);
3033 sys::swapByteOrder(i.size);
3034}
3035
Kevin Enderby0fc11822015-04-01 20:57:01 +00003036inline void swapStruct(struct objc_property_list64 &pl) {
3037 sys::swapByteOrder(pl.entsize);
3038 sys::swapByteOrder(pl.count);
3039}
3040
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003041inline void swapStruct(struct objc_property_list32 &pl) {
3042 sys::swapByteOrder(pl.entsize);
3043 sys::swapByteOrder(pl.count);
3044}
3045
Kevin Enderby0fc11822015-04-01 20:57:01 +00003046inline void swapStruct(struct objc_property64 &op) {
3047 sys::swapByteOrder(op.name);
3048 sys::swapByteOrder(op.attributes);
3049}
3050
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003051inline void swapStruct(struct objc_property32 &op) {
3052 sys::swapByteOrder(op.name);
3053 sys::swapByteOrder(op.attributes);
3054}
3055
Kevin Enderby0fc11822015-04-01 20:57:01 +00003056inline void swapStruct(struct category64_t &c) {
3057 sys::swapByteOrder(c.name);
3058 sys::swapByteOrder(c.cls);
3059 sys::swapByteOrder(c.instanceMethods);
3060 sys::swapByteOrder(c.classMethods);
3061 sys::swapByteOrder(c.protocols);
3062 sys::swapByteOrder(c.instanceProperties);
3063}
3064
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003065inline void swapStruct(struct category32_t &c) {
3066 sys::swapByteOrder(c.name);
3067 sys::swapByteOrder(c.cls);
3068 sys::swapByteOrder(c.instanceMethods);
3069 sys::swapByteOrder(c.classMethods);
3070 sys::swapByteOrder(c.protocols);
3071 sys::swapByteOrder(c.instanceProperties);
3072}
3073
Kevin Enderby0fc11822015-04-01 20:57:01 +00003074inline void swapStruct(struct objc_image_info64 &o) {
3075 sys::swapByteOrder(o.version);
3076 sys::swapByteOrder(o.flags);
3077}
3078
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003079inline void swapStruct(struct objc_image_info32 &o) {
3080 sys::swapByteOrder(o.version);
3081 sys::swapByteOrder(o.flags);
3082}
3083
Kevin Enderby846c0002015-04-16 17:19:59 +00003084inline void swapStruct(struct imageInfo_t &o) {
3085 sys::swapByteOrder(o.version);
3086 sys::swapByteOrder(o.flags);
3087}
3088
Kevin Enderby0fc11822015-04-01 20:57:01 +00003089inline void swapStruct(struct message_ref64 &mr) {
3090 sys::swapByteOrder(mr.imp);
3091 sys::swapByteOrder(mr.sel);
3092}
3093
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003094inline void swapStruct(struct message_ref32 &mr) {
3095 sys::swapByteOrder(mr.imp);
3096 sys::swapByteOrder(mr.sel);
3097}
3098
Kevin Enderby846c0002015-04-16 17:19:59 +00003099inline void swapStruct(struct objc_module_t &module) {
3100 sys::swapByteOrder(module.version);
3101 sys::swapByteOrder(module.size);
3102 sys::swapByteOrder(module.name);
3103 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003104}
Kevin Enderby846c0002015-04-16 17:19:59 +00003105
3106inline void swapStruct(struct objc_symtab_t &symtab) {
3107 sys::swapByteOrder(symtab.sel_ref_cnt);
3108 sys::swapByteOrder(symtab.refs);
3109 sys::swapByteOrder(symtab.cls_def_cnt);
3110 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003111}
Kevin Enderby846c0002015-04-16 17:19:59 +00003112
3113inline void swapStruct(struct objc_class_t &objc_class) {
3114 sys::swapByteOrder(objc_class.isa);
3115 sys::swapByteOrder(objc_class.super_class);
3116 sys::swapByteOrder(objc_class.name);
3117 sys::swapByteOrder(objc_class.version);
3118 sys::swapByteOrder(objc_class.info);
3119 sys::swapByteOrder(objc_class.instance_size);
3120 sys::swapByteOrder(objc_class.ivars);
3121 sys::swapByteOrder(objc_class.methodLists);
3122 sys::swapByteOrder(objc_class.cache);
3123 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003124}
Kevin Enderby846c0002015-04-16 17:19:59 +00003125
3126inline void swapStruct(struct objc_category_t &objc_category) {
3127 sys::swapByteOrder(objc_category.category_name);
3128 sys::swapByteOrder(objc_category.class_name);
3129 sys::swapByteOrder(objc_category.instance_methods);
3130 sys::swapByteOrder(objc_category.class_methods);
3131 sys::swapByteOrder(objc_category.protocols);
3132}
3133
3134inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3135 sys::swapByteOrder(objc_ivar_list.ivar_count);
3136}
3137
3138inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3139 sys::swapByteOrder(objc_ivar.ivar_name);
3140 sys::swapByteOrder(objc_ivar.ivar_type);
3141 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003142}
Kevin Enderby846c0002015-04-16 17:19:59 +00003143
3144inline void swapStruct(struct objc_method_list_t &method_list) {
3145 sys::swapByteOrder(method_list.obsolete);
3146 sys::swapByteOrder(method_list.method_count);
3147}
3148
3149inline void swapStruct(struct objc_method_t &method) {
3150 sys::swapByteOrder(method.method_name);
3151 sys::swapByteOrder(method.method_types);
3152 sys::swapByteOrder(method.method_imp);
3153}
3154
3155inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3156 sys::swapByteOrder(protocol_list.next);
3157 sys::swapByteOrder(protocol_list.count);
3158}
3159
3160inline void swapStruct(struct objc_protocol_t &protocol) {
3161 sys::swapByteOrder(protocol.isa);
3162 sys::swapByteOrder(protocol.protocol_name);
3163 sys::swapByteOrder(protocol.protocol_list);
3164 sys::swapByteOrder(protocol.instance_methods);
3165 sys::swapByteOrder(protocol.class_methods);
3166}
3167
3168inline void swapStruct(struct objc_method_description_list_t &mdl) {
3169 sys::swapByteOrder(mdl.count);
3170}
3171
3172inline void swapStruct(struct objc_method_description_t &md) {
3173 sys::swapByteOrder(md.name);
3174 sys::swapByteOrder(md.types);
3175}
3176
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003177static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3178 struct DisassembleInfo *info);
3179
3180// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3181// to an Objective-C class and returns the class name. It is also passed the
3182// address of the pointer, so when the pointer is zero as it can be in an .o
3183// file, that is used to look for an external relocation entry with a symbol
3184// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003185static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3186 uint64_t ReferenceValue,
3187 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003188 const char *r;
3189 uint32_t offset, left;
3190 SectionRef S;
3191
3192 // The pointer_value can be 0 in an object file and have a relocation
3193 // entry for the class symbol at the ReferenceValue (the address of the
3194 // pointer).
3195 if (pointer_value == 0) {
3196 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3197 if (r == nullptr || left < sizeof(uint64_t))
3198 return nullptr;
3199 uint64_t n_value;
3200 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3201 if (symbol_name == nullptr)
3202 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003203 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003204 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3205 return class_name + 2;
3206 else
3207 return nullptr;
3208 }
3209
3210 // The case were the pointer_value is non-zero and points to a class defined
3211 // in this Mach-O file.
3212 r = get_pointer_64(pointer_value, offset, left, S, info);
3213 if (r == nullptr || left < sizeof(struct class64_t))
3214 return nullptr;
3215 struct class64_t c;
3216 memcpy(&c, r, sizeof(struct class64_t));
3217 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3218 swapStruct(c);
3219 if (c.data == 0)
3220 return nullptr;
3221 r = get_pointer_64(c.data, offset, left, S, info);
3222 if (r == nullptr || left < sizeof(struct class_ro64_t))
3223 return nullptr;
3224 struct class_ro64_t cro;
3225 memcpy(&cro, r, sizeof(struct class_ro64_t));
3226 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3227 swapStruct(cro);
3228 if (cro.name == 0)
3229 return nullptr;
3230 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3231 return name;
3232}
3233
3234// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3235// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003236static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3237 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003238 const char *r, *name;
3239 uint32_t offset, left;
3240 SectionRef S;
3241 struct cfstring64_t cfs;
3242 uint64_t cfs_characters;
3243
3244 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3245 if (r == nullptr || left < sizeof(struct cfstring64_t))
3246 return nullptr;
3247 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3248 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3249 swapStruct(cfs);
3250 if (cfs.characters == 0) {
3251 uint64_t n_value;
3252 const char *symbol_name = get_symbol_64(
3253 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3254 if (symbol_name == nullptr)
3255 return nullptr;
3256 cfs_characters = n_value;
3257 } else
3258 cfs_characters = cfs.characters;
3259 name = get_pointer_64(cfs_characters, offset, left, S, info);
3260
3261 return name;
3262}
3263
3264// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3265// of a pointer to an Objective-C selector reference when the pointer value is
3266// zero as in a .o file and is likely to have a external relocation entry with
3267// who's symbol's n_value is the real pointer to the selector name. If that is
3268// the case the real pointer to the selector name is returned else 0 is
3269// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003270static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3271 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003272 uint32_t offset, left;
3273 SectionRef S;
3274
3275 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3276 if (r == nullptr || left < sizeof(uint64_t))
3277 return 0;
3278 uint64_t n_value;
3279 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3280 if (symbol_name == nullptr)
3281 return 0;
3282 return n_value;
3283}
3284
Kevin Enderby0fc11822015-04-01 20:57:01 +00003285static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3286 const char *sectname) {
3287 for (const SectionRef &Section : O->sections()) {
3288 StringRef SectName;
3289 Section.getName(SectName);
3290 DataRefImpl Ref = Section.getRawDataRefImpl();
3291 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3292 if (SegName == segname && SectName == sectname)
3293 return Section;
3294 }
3295 return SectionRef();
3296}
3297
3298static void
3299walk_pointer_list_64(const char *listname, const SectionRef S,
3300 MachOObjectFile *O, struct DisassembleInfo *info,
3301 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3302 if (S == SectionRef())
3303 return;
3304
3305 StringRef SectName;
3306 S.getName(SectName);
3307 DataRefImpl Ref = S.getRawDataRefImpl();
3308 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3309 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3310
3311 StringRef BytesStr;
3312 S.getContents(BytesStr);
3313 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3314
3315 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3316 uint32_t left = S.getSize() - i;
3317 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3318 uint64_t p = 0;
3319 memcpy(&p, Contents + i, size);
3320 if (i + sizeof(uint64_t) > S.getSize())
3321 outs() << listname << " list pointer extends past end of (" << SegName
3322 << "," << SectName << ") section\n";
3323 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3324
3325 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3326 sys::swapByteOrder(p);
3327
3328 uint64_t n_value = 0;
3329 const char *name = get_symbol_64(i, S, info, n_value, p);
3330 if (name == nullptr)
3331 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3332
3333 if (n_value != 0) {
3334 outs() << format("0x%" PRIx64, n_value);
3335 if (p != 0)
3336 outs() << " + " << format("0x%" PRIx64, p);
3337 } else
3338 outs() << format("0x%" PRIx64, p);
3339 if (name != nullptr)
3340 outs() << " " << name;
3341 outs() << "\n";
3342
3343 p += n_value;
3344 if (func)
3345 func(p, info);
3346 }
3347}
3348
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003349static void
3350walk_pointer_list_32(const char *listname, const SectionRef S,
3351 MachOObjectFile *O, struct DisassembleInfo *info,
3352 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3353 if (S == SectionRef())
3354 return;
3355
3356 StringRef SectName;
3357 S.getName(SectName);
3358 DataRefImpl Ref = S.getRawDataRefImpl();
3359 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3360 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3361
3362 StringRef BytesStr;
3363 S.getContents(BytesStr);
3364 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3365
3366 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3367 uint32_t left = S.getSize() - i;
3368 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3369 uint32_t p = 0;
3370 memcpy(&p, Contents + i, size);
3371 if (i + sizeof(uint32_t) > S.getSize())
3372 outs() << listname << " list pointer extends past end of (" << SegName
3373 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003374 uint32_t Address = S.getAddress() + i;
3375 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003376
3377 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3378 sys::swapByteOrder(p);
3379 outs() << format("0x%" PRIx32, p);
3380
3381 const char *name = get_symbol_32(i, S, info, p);
3382 if (name != nullptr)
3383 outs() << " " << name;
3384 outs() << "\n";
3385
3386 if (func)
3387 func(p, info);
3388 }
3389}
3390
3391static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003392 if (layout_map == nullptr)
3393 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003394 outs() << " layout map: ";
3395 do {
3396 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3397 left--;
3398 layout_map++;
3399 } while (*layout_map != '\0' && left != 0);
3400 outs() << "\n";
3401}
3402
Kevin Enderby0fc11822015-04-01 20:57:01 +00003403static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3404 uint32_t offset, left;
3405 SectionRef S;
3406 const char *layout_map;
3407
3408 if (p == 0)
3409 return;
3410 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003411 print_layout_map(layout_map, left);
3412}
3413
3414static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3415 uint32_t offset, left;
3416 SectionRef S;
3417 const char *layout_map;
3418
3419 if (p == 0)
3420 return;
3421 layout_map = get_pointer_32(p, offset, left, S, info);
3422 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003423}
3424
3425static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3426 const char *indent) {
3427 struct method_list64_t ml;
3428 struct method64_t m;
3429 const char *r;
3430 uint32_t offset, xoffset, left, i;
3431 SectionRef S, xS;
3432 const char *name, *sym_name;
3433 uint64_t n_value;
3434
3435 r = get_pointer_64(p, offset, left, S, info);
3436 if (r == nullptr)
3437 return;
3438 memset(&ml, '\0', sizeof(struct method_list64_t));
3439 if (left < sizeof(struct method_list64_t)) {
3440 memcpy(&ml, r, left);
3441 outs() << " (method_list_t entends past the end of the section)\n";
3442 } else
3443 memcpy(&ml, r, sizeof(struct method_list64_t));
3444 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3445 swapStruct(ml);
3446 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3447 outs() << indent << "\t\t count " << ml.count << "\n";
3448
3449 p += sizeof(struct method_list64_t);
3450 offset += sizeof(struct method_list64_t);
3451 for (i = 0; i < ml.count; i++) {
3452 r = get_pointer_64(p, offset, left, S, info);
3453 if (r == nullptr)
3454 return;
3455 memset(&m, '\0', sizeof(struct method64_t));
3456 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003457 memcpy(&m, r, left);
3458 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003459 } else
3460 memcpy(&m, r, sizeof(struct method64_t));
3461 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3462 swapStruct(m);
3463
3464 outs() << indent << "\t\t name ";
3465 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3466 info, n_value, m.name);
3467 if (n_value != 0) {
3468 if (info->verbose && sym_name != nullptr)
3469 outs() << sym_name;
3470 else
3471 outs() << format("0x%" PRIx64, n_value);
3472 if (m.name != 0)
3473 outs() << " + " << format("0x%" PRIx64, m.name);
3474 } else
3475 outs() << format("0x%" PRIx64, m.name);
3476 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3477 if (name != nullptr)
3478 outs() << format(" %.*s", left, name);
3479 outs() << "\n";
3480
3481 outs() << indent << "\t\t types ";
3482 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3483 info, n_value, m.types);
3484 if (n_value != 0) {
3485 if (info->verbose && sym_name != nullptr)
3486 outs() << sym_name;
3487 else
3488 outs() << format("0x%" PRIx64, n_value);
3489 if (m.types != 0)
3490 outs() << " + " << format("0x%" PRIx64, m.types);
3491 } else
3492 outs() << format("0x%" PRIx64, m.types);
3493 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3494 if (name != nullptr)
3495 outs() << format(" %.*s", left, name);
3496 outs() << "\n";
3497
3498 outs() << indent << "\t\t imp ";
3499 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3500 n_value, m.imp);
3501 if (info->verbose && name == nullptr) {
3502 if (n_value != 0) {
3503 outs() << format("0x%" PRIx64, n_value) << " ";
3504 if (m.imp != 0)
3505 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3506 } else
3507 outs() << format("0x%" PRIx64, m.imp) << " ";
3508 }
3509 if (name != nullptr)
3510 outs() << name;
3511 outs() << "\n";
3512
3513 p += sizeof(struct method64_t);
3514 offset += sizeof(struct method64_t);
3515 }
3516}
3517
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003518static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3519 const char *indent) {
3520 struct method_list32_t ml;
3521 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003522 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003523 uint32_t offset, xoffset, left, i;
3524 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003525
3526 r = get_pointer_32(p, offset, left, S, info);
3527 if (r == nullptr)
3528 return;
3529 memset(&ml, '\0', sizeof(struct method_list32_t));
3530 if (left < sizeof(struct method_list32_t)) {
3531 memcpy(&ml, r, left);
3532 outs() << " (method_list_t entends past the end of the section)\n";
3533 } else
3534 memcpy(&ml, r, sizeof(struct method_list32_t));
3535 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3536 swapStruct(ml);
3537 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3538 outs() << indent << "\t\t count " << ml.count << "\n";
3539
3540 p += sizeof(struct method_list32_t);
3541 offset += sizeof(struct method_list32_t);
3542 for (i = 0; i < ml.count; i++) {
3543 r = get_pointer_32(p, offset, left, S, info);
3544 if (r == nullptr)
3545 return;
3546 memset(&m, '\0', sizeof(struct method32_t));
3547 if (left < sizeof(struct method32_t)) {
3548 memcpy(&ml, r, left);
3549 outs() << indent << " (method_t entends past the end of the section)\n";
3550 } else
3551 memcpy(&m, r, sizeof(struct method32_t));
3552 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3553 swapStruct(m);
3554
3555 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3556 name = get_pointer_32(m.name, xoffset, left, xS, info);
3557 if (name != nullptr)
3558 outs() << format(" %.*s", left, name);
3559 outs() << "\n";
3560
3561 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3562 name = get_pointer_32(m.types, xoffset, left, xS, info);
3563 if (name != nullptr)
3564 outs() << format(" %.*s", left, name);
3565 outs() << "\n";
3566
3567 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3568 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3569 m.imp);
3570 if (name != nullptr)
3571 outs() << " " << name;
3572 outs() << "\n";
3573
3574 p += sizeof(struct method32_t);
3575 offset += sizeof(struct method32_t);
3576 }
3577}
3578
Kevin Enderby846c0002015-04-16 17:19:59 +00003579static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3580 uint32_t offset, left, xleft;
3581 SectionRef S;
3582 struct objc_method_list_t method_list;
3583 struct objc_method_t method;
3584 const char *r, *methods, *name, *SymbolName;
3585 int32_t i;
3586
3587 r = get_pointer_32(p, offset, left, S, info, true);
3588 if (r == nullptr)
3589 return true;
3590
3591 outs() << "\n";
3592 if (left > sizeof(struct objc_method_list_t)) {
3593 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3594 } else {
3595 outs() << "\t\t objc_method_list extends past end of the section\n";
3596 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3597 memcpy(&method_list, r, left);
3598 }
3599 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3600 swapStruct(method_list);
3601
3602 outs() << "\t\t obsolete "
3603 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3604 outs() << "\t\t method_count " << method_list.method_count << "\n";
3605
3606 methods = r + sizeof(struct objc_method_list_t);
3607 for (i = 0; i < method_list.method_count; i++) {
3608 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3609 outs() << "\t\t remaining method's extend past the of the section\n";
3610 break;
3611 }
3612 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3613 sizeof(struct objc_method_t));
3614 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3615 swapStruct(method);
3616
3617 outs() << "\t\t method_name "
3618 << format("0x%08" PRIx32, method.method_name);
3619 if (info->verbose) {
3620 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3621 if (name != nullptr)
3622 outs() << format(" %.*s", xleft, name);
3623 else
3624 outs() << " (not in an __OBJC section)";
3625 }
3626 outs() << "\n";
3627
3628 outs() << "\t\t method_types "
3629 << format("0x%08" PRIx32, method.method_types);
3630 if (info->verbose) {
3631 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3632 if (name != nullptr)
3633 outs() << format(" %.*s", xleft, name);
3634 else
3635 outs() << " (not in an __OBJC section)";
3636 }
3637 outs() << "\n";
3638
3639 outs() << "\t\t method_imp "
3640 << format("0x%08" PRIx32, method.method_imp) << " ";
3641 if (info->verbose) {
3642 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3643 if (SymbolName != nullptr)
3644 outs() << SymbolName;
3645 }
3646 outs() << "\n";
3647 }
3648 return false;
3649}
3650
Kevin Enderby0fc11822015-04-01 20:57:01 +00003651static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3652 struct protocol_list64_t pl;
3653 uint64_t q, n_value;
3654 struct protocol64_t pc;
3655 const char *r;
3656 uint32_t offset, xoffset, left, i;
3657 SectionRef S, xS;
3658 const char *name, *sym_name;
3659
3660 r = get_pointer_64(p, offset, left, S, info);
3661 if (r == nullptr)
3662 return;
3663 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3664 if (left < sizeof(struct protocol_list64_t)) {
3665 memcpy(&pl, r, left);
3666 outs() << " (protocol_list_t entends past the end of the section)\n";
3667 } else
3668 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3669 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3670 swapStruct(pl);
3671 outs() << " count " << pl.count << "\n";
3672
3673 p += sizeof(struct protocol_list64_t);
3674 offset += sizeof(struct protocol_list64_t);
3675 for (i = 0; i < pl.count; i++) {
3676 r = get_pointer_64(p, offset, left, S, info);
3677 if (r == nullptr)
3678 return;
3679 q = 0;
3680 if (left < sizeof(uint64_t)) {
3681 memcpy(&q, r, left);
3682 outs() << " (protocol_t * entends past the end of the section)\n";
3683 } else
3684 memcpy(&q, r, sizeof(uint64_t));
3685 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3686 sys::swapByteOrder(q);
3687
3688 outs() << "\t\t list[" << i << "] ";
3689 sym_name = get_symbol_64(offset, S, info, n_value, q);
3690 if (n_value != 0) {
3691 if (info->verbose && sym_name != nullptr)
3692 outs() << sym_name;
3693 else
3694 outs() << format("0x%" PRIx64, n_value);
3695 if (q != 0)
3696 outs() << " + " << format("0x%" PRIx64, q);
3697 } else
3698 outs() << format("0x%" PRIx64, q);
3699 outs() << " (struct protocol_t *)\n";
3700
3701 r = get_pointer_64(q + n_value, offset, left, S, info);
3702 if (r == nullptr)
3703 return;
3704 memset(&pc, '\0', sizeof(struct protocol64_t));
3705 if (left < sizeof(struct protocol64_t)) {
3706 memcpy(&pc, r, left);
3707 outs() << " (protocol_t entends past the end of the section)\n";
3708 } else
3709 memcpy(&pc, r, sizeof(struct protocol64_t));
3710 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3711 swapStruct(pc);
3712
3713 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3714
3715 outs() << "\t\t\t name ";
3716 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3717 info, n_value, pc.name);
3718 if (n_value != 0) {
3719 if (info->verbose && sym_name != nullptr)
3720 outs() << sym_name;
3721 else
3722 outs() << format("0x%" PRIx64, n_value);
3723 if (pc.name != 0)
3724 outs() << " + " << format("0x%" PRIx64, pc.name);
3725 } else
3726 outs() << format("0x%" PRIx64, pc.name);
3727 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3728 if (name != nullptr)
3729 outs() << format(" %.*s", left, name);
3730 outs() << "\n";
3731
3732 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3733
3734 outs() << "\t\t instanceMethods ";
3735 sym_name =
3736 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3737 S, info, n_value, pc.instanceMethods);
3738 if (n_value != 0) {
3739 if (info->verbose && sym_name != nullptr)
3740 outs() << sym_name;
3741 else
3742 outs() << format("0x%" PRIx64, n_value);
3743 if (pc.instanceMethods != 0)
3744 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3745 } else
3746 outs() << format("0x%" PRIx64, pc.instanceMethods);
3747 outs() << " (struct method_list_t *)\n";
3748 if (pc.instanceMethods + n_value != 0)
3749 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3750
3751 outs() << "\t\t classMethods ";
3752 sym_name =
3753 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3754 info, n_value, pc.classMethods);
3755 if (n_value != 0) {
3756 if (info->verbose && sym_name != nullptr)
3757 outs() << sym_name;
3758 else
3759 outs() << format("0x%" PRIx64, n_value);
3760 if (pc.classMethods != 0)
3761 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3762 } else
3763 outs() << format("0x%" PRIx64, pc.classMethods);
3764 outs() << " (struct method_list_t *)\n";
3765 if (pc.classMethods + n_value != 0)
3766 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3767
3768 outs() << "\t optionalInstanceMethods "
3769 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3770 outs() << "\t optionalClassMethods "
3771 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3772 outs() << "\t instanceProperties "
3773 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3774
3775 p += sizeof(uint64_t);
3776 offset += sizeof(uint64_t);
3777 }
3778}
3779
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003780static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3781 struct protocol_list32_t pl;
3782 uint32_t q;
3783 struct protocol32_t pc;
3784 const char *r;
3785 uint32_t offset, xoffset, left, i;
3786 SectionRef S, xS;
3787 const char *name;
3788
3789 r = get_pointer_32(p, offset, left, S, info);
3790 if (r == nullptr)
3791 return;
3792 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3793 if (left < sizeof(struct protocol_list32_t)) {
3794 memcpy(&pl, r, left);
3795 outs() << " (protocol_list_t entends past the end of the section)\n";
3796 } else
3797 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3798 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3799 swapStruct(pl);
3800 outs() << " count " << pl.count << "\n";
3801
3802 p += sizeof(struct protocol_list32_t);
3803 offset += sizeof(struct protocol_list32_t);
3804 for (i = 0; i < pl.count; i++) {
3805 r = get_pointer_32(p, offset, left, S, info);
3806 if (r == nullptr)
3807 return;
3808 q = 0;
3809 if (left < sizeof(uint32_t)) {
3810 memcpy(&q, r, left);
3811 outs() << " (protocol_t * entends past the end of the section)\n";
3812 } else
3813 memcpy(&q, r, sizeof(uint32_t));
3814 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3815 sys::swapByteOrder(q);
3816 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3817 << " (struct protocol_t *)\n";
3818 r = get_pointer_32(q, offset, left, S, info);
3819 if (r == nullptr)
3820 return;
3821 memset(&pc, '\0', sizeof(struct protocol32_t));
3822 if (left < sizeof(struct protocol32_t)) {
3823 memcpy(&pc, r, left);
3824 outs() << " (protocol_t entends past the end of the section)\n";
3825 } else
3826 memcpy(&pc, r, sizeof(struct protocol32_t));
3827 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3828 swapStruct(pc);
3829 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3830 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3831 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3832 if (name != nullptr)
3833 outs() << format(" %.*s", left, name);
3834 outs() << "\n";
3835 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3836 outs() << "\t\t instanceMethods "
3837 << format("0x%" PRIx32, pc.instanceMethods)
3838 << " (struct method_list_t *)\n";
3839 if (pc.instanceMethods != 0)
3840 print_method_list32_t(pc.instanceMethods, info, "\t");
3841 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3842 << " (struct method_list_t *)\n";
3843 if (pc.classMethods != 0)
3844 print_method_list32_t(pc.classMethods, info, "\t");
3845 outs() << "\t optionalInstanceMethods "
3846 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3847 outs() << "\t optionalClassMethods "
3848 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3849 outs() << "\t instanceProperties "
3850 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3851 p += sizeof(uint32_t);
3852 offset += sizeof(uint32_t);
3853 }
3854}
3855
Kevin Enderby846c0002015-04-16 17:19:59 +00003856static void print_indent(uint32_t indent) {
3857 for (uint32_t i = 0; i < indent;) {
3858 if (indent - i >= 8) {
3859 outs() << "\t";
3860 i += 8;
3861 } else {
3862 for (uint32_t j = i; j < indent; j++)
3863 outs() << " ";
3864 return;
3865 }
3866 }
3867}
3868
3869static bool print_method_description_list(uint32_t p, uint32_t indent,
3870 struct DisassembleInfo *info) {
3871 uint32_t offset, left, xleft;
3872 SectionRef S;
3873 struct objc_method_description_list_t mdl;
3874 struct objc_method_description_t md;
3875 const char *r, *list, *name;
3876 int32_t i;
3877
3878 r = get_pointer_32(p, offset, left, S, info, true);
3879 if (r == nullptr)
3880 return true;
3881
3882 outs() << "\n";
3883 if (left > sizeof(struct objc_method_description_list_t)) {
3884 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3885 } else {
3886 print_indent(indent);
3887 outs() << " objc_method_description_list extends past end of the section\n";
3888 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3889 memcpy(&mdl, r, left);
3890 }
3891 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3892 swapStruct(mdl);
3893
3894 print_indent(indent);
3895 outs() << " count " << mdl.count << "\n";
3896
3897 list = r + sizeof(struct objc_method_description_list_t);
3898 for (i = 0; i < mdl.count; i++) {
3899 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3900 print_indent(indent);
3901 outs() << " remaining list entries extend past the of the section\n";
3902 break;
3903 }
3904 print_indent(indent);
3905 outs() << " list[" << i << "]\n";
3906 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3907 sizeof(struct objc_method_description_t));
3908 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3909 swapStruct(md);
3910
3911 print_indent(indent);
3912 outs() << " name " << format("0x%08" PRIx32, md.name);
3913 if (info->verbose) {
3914 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3915 if (name != nullptr)
3916 outs() << format(" %.*s", xleft, name);
3917 else
3918 outs() << " (not in an __OBJC section)";
3919 }
3920 outs() << "\n";
3921
3922 print_indent(indent);
3923 outs() << " types " << format("0x%08" PRIx32, md.types);
3924 if (info->verbose) {
3925 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3926 if (name != nullptr)
3927 outs() << format(" %.*s", xleft, name);
3928 else
3929 outs() << " (not in an __OBJC section)";
3930 }
3931 outs() << "\n";
3932 }
3933 return false;
3934}
3935
3936static bool print_protocol_list(uint32_t p, uint32_t indent,
3937 struct DisassembleInfo *info);
3938
3939static bool print_protocol(uint32_t p, uint32_t indent,
3940 struct DisassembleInfo *info) {
3941 uint32_t offset, left;
3942 SectionRef S;
3943 struct objc_protocol_t protocol;
3944 const char *r, *name;
3945
3946 r = get_pointer_32(p, offset, left, S, info, true);
3947 if (r == nullptr)
3948 return true;
3949
3950 outs() << "\n";
3951 if (left >= sizeof(struct objc_protocol_t)) {
3952 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3953 } else {
3954 print_indent(indent);
3955 outs() << " Protocol extends past end of the section\n";
3956 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3957 memcpy(&protocol, r, left);
3958 }
3959 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3960 swapStruct(protocol);
3961
3962 print_indent(indent);
3963 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3964 << "\n";
3965
3966 print_indent(indent);
3967 outs() << " protocol_name "
3968 << format("0x%08" PRIx32, protocol.protocol_name);
3969 if (info->verbose) {
3970 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3971 if (name != nullptr)
3972 outs() << format(" %.*s", left, name);
3973 else
3974 outs() << " (not in an __OBJC section)";
3975 }
3976 outs() << "\n";
3977
3978 print_indent(indent);
3979 outs() << " protocol_list "
3980 << format("0x%08" PRIx32, protocol.protocol_list);
3981 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3982 outs() << " (not in an __OBJC section)\n";
3983
3984 print_indent(indent);
3985 outs() << " instance_methods "
3986 << format("0x%08" PRIx32, protocol.instance_methods);
3987 if (print_method_description_list(protocol.instance_methods, indent, info))
3988 outs() << " (not in an __OBJC section)\n";
3989
3990 print_indent(indent);
3991 outs() << " class_methods "
3992 << format("0x%08" PRIx32, protocol.class_methods);
3993 if (print_method_description_list(protocol.class_methods, indent, info))
3994 outs() << " (not in an __OBJC section)\n";
3995
3996 return false;
3997}
3998
3999static bool print_protocol_list(uint32_t p, uint32_t indent,
4000 struct DisassembleInfo *info) {
4001 uint32_t offset, left, l;
4002 SectionRef S;
4003 struct objc_protocol_list_t protocol_list;
4004 const char *r, *list;
4005 int32_t i;
4006
4007 r = get_pointer_32(p, offset, left, S, info, true);
4008 if (r == nullptr)
4009 return true;
4010
4011 outs() << "\n";
4012 if (left > sizeof(struct objc_protocol_list_t)) {
4013 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4014 } else {
4015 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4016 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4017 memcpy(&protocol_list, r, left);
4018 }
4019 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4020 swapStruct(protocol_list);
4021
4022 print_indent(indent);
4023 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4024 << "\n";
4025 print_indent(indent);
4026 outs() << " count " << protocol_list.count << "\n";
4027
4028 list = r + sizeof(struct objc_protocol_list_t);
4029 for (i = 0; i < protocol_list.count; i++) {
4030 if ((i + 1) * sizeof(uint32_t) > left) {
4031 outs() << "\t\t remaining list entries extend past the of the section\n";
4032 break;
4033 }
4034 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4035 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4036 sys::swapByteOrder(l);
4037
4038 print_indent(indent);
4039 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4040 if (print_protocol(l, indent, info))
4041 outs() << "(not in an __OBJC section)\n";
4042 }
4043 return false;
4044}
4045
Kevin Enderby0fc11822015-04-01 20:57:01 +00004046static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4047 struct ivar_list64_t il;
4048 struct ivar64_t i;
4049 const char *r;
4050 uint32_t offset, xoffset, left, j;
4051 SectionRef S, xS;
4052 const char *name, *sym_name, *ivar_offset_p;
4053 uint64_t ivar_offset, n_value;
4054
4055 r = get_pointer_64(p, offset, left, S, info);
4056 if (r == nullptr)
4057 return;
4058 memset(&il, '\0', sizeof(struct ivar_list64_t));
4059 if (left < sizeof(struct ivar_list64_t)) {
4060 memcpy(&il, r, left);
4061 outs() << " (ivar_list_t entends past the end of the section)\n";
4062 } else
4063 memcpy(&il, r, sizeof(struct ivar_list64_t));
4064 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4065 swapStruct(il);
4066 outs() << " entsize " << il.entsize << "\n";
4067 outs() << " count " << il.count << "\n";
4068
4069 p += sizeof(struct ivar_list64_t);
4070 offset += sizeof(struct ivar_list64_t);
4071 for (j = 0; j < il.count; j++) {
4072 r = get_pointer_64(p, offset, left, S, info);
4073 if (r == nullptr)
4074 return;
4075 memset(&i, '\0', sizeof(struct ivar64_t));
4076 if (left < sizeof(struct ivar64_t)) {
4077 memcpy(&i, r, left);
4078 outs() << " (ivar_t entends past the end of the section)\n";
4079 } else
4080 memcpy(&i, r, sizeof(struct ivar64_t));
4081 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4082 swapStruct(i);
4083
4084 outs() << "\t\t\t offset ";
4085 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4086 info, n_value, i.offset);
4087 if (n_value != 0) {
4088 if (info->verbose && sym_name != nullptr)
4089 outs() << sym_name;
4090 else
4091 outs() << format("0x%" PRIx64, n_value);
4092 if (i.offset != 0)
4093 outs() << " + " << format("0x%" PRIx64, i.offset);
4094 } else
4095 outs() << format("0x%" PRIx64, i.offset);
4096 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4097 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4098 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4099 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4100 sys::swapByteOrder(ivar_offset);
4101 outs() << " " << ivar_offset << "\n";
4102 } else
4103 outs() << "\n";
4104
4105 outs() << "\t\t\t name ";
4106 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4107 n_value, i.name);
4108 if (n_value != 0) {
4109 if (info->verbose && sym_name != nullptr)
4110 outs() << sym_name;
4111 else
4112 outs() << format("0x%" PRIx64, n_value);
4113 if (i.name != 0)
4114 outs() << " + " << format("0x%" PRIx64, i.name);
4115 } else
4116 outs() << format("0x%" PRIx64, i.name);
4117 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4118 if (name != nullptr)
4119 outs() << format(" %.*s", left, name);
4120 outs() << "\n";
4121
4122 outs() << "\t\t\t type ";
4123 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4124 n_value, i.name);
4125 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4126 if (n_value != 0) {
4127 if (info->verbose && sym_name != nullptr)
4128 outs() << sym_name;
4129 else
4130 outs() << format("0x%" PRIx64, n_value);
4131 if (i.type != 0)
4132 outs() << " + " << format("0x%" PRIx64, i.type);
4133 } else
4134 outs() << format("0x%" PRIx64, i.type);
4135 if (name != nullptr)
4136 outs() << format(" %.*s", left, name);
4137 outs() << "\n";
4138
4139 outs() << "\t\t\talignment " << i.alignment << "\n";
4140 outs() << "\t\t\t size " << i.size << "\n";
4141
4142 p += sizeof(struct ivar64_t);
4143 offset += sizeof(struct ivar64_t);
4144 }
4145}
4146
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004147static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4148 struct ivar_list32_t il;
4149 struct ivar32_t i;
4150 const char *r;
4151 uint32_t offset, xoffset, left, j;
4152 SectionRef S, xS;
4153 const char *name, *ivar_offset_p;
4154 uint32_t ivar_offset;
4155
4156 r = get_pointer_32(p, offset, left, S, info);
4157 if (r == nullptr)
4158 return;
4159 memset(&il, '\0', sizeof(struct ivar_list32_t));
4160 if (left < sizeof(struct ivar_list32_t)) {
4161 memcpy(&il, r, left);
4162 outs() << " (ivar_list_t entends past the end of the section)\n";
4163 } else
4164 memcpy(&il, r, sizeof(struct ivar_list32_t));
4165 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4166 swapStruct(il);
4167 outs() << " entsize " << il.entsize << "\n";
4168 outs() << " count " << il.count << "\n";
4169
4170 p += sizeof(struct ivar_list32_t);
4171 offset += sizeof(struct ivar_list32_t);
4172 for (j = 0; j < il.count; j++) {
4173 r = get_pointer_32(p, offset, left, S, info);
4174 if (r == nullptr)
4175 return;
4176 memset(&i, '\0', sizeof(struct ivar32_t));
4177 if (left < sizeof(struct ivar32_t)) {
4178 memcpy(&i, r, left);
4179 outs() << " (ivar_t entends past the end of the section)\n";
4180 } else
4181 memcpy(&i, r, sizeof(struct ivar32_t));
4182 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4183 swapStruct(i);
4184
4185 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4186 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4187 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4188 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4189 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4190 sys::swapByteOrder(ivar_offset);
4191 outs() << " " << ivar_offset << "\n";
4192 } else
4193 outs() << "\n";
4194
4195 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4196 name = get_pointer_32(i.name, xoffset, left, xS, info);
4197 if (name != nullptr)
4198 outs() << format(" %.*s", left, name);
4199 outs() << "\n";
4200
4201 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4202 name = get_pointer_32(i.type, xoffset, left, xS, info);
4203 if (name != nullptr)
4204 outs() << format(" %.*s", left, name);
4205 outs() << "\n";
4206
4207 outs() << "\t\t\talignment " << i.alignment << "\n";
4208 outs() << "\t\t\t size " << i.size << "\n";
4209
4210 p += sizeof(struct ivar32_t);
4211 offset += sizeof(struct ivar32_t);
4212 }
4213}
4214
Kevin Enderby0fc11822015-04-01 20:57:01 +00004215static void print_objc_property_list64(uint64_t p,
4216 struct DisassembleInfo *info) {
4217 struct objc_property_list64 opl;
4218 struct objc_property64 op;
4219 const char *r;
4220 uint32_t offset, xoffset, left, j;
4221 SectionRef S, xS;
4222 const char *name, *sym_name;
4223 uint64_t n_value;
4224
4225 r = get_pointer_64(p, offset, left, S, info);
4226 if (r == nullptr)
4227 return;
4228 memset(&opl, '\0', sizeof(struct objc_property_list64));
4229 if (left < sizeof(struct objc_property_list64)) {
4230 memcpy(&opl, r, left);
4231 outs() << " (objc_property_list entends past the end of the section)\n";
4232 } else
4233 memcpy(&opl, r, sizeof(struct objc_property_list64));
4234 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4235 swapStruct(opl);
4236 outs() << " entsize " << opl.entsize << "\n";
4237 outs() << " count " << opl.count << "\n";
4238
4239 p += sizeof(struct objc_property_list64);
4240 offset += sizeof(struct objc_property_list64);
4241 for (j = 0; j < opl.count; j++) {
4242 r = get_pointer_64(p, offset, left, S, info);
4243 if (r == nullptr)
4244 return;
4245 memset(&op, '\0', sizeof(struct objc_property64));
4246 if (left < sizeof(struct objc_property64)) {
4247 memcpy(&op, r, left);
4248 outs() << " (objc_property entends past the end of the section)\n";
4249 } else
4250 memcpy(&op, r, sizeof(struct objc_property64));
4251 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4252 swapStruct(op);
4253
4254 outs() << "\t\t\t name ";
4255 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4256 info, n_value, op.name);
4257 if (n_value != 0) {
4258 if (info->verbose && sym_name != nullptr)
4259 outs() << sym_name;
4260 else
4261 outs() << format("0x%" PRIx64, n_value);
4262 if (op.name != 0)
4263 outs() << " + " << format("0x%" PRIx64, op.name);
4264 } else
4265 outs() << format("0x%" PRIx64, op.name);
4266 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4267 if (name != nullptr)
4268 outs() << format(" %.*s", left, name);
4269 outs() << "\n";
4270
4271 outs() << "\t\t\tattributes ";
4272 sym_name =
4273 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4274 info, n_value, op.attributes);
4275 if (n_value != 0) {
4276 if (info->verbose && sym_name != nullptr)
4277 outs() << sym_name;
4278 else
4279 outs() << format("0x%" PRIx64, n_value);
4280 if (op.attributes != 0)
4281 outs() << " + " << format("0x%" PRIx64, op.attributes);
4282 } else
4283 outs() << format("0x%" PRIx64, op.attributes);
4284 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4285 if (name != nullptr)
4286 outs() << format(" %.*s", left, name);
4287 outs() << "\n";
4288
4289 p += sizeof(struct objc_property64);
4290 offset += sizeof(struct objc_property64);
4291 }
4292}
4293
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004294static void print_objc_property_list32(uint32_t p,
4295 struct DisassembleInfo *info) {
4296 struct objc_property_list32 opl;
4297 struct objc_property32 op;
4298 const char *r;
4299 uint32_t offset, xoffset, left, j;
4300 SectionRef S, xS;
4301 const char *name;
4302
4303 r = get_pointer_32(p, offset, left, S, info);
4304 if (r == nullptr)
4305 return;
4306 memset(&opl, '\0', sizeof(struct objc_property_list32));
4307 if (left < sizeof(struct objc_property_list32)) {
4308 memcpy(&opl, r, left);
4309 outs() << " (objc_property_list entends past the end of the section)\n";
4310 } else
4311 memcpy(&opl, r, sizeof(struct objc_property_list32));
4312 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4313 swapStruct(opl);
4314 outs() << " entsize " << opl.entsize << "\n";
4315 outs() << " count " << opl.count << "\n";
4316
4317 p += sizeof(struct objc_property_list32);
4318 offset += sizeof(struct objc_property_list32);
4319 for (j = 0; j < opl.count; j++) {
4320 r = get_pointer_32(p, offset, left, S, info);
4321 if (r == nullptr)
4322 return;
4323 memset(&op, '\0', sizeof(struct objc_property32));
4324 if (left < sizeof(struct objc_property32)) {
4325 memcpy(&op, r, left);
4326 outs() << " (objc_property entends past the end of the section)\n";
4327 } else
4328 memcpy(&op, r, sizeof(struct objc_property32));
4329 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4330 swapStruct(op);
4331
4332 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4333 name = get_pointer_32(op.name, xoffset, left, xS, info);
4334 if (name != nullptr)
4335 outs() << format(" %.*s", left, name);
4336 outs() << "\n";
4337
4338 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4339 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4340 if (name != nullptr)
4341 outs() << format(" %.*s", left, name);
4342 outs() << "\n";
4343
4344 p += sizeof(struct objc_property32);
4345 offset += sizeof(struct objc_property32);
4346 }
4347}
4348
Richard Smith81ff44d2015-10-09 22:09:56 +00004349static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004350 bool &is_meta_class) {
4351 struct class_ro64_t cro;
4352 const char *r;
4353 uint32_t offset, xoffset, left;
4354 SectionRef S, xS;
4355 const char *name, *sym_name;
4356 uint64_t n_value;
4357
4358 r = get_pointer_64(p, offset, left, S, info);
4359 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004360 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004361 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004362 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4363 swapStruct(cro);
4364 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4365 if (cro.flags & RO_META)
4366 outs() << " RO_META";
4367 if (cro.flags & RO_ROOT)
4368 outs() << " RO_ROOT";
4369 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4370 outs() << " RO_HAS_CXX_STRUCTORS";
4371 outs() << "\n";
4372 outs() << " instanceStart " << cro.instanceStart << "\n";
4373 outs() << " instanceSize " << cro.instanceSize << "\n";
4374 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4375 << "\n";
4376 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4377 << "\n";
4378 print_layout_map64(cro.ivarLayout, info);
4379
4380 outs() << " name ";
4381 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4382 info, n_value, cro.name);
4383 if (n_value != 0) {
4384 if (info->verbose && sym_name != nullptr)
4385 outs() << sym_name;
4386 else
4387 outs() << format("0x%" PRIx64, n_value);
4388 if (cro.name != 0)
4389 outs() << " + " << format("0x%" PRIx64, cro.name);
4390 } else
4391 outs() << format("0x%" PRIx64, cro.name);
4392 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4393 if (name != nullptr)
4394 outs() << format(" %.*s", left, name);
4395 outs() << "\n";
4396
4397 outs() << " baseMethods ";
4398 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4399 S, info, n_value, cro.baseMethods);
4400 if (n_value != 0) {
4401 if (info->verbose && sym_name != nullptr)
4402 outs() << sym_name;
4403 else
4404 outs() << format("0x%" PRIx64, n_value);
4405 if (cro.baseMethods != 0)
4406 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4407 } else
4408 outs() << format("0x%" PRIx64, cro.baseMethods);
4409 outs() << " (struct method_list_t *)\n";
4410 if (cro.baseMethods + n_value != 0)
4411 print_method_list64_t(cro.baseMethods + n_value, info, "");
4412
4413 outs() << " baseProtocols ";
4414 sym_name =
4415 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4416 info, n_value, cro.baseProtocols);
4417 if (n_value != 0) {
4418 if (info->verbose && sym_name != nullptr)
4419 outs() << sym_name;
4420 else
4421 outs() << format("0x%" PRIx64, n_value);
4422 if (cro.baseProtocols != 0)
4423 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4424 } else
4425 outs() << format("0x%" PRIx64, cro.baseProtocols);
4426 outs() << "\n";
4427 if (cro.baseProtocols + n_value != 0)
4428 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4429
4430 outs() << " ivars ";
4431 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004432 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004433 if (n_value != 0) {
4434 if (info->verbose && sym_name != nullptr)
4435 outs() << sym_name;
4436 else
4437 outs() << format("0x%" PRIx64, n_value);
4438 if (cro.ivars != 0)
4439 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4440 } else
4441 outs() << format("0x%" PRIx64, cro.ivars);
4442 outs() << "\n";
4443 if (cro.ivars + n_value != 0)
4444 print_ivar_list64_t(cro.ivars + n_value, info);
4445
4446 outs() << " weakIvarLayout ";
4447 sym_name =
4448 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4449 info, n_value, cro.weakIvarLayout);
4450 if (n_value != 0) {
4451 if (info->verbose && sym_name != nullptr)
4452 outs() << sym_name;
4453 else
4454 outs() << format("0x%" PRIx64, n_value);
4455 if (cro.weakIvarLayout != 0)
4456 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4457 } else
4458 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4459 outs() << "\n";
4460 print_layout_map64(cro.weakIvarLayout + n_value, info);
4461
4462 outs() << " baseProperties ";
4463 sym_name =
4464 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4465 info, n_value, cro.baseProperties);
4466 if (n_value != 0) {
4467 if (info->verbose && sym_name != nullptr)
4468 outs() << sym_name;
4469 else
4470 outs() << format("0x%" PRIx64, n_value);
4471 if (cro.baseProperties != 0)
4472 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4473 } else
4474 outs() << format("0x%" PRIx64, cro.baseProperties);
4475 outs() << "\n";
4476 if (cro.baseProperties + n_value != 0)
4477 print_objc_property_list64(cro.baseProperties + n_value, info);
4478
Rafael Espindolab9091322015-10-24 23:19:10 +00004479 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004480 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004481}
4482
Richard Smith81ff44d2015-10-09 22:09:56 +00004483static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004484 bool &is_meta_class) {
4485 struct class_ro32_t cro;
4486 const char *r;
4487 uint32_t offset, xoffset, left;
4488 SectionRef S, xS;
4489 const char *name;
4490
4491 r = get_pointer_32(p, offset, left, S, info);
4492 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004493 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004494 memset(&cro, '\0', sizeof(struct class_ro32_t));
4495 if (left < sizeof(struct class_ro32_t)) {
4496 memcpy(&cro, r, left);
4497 outs() << " (class_ro_t entends past the end of the section)\n";
4498 } else
4499 memcpy(&cro, r, sizeof(struct class_ro32_t));
4500 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4501 swapStruct(cro);
4502 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4503 if (cro.flags & RO_META)
4504 outs() << " RO_META";
4505 if (cro.flags & RO_ROOT)
4506 outs() << " RO_ROOT";
4507 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4508 outs() << " RO_HAS_CXX_STRUCTORS";
4509 outs() << "\n";
4510 outs() << " instanceStart " << cro.instanceStart << "\n";
4511 outs() << " instanceSize " << cro.instanceSize << "\n";
4512 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4513 << "\n";
4514 print_layout_map32(cro.ivarLayout, info);
4515
4516 outs() << " name " << format("0x%" PRIx32, cro.name);
4517 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4518 if (name != nullptr)
4519 outs() << format(" %.*s", left, name);
4520 outs() << "\n";
4521
4522 outs() << " baseMethods "
4523 << format("0x%" PRIx32, cro.baseMethods)
4524 << " (struct method_list_t *)\n";
4525 if (cro.baseMethods != 0)
4526 print_method_list32_t(cro.baseMethods, info, "");
4527
4528 outs() << " baseProtocols "
4529 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4530 if (cro.baseProtocols != 0)
4531 print_protocol_list32_t(cro.baseProtocols, info);
4532 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4533 << "\n";
4534 if (cro.ivars != 0)
4535 print_ivar_list32_t(cro.ivars, info);
4536 outs() << " weakIvarLayout "
4537 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4538 print_layout_map32(cro.weakIvarLayout, info);
4539 outs() << " baseProperties "
4540 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4541 if (cro.baseProperties != 0)
4542 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004543 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004544 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004545}
4546
Kevin Enderby0fc11822015-04-01 20:57:01 +00004547static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4548 struct class64_t c;
4549 const char *r;
4550 uint32_t offset, left;
4551 SectionRef S;
4552 const char *name;
4553 uint64_t isa_n_value, n_value;
4554
4555 r = get_pointer_64(p, offset, left, S, info);
4556 if (r == nullptr || left < sizeof(struct class64_t))
4557 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004558 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004559 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4560 swapStruct(c);
4561
4562 outs() << " isa " << format("0x%" PRIx64, c.isa);
4563 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4564 isa_n_value, c.isa);
4565 if (name != nullptr)
4566 outs() << " " << name;
4567 outs() << "\n";
4568
4569 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4570 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4571 n_value, c.superclass);
4572 if (name != nullptr)
4573 outs() << " " << name;
4574 outs() << "\n";
4575
4576 outs() << " cache " << format("0x%" PRIx64, c.cache);
4577 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4578 n_value, c.cache);
4579 if (name != nullptr)
4580 outs() << " " << name;
4581 outs() << "\n";
4582
4583 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4584 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4585 n_value, c.vtable);
4586 if (name != nullptr)
4587 outs() << " " << name;
4588 outs() << "\n";
4589
4590 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4591 n_value, c.data);
4592 outs() << " data ";
4593 if (n_value != 0) {
4594 if (info->verbose && name != nullptr)
4595 outs() << name;
4596 else
4597 outs() << format("0x%" PRIx64, n_value);
4598 if (c.data != 0)
4599 outs() << " + " << format("0x%" PRIx64, c.data);
4600 } else
4601 outs() << format("0x%" PRIx64, c.data);
4602 outs() << " (struct class_ro_t *)";
4603
4604 // This is a Swift class if some of the low bits of the pointer are set.
4605 if ((c.data + n_value) & 0x7)
4606 outs() << " Swift class";
4607 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004608 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004609 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4610 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004611
Kevin Enderbyaac75382015-10-08 16:56:35 +00004612 if (!is_meta_class &&
4613 c.isa + isa_n_value != p &&
4614 c.isa + isa_n_value != 0 &&
4615 info->depth < 100) {
4616 info->depth++;
4617 outs() << "Meta Class\n";
4618 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004619 }
4620}
4621
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004622static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4623 struct class32_t c;
4624 const char *r;
4625 uint32_t offset, left;
4626 SectionRef S;
4627 const char *name;
4628
4629 r = get_pointer_32(p, offset, left, S, info);
4630 if (r == nullptr)
4631 return;
4632 memset(&c, '\0', sizeof(struct class32_t));
4633 if (left < sizeof(struct class32_t)) {
4634 memcpy(&c, r, left);
4635 outs() << " (class_t entends past the end of the section)\n";
4636 } else
4637 memcpy(&c, r, sizeof(struct class32_t));
4638 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4639 swapStruct(c);
4640
4641 outs() << " isa " << format("0x%" PRIx32, c.isa);
4642 name =
4643 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4644 if (name != nullptr)
4645 outs() << " " << name;
4646 outs() << "\n";
4647
4648 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4649 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4650 c.superclass);
4651 if (name != nullptr)
4652 outs() << " " << name;
4653 outs() << "\n";
4654
4655 outs() << " cache " << format("0x%" PRIx32, c.cache);
4656 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4657 c.cache);
4658 if (name != nullptr)
4659 outs() << " " << name;
4660 outs() << "\n";
4661
4662 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4663 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4664 c.vtable);
4665 if (name != nullptr)
4666 outs() << " " << name;
4667 outs() << "\n";
4668
4669 name =
4670 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4671 outs() << " data " << format("0x%" PRIx32, c.data)
4672 << " (struct class_ro_t *)";
4673
4674 // This is a Swift class if some of the low bits of the pointer are set.
4675 if (c.data & 0x3)
4676 outs() << " Swift class";
4677 outs() << "\n";
4678 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004679 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4680 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004681
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004682 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004683 outs() << "Meta Class\n";
4684 print_class32_t(c.isa, info);
4685 }
4686}
4687
Kevin Enderby846c0002015-04-16 17:19:59 +00004688static void print_objc_class_t(struct objc_class_t *objc_class,
4689 struct DisassembleInfo *info) {
4690 uint32_t offset, left, xleft;
4691 const char *name, *p, *ivar_list;
4692 SectionRef S;
4693 int32_t i;
4694 struct objc_ivar_list_t objc_ivar_list;
4695 struct objc_ivar_t ivar;
4696
4697 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4698 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4699 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4700 if (name != nullptr)
4701 outs() << format(" %.*s", left, name);
4702 else
4703 outs() << " (not in an __OBJC section)";
4704 }
4705 outs() << "\n";
4706
4707 outs() << "\t super_class "
4708 << format("0x%08" PRIx32, objc_class->super_class);
4709 if (info->verbose) {
4710 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4711 if (name != nullptr)
4712 outs() << format(" %.*s", left, name);
4713 else
4714 outs() << " (not in an __OBJC section)";
4715 }
4716 outs() << "\n";
4717
4718 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4719 if (info->verbose) {
4720 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4721 if (name != nullptr)
4722 outs() << format(" %.*s", left, name);
4723 else
4724 outs() << " (not in an __OBJC section)";
4725 }
4726 outs() << "\n";
4727
4728 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4729 << "\n";
4730
4731 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4732 if (info->verbose) {
4733 if (CLS_GETINFO(objc_class, CLS_CLASS))
4734 outs() << " CLS_CLASS";
4735 else if (CLS_GETINFO(objc_class, CLS_META))
4736 outs() << " CLS_META";
4737 }
4738 outs() << "\n";
4739
4740 outs() << "\t instance_size "
4741 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4742
4743 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4744 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4745 if (p != nullptr) {
4746 if (left > sizeof(struct objc_ivar_list_t)) {
4747 outs() << "\n";
4748 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4749 } else {
4750 outs() << " (entends past the end of the section)\n";
4751 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4752 memcpy(&objc_ivar_list, p, left);
4753 }
4754 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4755 swapStruct(objc_ivar_list);
4756 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4757 ivar_list = p + sizeof(struct objc_ivar_list_t);
4758 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4759 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4760 outs() << "\t\t remaining ivar's extend past the of the section\n";
4761 break;
4762 }
4763 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4764 sizeof(struct objc_ivar_t));
4765 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4766 swapStruct(ivar);
4767
4768 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4769 if (info->verbose) {
4770 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4771 if (name != nullptr)
4772 outs() << format(" %.*s", xleft, name);
4773 else
4774 outs() << " (not in an __OBJC section)";
4775 }
4776 outs() << "\n";
4777
4778 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4779 if (info->verbose) {
4780 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4781 if (name != nullptr)
4782 outs() << format(" %.*s", xleft, name);
4783 else
4784 outs() << " (not in an __OBJC section)";
4785 }
4786 outs() << "\n";
4787
4788 outs() << "\t\t ivar_offset "
4789 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4790 }
4791 } else {
4792 outs() << " (not in an __OBJC section)\n";
4793 }
4794
4795 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4796 if (print_method_list(objc_class->methodLists, info))
4797 outs() << " (not in an __OBJC section)\n";
4798
4799 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4800 << "\n";
4801
4802 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4803 if (print_protocol_list(objc_class->protocols, 16, info))
4804 outs() << " (not in an __OBJC section)\n";
4805}
4806
4807static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4808 struct DisassembleInfo *info) {
4809 uint32_t offset, left;
4810 const char *name;
4811 SectionRef S;
4812
4813 outs() << "\t category name "
4814 << format("0x%08" PRIx32, objc_category->category_name);
4815 if (info->verbose) {
4816 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4817 true);
4818 if (name != nullptr)
4819 outs() << format(" %.*s", left, name);
4820 else
4821 outs() << " (not in an __OBJC section)";
4822 }
4823 outs() << "\n";
4824
4825 outs() << "\t\t class name "
4826 << format("0x%08" PRIx32, objc_category->class_name);
4827 if (info->verbose) {
4828 name =
4829 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4830 if (name != nullptr)
4831 outs() << format(" %.*s", left, name);
4832 else
4833 outs() << " (not in an __OBJC section)";
4834 }
4835 outs() << "\n";
4836
4837 outs() << "\t instance methods "
4838 << format("0x%08" PRIx32, objc_category->instance_methods);
4839 if (print_method_list(objc_category->instance_methods, info))
4840 outs() << " (not in an __OBJC section)\n";
4841
4842 outs() << "\t class methods "
4843 << format("0x%08" PRIx32, objc_category->class_methods);
4844 if (print_method_list(objc_category->class_methods, info))
4845 outs() << " (not in an __OBJC section)\n";
4846}
4847
Kevin Enderby0fc11822015-04-01 20:57:01 +00004848static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4849 struct category64_t c;
4850 const char *r;
4851 uint32_t offset, xoffset, left;
4852 SectionRef S, xS;
4853 const char *name, *sym_name;
4854 uint64_t n_value;
4855
4856 r = get_pointer_64(p, offset, left, S, info);
4857 if (r == nullptr)
4858 return;
4859 memset(&c, '\0', sizeof(struct category64_t));
4860 if (left < sizeof(struct category64_t)) {
4861 memcpy(&c, r, left);
4862 outs() << " (category_t entends past the end of the section)\n";
4863 } else
4864 memcpy(&c, r, sizeof(struct category64_t));
4865 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4866 swapStruct(c);
4867
4868 outs() << " name ";
4869 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4870 info, n_value, c.name);
4871 if (n_value != 0) {
4872 if (info->verbose && sym_name != nullptr)
4873 outs() << sym_name;
4874 else
4875 outs() << format("0x%" PRIx64, n_value);
4876 if (c.name != 0)
4877 outs() << " + " << format("0x%" PRIx64, c.name);
4878 } else
4879 outs() << format("0x%" PRIx64, c.name);
4880 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4881 if (name != nullptr)
4882 outs() << format(" %.*s", left, name);
4883 outs() << "\n";
4884
4885 outs() << " cls ";
4886 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4887 n_value, c.cls);
4888 if (n_value != 0) {
4889 if (info->verbose && sym_name != nullptr)
4890 outs() << sym_name;
4891 else
4892 outs() << format("0x%" PRIx64, n_value);
4893 if (c.cls != 0)
4894 outs() << " + " << format("0x%" PRIx64, c.cls);
4895 } else
4896 outs() << format("0x%" PRIx64, c.cls);
4897 outs() << "\n";
4898 if (c.cls + n_value != 0)
4899 print_class64_t(c.cls + n_value, info);
4900
4901 outs() << " instanceMethods ";
4902 sym_name =
4903 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4904 info, n_value, c.instanceMethods);
4905 if (n_value != 0) {
4906 if (info->verbose && sym_name != nullptr)
4907 outs() << sym_name;
4908 else
4909 outs() << format("0x%" PRIx64, n_value);
4910 if (c.instanceMethods != 0)
4911 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4912 } else
4913 outs() << format("0x%" PRIx64, c.instanceMethods);
4914 outs() << "\n";
4915 if (c.instanceMethods + n_value != 0)
4916 print_method_list64_t(c.instanceMethods + n_value, info, "");
4917
4918 outs() << " classMethods ";
4919 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4920 S, info, n_value, c.classMethods);
4921 if (n_value != 0) {
4922 if (info->verbose && sym_name != nullptr)
4923 outs() << sym_name;
4924 else
4925 outs() << format("0x%" PRIx64, n_value);
4926 if (c.classMethods != 0)
4927 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4928 } else
4929 outs() << format("0x%" PRIx64, c.classMethods);
4930 outs() << "\n";
4931 if (c.classMethods + n_value != 0)
4932 print_method_list64_t(c.classMethods + n_value, info, "");
4933
4934 outs() << " protocols ";
4935 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4936 info, n_value, c.protocols);
4937 if (n_value != 0) {
4938 if (info->verbose && sym_name != nullptr)
4939 outs() << sym_name;
4940 else
4941 outs() << format("0x%" PRIx64, n_value);
4942 if (c.protocols != 0)
4943 outs() << " + " << format("0x%" PRIx64, c.protocols);
4944 } else
4945 outs() << format("0x%" PRIx64, c.protocols);
4946 outs() << "\n";
4947 if (c.protocols + n_value != 0)
4948 print_protocol_list64_t(c.protocols + n_value, info);
4949
4950 outs() << "instanceProperties ";
4951 sym_name =
4952 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4953 S, info, n_value, c.instanceProperties);
4954 if (n_value != 0) {
4955 if (info->verbose && sym_name != nullptr)
4956 outs() << sym_name;
4957 else
4958 outs() << format("0x%" PRIx64, n_value);
4959 if (c.instanceProperties != 0)
4960 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4961 } else
4962 outs() << format("0x%" PRIx64, c.instanceProperties);
4963 outs() << "\n";
4964 if (c.instanceProperties + n_value != 0)
4965 print_objc_property_list64(c.instanceProperties + n_value, info);
4966}
4967
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004968static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4969 struct category32_t c;
4970 const char *r;
4971 uint32_t offset, left;
4972 SectionRef S, xS;
4973 const char *name;
4974
4975 r = get_pointer_32(p, offset, left, S, info);
4976 if (r == nullptr)
4977 return;
4978 memset(&c, '\0', sizeof(struct category32_t));
4979 if (left < sizeof(struct category32_t)) {
4980 memcpy(&c, r, left);
4981 outs() << " (category_t entends past the end of the section)\n";
4982 } else
4983 memcpy(&c, r, sizeof(struct category32_t));
4984 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4985 swapStruct(c);
4986
4987 outs() << " name " << format("0x%" PRIx32, c.name);
4988 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4989 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004990 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004991 outs() << " " << name;
4992 outs() << "\n";
4993
4994 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4995 if (c.cls != 0)
4996 print_class32_t(c.cls, info);
4997 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4998 << "\n";
4999 if (c.instanceMethods != 0)
5000 print_method_list32_t(c.instanceMethods, info, "");
5001 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5002 << "\n";
5003 if (c.classMethods != 0)
5004 print_method_list32_t(c.classMethods, info, "");
5005 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5006 if (c.protocols != 0)
5007 print_protocol_list32_t(c.protocols, info);
5008 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5009 << "\n";
5010 if (c.instanceProperties != 0)
5011 print_objc_property_list32(c.instanceProperties, info);
5012}
5013
Kevin Enderby0fc11822015-04-01 20:57:01 +00005014static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5015 uint32_t i, left, offset, xoffset;
5016 uint64_t p, n_value;
5017 struct message_ref64 mr;
5018 const char *name, *sym_name;
5019 const char *r;
5020 SectionRef xS;
5021
5022 if (S == SectionRef())
5023 return;
5024
5025 StringRef SectName;
5026 S.getName(SectName);
5027 DataRefImpl Ref = S.getRawDataRefImpl();
5028 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5029 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5030 offset = 0;
5031 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5032 p = S.getAddress() + i;
5033 r = get_pointer_64(p, offset, left, S, info);
5034 if (r == nullptr)
5035 return;
5036 memset(&mr, '\0', sizeof(struct message_ref64));
5037 if (left < sizeof(struct message_ref64)) {
5038 memcpy(&mr, r, left);
5039 outs() << " (message_ref entends past the end of the section)\n";
5040 } else
5041 memcpy(&mr, r, sizeof(struct message_ref64));
5042 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5043 swapStruct(mr);
5044
5045 outs() << " imp ";
5046 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5047 n_value, mr.imp);
5048 if (n_value != 0) {
5049 outs() << format("0x%" PRIx64, n_value) << " ";
5050 if (mr.imp != 0)
5051 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5052 } else
5053 outs() << format("0x%" PRIx64, mr.imp) << " ";
5054 if (name != nullptr)
5055 outs() << " " << name;
5056 outs() << "\n";
5057
5058 outs() << " sel ";
5059 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5060 info, n_value, mr.sel);
5061 if (n_value != 0) {
5062 if (info->verbose && sym_name != nullptr)
5063 outs() << sym_name;
5064 else
5065 outs() << format("0x%" PRIx64, n_value);
5066 if (mr.sel != 0)
5067 outs() << " + " << format("0x%" PRIx64, mr.sel);
5068 } else
5069 outs() << format("0x%" PRIx64, mr.sel);
5070 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5071 if (name != nullptr)
5072 outs() << format(" %.*s", left, name);
5073 outs() << "\n";
5074
5075 offset += sizeof(struct message_ref64);
5076 }
5077}
5078
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005079static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5080 uint32_t i, left, offset, xoffset, p;
5081 struct message_ref32 mr;
5082 const char *name, *r;
5083 SectionRef xS;
5084
5085 if (S == SectionRef())
5086 return;
5087
5088 StringRef SectName;
5089 S.getName(SectName);
5090 DataRefImpl Ref = S.getRawDataRefImpl();
5091 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5092 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5093 offset = 0;
5094 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5095 p = S.getAddress() + i;
5096 r = get_pointer_32(p, offset, left, S, info);
5097 if (r == nullptr)
5098 return;
5099 memset(&mr, '\0', sizeof(struct message_ref32));
5100 if (left < sizeof(struct message_ref32)) {
5101 memcpy(&mr, r, left);
5102 outs() << " (message_ref entends past the end of the section)\n";
5103 } else
5104 memcpy(&mr, r, sizeof(struct message_ref32));
5105 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5106 swapStruct(mr);
5107
5108 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5109 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5110 mr.imp);
5111 if (name != nullptr)
5112 outs() << " " << name;
5113 outs() << "\n";
5114
5115 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5116 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5117 if (name != nullptr)
5118 outs() << " " << name;
5119 outs() << "\n";
5120
5121 offset += sizeof(struct message_ref32);
5122 }
5123}
5124
Kevin Enderby0fc11822015-04-01 20:57:01 +00005125static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5126 uint32_t left, offset, swift_version;
5127 uint64_t p;
5128 struct objc_image_info64 o;
5129 const char *r;
5130
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005131 if (S == SectionRef())
5132 return;
5133
Kevin Enderby0fc11822015-04-01 20:57:01 +00005134 StringRef SectName;
5135 S.getName(SectName);
5136 DataRefImpl Ref = S.getRawDataRefImpl();
5137 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5138 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5139 p = S.getAddress();
5140 r = get_pointer_64(p, offset, left, S, info);
5141 if (r == nullptr)
5142 return;
5143 memset(&o, '\0', sizeof(struct objc_image_info64));
5144 if (left < sizeof(struct objc_image_info64)) {
5145 memcpy(&o, r, left);
5146 outs() << " (objc_image_info entends past the end of the section)\n";
5147 } else
5148 memcpy(&o, r, sizeof(struct objc_image_info64));
5149 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5150 swapStruct(o);
5151 outs() << " version " << o.version << "\n";
5152 outs() << " flags " << format("0x%" PRIx32, o.flags);
5153 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5154 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5155 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5156 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5157 swift_version = (o.flags >> 8) & 0xff;
5158 if (swift_version != 0) {
5159 if (swift_version == 1)
5160 outs() << " Swift 1.0";
5161 else if (swift_version == 2)
5162 outs() << " Swift 1.1";
5163 else
5164 outs() << " unknown future Swift version (" << swift_version << ")";
5165 }
5166 outs() << "\n";
5167}
5168
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005169static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5170 uint32_t left, offset, swift_version, p;
5171 struct objc_image_info32 o;
5172 const char *r;
5173
Kevin Enderby19be2512016-04-21 19:49:29 +00005174 if (S == SectionRef())
5175 return;
5176
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005177 StringRef SectName;
5178 S.getName(SectName);
5179 DataRefImpl Ref = S.getRawDataRefImpl();
5180 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5181 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5182 p = S.getAddress();
5183 r = get_pointer_32(p, offset, left, S, info);
5184 if (r == nullptr)
5185 return;
5186 memset(&o, '\0', sizeof(struct objc_image_info32));
5187 if (left < sizeof(struct objc_image_info32)) {
5188 memcpy(&o, r, left);
5189 outs() << " (objc_image_info entends past the end of the section)\n";
5190 } else
5191 memcpy(&o, r, sizeof(struct objc_image_info32));
5192 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5193 swapStruct(o);
5194 outs() << " version " << o.version << "\n";
5195 outs() << " flags " << format("0x%" PRIx32, o.flags);
5196 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5197 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5198 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5199 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5200 swift_version = (o.flags >> 8) & 0xff;
5201 if (swift_version != 0) {
5202 if (swift_version == 1)
5203 outs() << " Swift 1.0";
5204 else if (swift_version == 2)
5205 outs() << " Swift 1.1";
5206 else
5207 outs() << " unknown future Swift version (" << swift_version << ")";
5208 }
5209 outs() << "\n";
5210}
5211
Kevin Enderby846c0002015-04-16 17:19:59 +00005212static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5213 uint32_t left, offset, p;
5214 struct imageInfo_t o;
5215 const char *r;
5216
5217 StringRef SectName;
5218 S.getName(SectName);
5219 DataRefImpl Ref = S.getRawDataRefImpl();
5220 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5221 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5222 p = S.getAddress();
5223 r = get_pointer_32(p, offset, left, S, info);
5224 if (r == nullptr)
5225 return;
5226 memset(&o, '\0', sizeof(struct imageInfo_t));
5227 if (left < sizeof(struct imageInfo_t)) {
5228 memcpy(&o, r, left);
5229 outs() << " (imageInfo entends past the end of the section)\n";
5230 } else
5231 memcpy(&o, r, sizeof(struct imageInfo_t));
5232 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5233 swapStruct(o);
5234 outs() << " version " << o.version << "\n";
5235 outs() << " flags " << format("0x%" PRIx32, o.flags);
5236 if (o.flags & 0x1)
5237 outs() << " F&C";
5238 if (o.flags & 0x2)
5239 outs() << " GC";
5240 if (o.flags & 0x4)
5241 outs() << " GC-only";
5242 else
5243 outs() << " RR";
5244 outs() << "\n";
5245}
5246
Kevin Enderby0fc11822015-04-01 20:57:01 +00005247static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5248 SymbolAddressMap AddrMap;
5249 if (verbose)
5250 CreateSymbolAddressMap(O, &AddrMap);
5251
5252 std::vector<SectionRef> Sections;
5253 for (const SectionRef &Section : O->sections()) {
5254 StringRef SectName;
5255 Section.getName(SectName);
5256 Sections.push_back(Section);
5257 }
5258
5259 struct DisassembleInfo info;
5260 // Set up the block of info used by the Symbolizer call backs.
5261 info.verbose = verbose;
5262 info.O = O;
5263 info.AddrMap = &AddrMap;
5264 info.Sections = &Sections;
5265 info.class_name = nullptr;
5266 info.selector_name = nullptr;
5267 info.method = nullptr;
5268 info.demangled_name = nullptr;
5269 info.bindtable = nullptr;
5270 info.adrp_addr = 0;
5271 info.adrp_inst = 0;
5272
Kevin Enderbyaac75382015-10-08 16:56:35 +00005273 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005274 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5275 if (CL == SectionRef())
5276 CL = get_section(O, "__DATA", "__objc_classlist");
5277 info.S = CL;
5278 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005279
Davide Italiano62507042015-12-11 22:27:59 +00005280 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5281 if (CR == SectionRef())
5282 CR = get_section(O, "__DATA", "__objc_classrefs");
5283 info.S = CR;
5284 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005285
Davide Italiano62507042015-12-11 22:27:59 +00005286 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5287 if (SR == SectionRef())
5288 SR = get_section(O, "__DATA", "__objc_superrefs");
5289 info.S = SR;
5290 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005291
Davide Italiano62507042015-12-11 22:27:59 +00005292 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5293 if (CA == SectionRef())
5294 CA = get_section(O, "__DATA", "__objc_catlist");
5295 info.S = CA;
5296 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005297
Davide Italiano62507042015-12-11 22:27:59 +00005298 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5299 if (PL == SectionRef())
5300 PL = get_section(O, "__DATA", "__objc_protolist");
5301 info.S = PL;
5302 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005303
Davide Italiano62507042015-12-11 22:27:59 +00005304 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5305 if (MR == SectionRef())
5306 MR = get_section(O, "__DATA", "__objc_msgrefs");
5307 info.S = MR;
5308 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005309
Davide Italiano62507042015-12-11 22:27:59 +00005310 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5311 if (II == SectionRef())
5312 II = get_section(O, "__DATA", "__objc_imageinfo");
5313 info.S = II;
5314 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005315}
5316
5317static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005318 SymbolAddressMap AddrMap;
5319 if (verbose)
5320 CreateSymbolAddressMap(O, &AddrMap);
5321
5322 std::vector<SectionRef> Sections;
5323 for (const SectionRef &Section : O->sections()) {
5324 StringRef SectName;
5325 Section.getName(SectName);
5326 Sections.push_back(Section);
5327 }
5328
5329 struct DisassembleInfo info;
5330 // Set up the block of info used by the Symbolizer call backs.
5331 info.verbose = verbose;
5332 info.O = O;
5333 info.AddrMap = &AddrMap;
5334 info.Sections = &Sections;
5335 info.class_name = nullptr;
5336 info.selector_name = nullptr;
5337 info.method = nullptr;
5338 info.demangled_name = nullptr;
5339 info.bindtable = nullptr;
5340 info.adrp_addr = 0;
5341 info.adrp_inst = 0;
5342
5343 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5344 if (CL != SectionRef()) {
5345 info.S = CL;
5346 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5347 } else {
5348 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5349 info.S = CL;
5350 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5351 }
5352
5353 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5354 if (CR != SectionRef()) {
5355 info.S = CR;
5356 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5357 } else {
5358 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5359 info.S = CR;
5360 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5361 }
5362
5363 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5364 if (SR != SectionRef()) {
5365 info.S = SR;
5366 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5367 } else {
5368 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5369 info.S = SR;
5370 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5371 }
5372
5373 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5374 if (CA != SectionRef()) {
5375 info.S = CA;
5376 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5377 } else {
5378 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5379 info.S = CA;
5380 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5381 }
5382
5383 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5384 if (PL != SectionRef()) {
5385 info.S = PL;
5386 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5387 } else {
5388 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5389 info.S = PL;
5390 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5391 }
5392
5393 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5394 if (MR != SectionRef()) {
5395 info.S = MR;
5396 print_message_refs32(MR, &info);
5397 } else {
5398 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5399 info.S = MR;
5400 print_message_refs32(MR, &info);
5401 }
5402
5403 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5404 if (II != SectionRef()) {
5405 info.S = II;
5406 print_image_info32(II, &info);
5407 } else {
5408 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5409 info.S = II;
5410 print_image_info32(II, &info);
5411 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005412}
5413
5414static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005415 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5416 const char *r, *name, *defs;
5417 struct objc_module_t module;
5418 SectionRef S, xS;
5419 struct objc_symtab_t symtab;
5420 struct objc_class_t objc_class;
5421 struct objc_category_t objc_category;
5422
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005423 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005424 S = get_section(O, "__OBJC", "__module_info");
5425 if (S == SectionRef())
5426 return false;
5427
5428 SymbolAddressMap AddrMap;
5429 if (verbose)
5430 CreateSymbolAddressMap(O, &AddrMap);
5431
5432 std::vector<SectionRef> Sections;
5433 for (const SectionRef &Section : O->sections()) {
5434 StringRef SectName;
5435 Section.getName(SectName);
5436 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005437 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005438
5439 struct DisassembleInfo info;
5440 // Set up the block of info used by the Symbolizer call backs.
5441 info.verbose = verbose;
5442 info.O = O;
5443 info.AddrMap = &AddrMap;
5444 info.Sections = &Sections;
5445 info.class_name = nullptr;
5446 info.selector_name = nullptr;
5447 info.method = nullptr;
5448 info.demangled_name = nullptr;
5449 info.bindtable = nullptr;
5450 info.adrp_addr = 0;
5451 info.adrp_inst = 0;
5452
5453 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5454 p = S.getAddress() + i;
5455 r = get_pointer_32(p, offset, left, S, &info, true);
5456 if (r == nullptr)
5457 return true;
5458 memset(&module, '\0', sizeof(struct objc_module_t));
5459 if (left < sizeof(struct objc_module_t)) {
5460 memcpy(&module, r, left);
5461 outs() << " (module extends past end of __module_info section)\n";
5462 } else
5463 memcpy(&module, r, sizeof(struct objc_module_t));
5464 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5465 swapStruct(module);
5466
5467 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5468 outs() << " version " << module.version << "\n";
5469 outs() << " size " << module.size << "\n";
5470 outs() << " name ";
5471 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5472 if (name != nullptr)
5473 outs() << format("%.*s", left, name);
5474 else
5475 outs() << format("0x%08" PRIx32, module.name)
5476 << "(not in an __OBJC section)";
5477 outs() << "\n";
5478
5479 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5480 if (module.symtab == 0 || r == nullptr) {
5481 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5482 << " (not in an __OBJC section)\n";
5483 continue;
5484 }
5485 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5486 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5487 defs_left = 0;
5488 defs = nullptr;
5489 if (left < sizeof(struct objc_symtab_t)) {
5490 memcpy(&symtab, r, left);
5491 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5492 } else {
5493 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5494 if (left > sizeof(struct objc_symtab_t)) {
5495 defs_left = left - sizeof(struct objc_symtab_t);
5496 defs = r + sizeof(struct objc_symtab_t);
5497 }
5498 }
5499 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5500 swapStruct(symtab);
5501
5502 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5503 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5504 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5505 if (r == nullptr)
5506 outs() << " (not in an __OBJC section)";
5507 outs() << "\n";
5508 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5509 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5510 if (symtab.cls_def_cnt > 0)
5511 outs() << "\tClass Definitions\n";
5512 for (j = 0; j < symtab.cls_def_cnt; j++) {
5513 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5514 outs() << "\t(remaining class defs entries entends past the end of the "
5515 << "section)\n";
5516 break;
5517 }
5518 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5519 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5520 sys::swapByteOrder(def);
5521
5522 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5523 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5524 if (r != nullptr) {
5525 if (left > sizeof(struct objc_class_t)) {
5526 outs() << "\n";
5527 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5528 } else {
5529 outs() << " (entends past the end of the section)\n";
5530 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5531 memcpy(&objc_class, r, left);
5532 }
5533 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5534 swapStruct(objc_class);
5535 print_objc_class_t(&objc_class, &info);
5536 } else {
5537 outs() << "(not in an __OBJC section)\n";
5538 }
5539
5540 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5541 outs() << "\tMeta Class";
5542 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5543 if (r != nullptr) {
5544 if (left > sizeof(struct objc_class_t)) {
5545 outs() << "\n";
5546 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5547 } else {
5548 outs() << " (entends past the end of the section)\n";
5549 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5550 memcpy(&objc_class, r, left);
5551 }
5552 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5553 swapStruct(objc_class);
5554 print_objc_class_t(&objc_class, &info);
5555 } else {
5556 outs() << "(not in an __OBJC section)\n";
5557 }
5558 }
5559 }
5560 if (symtab.cat_def_cnt > 0)
5561 outs() << "\tCategory Definitions\n";
5562 for (j = 0; j < symtab.cat_def_cnt; j++) {
5563 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5564 outs() << "\t(remaining category defs entries entends past the end of "
5565 << "the section)\n";
5566 break;
5567 }
5568 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5569 sizeof(uint32_t));
5570 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5571 sys::swapByteOrder(def);
5572
5573 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5574 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5575 << format("0x%08" PRIx32, def);
5576 if (r != nullptr) {
5577 if (left > sizeof(struct objc_category_t)) {
5578 outs() << "\n";
5579 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5580 } else {
5581 outs() << " (entends past the end of the section)\n";
5582 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5583 memcpy(&objc_category, r, left);
5584 }
5585 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5586 swapStruct(objc_category);
5587 print_objc_objc_category_t(&objc_category, &info);
5588 } else {
5589 outs() << "(not in an __OBJC section)\n";
5590 }
5591 }
5592 }
5593 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5594 if (II != SectionRef())
5595 print_image_info(II, &info);
5596
5597 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005598}
5599
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005600static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5601 uint32_t size, uint32_t addr) {
5602 SymbolAddressMap AddrMap;
5603 CreateSymbolAddressMap(O, &AddrMap);
5604
5605 std::vector<SectionRef> Sections;
5606 for (const SectionRef &Section : O->sections()) {
5607 StringRef SectName;
5608 Section.getName(SectName);
5609 Sections.push_back(Section);
5610 }
5611
5612 struct DisassembleInfo info;
5613 // Set up the block of info used by the Symbolizer call backs.
5614 info.verbose = true;
5615 info.O = O;
5616 info.AddrMap = &AddrMap;
5617 info.Sections = &Sections;
5618 info.class_name = nullptr;
5619 info.selector_name = nullptr;
5620 info.method = nullptr;
5621 info.demangled_name = nullptr;
5622 info.bindtable = nullptr;
5623 info.adrp_addr = 0;
5624 info.adrp_inst = 0;
5625
5626 const char *p;
5627 struct objc_protocol_t protocol;
5628 uint32_t left, paddr;
5629 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5630 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5631 left = size - (p - sect);
5632 if (left < sizeof(struct objc_protocol_t)) {
5633 outs() << "Protocol extends past end of __protocol section\n";
5634 memcpy(&protocol, p, left);
5635 } else
5636 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5637 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5638 swapStruct(protocol);
5639 paddr = addr + (p - sect);
5640 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5641 if (print_protocol(paddr, 0, &info))
5642 outs() << "(not in an __OBJC section)\n";
5643 }
5644}
5645
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005646#ifdef HAVE_LIBXAR
5647inline void swapStruct(struct xar_header &xar) {
5648 sys::swapByteOrder(xar.magic);
5649 sys::swapByteOrder(xar.size);
5650 sys::swapByteOrder(xar.version);
5651 sys::swapByteOrder(xar.toc_length_compressed);
5652 sys::swapByteOrder(xar.toc_length_uncompressed);
5653 sys::swapByteOrder(xar.cksum_alg);
5654}
5655
5656static void PrintModeVerbose(uint32_t mode) {
5657 switch(mode & S_IFMT){
5658 case S_IFDIR:
5659 outs() << "d";
5660 break;
5661 case S_IFCHR:
5662 outs() << "c";
5663 break;
5664 case S_IFBLK:
5665 outs() << "b";
5666 break;
5667 case S_IFREG:
5668 outs() << "-";
5669 break;
5670 case S_IFLNK:
5671 outs() << "l";
5672 break;
5673 case S_IFSOCK:
5674 outs() << "s";
5675 break;
5676 default:
5677 outs() << "?";
5678 break;
5679 }
5680
5681 /* owner permissions */
5682 if(mode & S_IREAD)
5683 outs() << "r";
5684 else
5685 outs() << "-";
5686 if(mode & S_IWRITE)
5687 outs() << "w";
5688 else
5689 outs() << "-";
5690 if(mode & S_ISUID)
5691 outs() << "s";
5692 else if(mode & S_IEXEC)
5693 outs() << "x";
5694 else
5695 outs() << "-";
5696
5697 /* group permissions */
5698 if(mode & (S_IREAD >> 3))
5699 outs() << "r";
5700 else
5701 outs() << "-";
5702 if(mode & (S_IWRITE >> 3))
5703 outs() << "w";
5704 else
5705 outs() << "-";
5706 if(mode & S_ISGID)
5707 outs() << "s";
5708 else if(mode & (S_IEXEC >> 3))
5709 outs() << "x";
5710 else
5711 outs() << "-";
5712
5713 /* other permissions */
5714 if(mode & (S_IREAD >> 6))
5715 outs() << "r";
5716 else
5717 outs() << "-";
5718 if(mode & (S_IWRITE >> 6))
5719 outs() << "w";
5720 else
5721 outs() << "-";
5722 if(mode & S_ISVTX)
5723 outs() << "t";
5724 else if(mode & (S_IEXEC >> 6))
5725 outs() << "x";
5726 else
5727 outs() << "-";
5728}
5729
5730static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5731 xar_iter_t xi;
5732 xar_file_t xf;
5733 xar_iter_t xp;
5734 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5735 char *endp;
5736 uint32_t mode_value;
5737
5738 xi = xar_iter_new();
5739 if (!xi) {
5740 errs() << "Can't obtain an xar iterator for xar archive "
5741 << XarFilename << "\n";
5742 return;
5743 }
5744
5745 // Go through the xar's files.
5746 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5747 xp = xar_iter_new();
5748 if(!xp){
5749 errs() << "Can't obtain an xar iterator for xar archive "
5750 << XarFilename << "\n";
5751 return;
5752 }
5753 type = nullptr;
5754 mode = nullptr;
5755 user = nullptr;
5756 group = nullptr;
5757 size = nullptr;
5758 mtime = nullptr;
5759 name = nullptr;
5760 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5761 const char *val = nullptr;
5762 xar_prop_get(xf, key, &val);
5763#if 0 // Useful for debugging.
5764 outs() << "key: " << key << " value: " << val << "\n";
5765#endif
5766 if(strcmp(key, "type") == 0)
5767 type = val;
5768 if(strcmp(key, "mode") == 0)
5769 mode = val;
5770 if(strcmp(key, "user") == 0)
5771 user = val;
5772 if(strcmp(key, "group") == 0)
5773 group = val;
5774 if(strcmp(key, "data/size") == 0)
5775 size = val;
5776 if(strcmp(key, "mtime") == 0)
5777 mtime = val;
5778 if(strcmp(key, "name") == 0)
5779 name = val;
5780 }
5781 if(mode != nullptr){
5782 mode_value = strtoul(mode, &endp, 8);
5783 if(*endp != '\0')
5784 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5785 if(strcmp(type, "file") == 0)
5786 mode_value |= S_IFREG;
5787 PrintModeVerbose(mode_value);
5788 outs() << " ";
5789 }
5790 if(user != nullptr)
5791 outs() << format("%10s/", user);
5792 if(group != nullptr)
5793 outs() << format("%-10s ", group);
5794 if(size != nullptr)
5795 outs() << format("%7s ", size);
5796 if(mtime != nullptr){
5797 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5798 outs() << *m;
5799 if(*m == 'T')
5800 m++;
5801 outs() << " ";
5802 for( ; *m != 'Z' && *m != '\0'; m++)
5803 outs() << *m;
5804 outs() << " ";
5805 }
5806 if(name != nullptr)
5807 outs() << name;
5808 outs() << "\n";
5809 }
5810}
5811
5812static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5813 uint32_t size, bool verbose,
5814 bool PrintXarHeader, bool PrintXarFileHeaders,
5815 std::string XarMemberName) {
5816 if(size < sizeof(struct xar_header)) {
5817 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5818 "of struct xar_header)\n";
5819 return;
5820 }
5821 struct xar_header XarHeader;
5822 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5823 if (sys::IsLittleEndianHost)
5824 swapStruct(XarHeader);
5825 if (PrintXarHeader) {
5826 if (!XarMemberName.empty())
5827 outs() << "In xar member " << XarMemberName << ": ";
5828 else
5829 outs() << "For (__LLVM,__bundle) section: ";
5830 outs() << "xar header\n";
5831 if (XarHeader.magic == XAR_HEADER_MAGIC)
5832 outs() << " magic XAR_HEADER_MAGIC\n";
5833 else
5834 outs() << " magic "
5835 << format_hex(XarHeader.magic, 10, true)
5836 << " (not XAR_HEADER_MAGIC)\n";
5837 outs() << " size " << XarHeader.size << "\n";
5838 outs() << " version " << XarHeader.version << "\n";
5839 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5840 << "\n";
5841 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5842 << "\n";
5843 outs() << " cksum_alg ";
5844 switch (XarHeader.cksum_alg) {
5845 case XAR_CKSUM_NONE:
5846 outs() << "XAR_CKSUM_NONE\n";
5847 break;
5848 case XAR_CKSUM_SHA1:
5849 outs() << "XAR_CKSUM_SHA1\n";
5850 break;
5851 case XAR_CKSUM_MD5:
5852 outs() << "XAR_CKSUM_MD5\n";
5853 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005854#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005855 case XAR_CKSUM_SHA256:
5856 outs() << "XAR_CKSUM_SHA256\n";
5857 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005858#endif
5859#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005860 case XAR_CKSUM_SHA512:
5861 outs() << "XAR_CKSUM_SHA512\n";
5862 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005863#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005864 default:
5865 outs() << XarHeader.cksum_alg << "\n";
5866 }
5867 }
5868
5869 SmallString<128> XarFilename;
5870 int FD;
5871 std::error_code XarEC =
5872 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5873 if (XarEC) {
5874 errs() << XarEC.message() << "\n";
5875 return;
5876 }
5877 tool_output_file XarFile(XarFilename, FD);
5878 raw_fd_ostream &XarOut = XarFile.os();
5879 StringRef XarContents(sect, size);
5880 XarOut << XarContents;
5881 XarOut.close();
5882 if (XarOut.has_error())
5883 return;
5884
5885 xar_t xar = xar_open(XarFilename.c_str(), READ);
5886 if (!xar) {
5887 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5888 return;
5889 }
5890
5891 SmallString<128> TocFilename;
5892 std::error_code TocEC =
5893 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5894 if (TocEC) {
5895 errs() << TocEC.message() << "\n";
5896 return;
5897 }
5898 xar_serialize(xar, TocFilename.c_str());
5899
5900 if (PrintXarFileHeaders) {
5901 if (!XarMemberName.empty())
5902 outs() << "In xar member " << XarMemberName << ": ";
5903 else
5904 outs() << "For (__LLVM,__bundle) section: ";
5905 outs() << "xar archive files:\n";
5906 PrintXarFilesSummary(XarFilename.c_str(), xar);
5907 }
5908
5909 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5910 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5911 if (std::error_code EC = FileOrErr.getError()) {
5912 errs() << EC.message() << "\n";
5913 return;
5914 }
5915 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5916
5917 if (!XarMemberName.empty())
5918 outs() << "In xar member " << XarMemberName << ": ";
5919 else
5920 outs() << "For (__LLVM,__bundle) section: ";
5921 outs() << "xar table of contents:\n";
5922 outs() << Buffer->getBuffer() << "\n";
5923
5924 // TODO: Go through the xar's files.
5925 xar_iter_t xi = xar_iter_new();
5926 if(!xi){
5927 errs() << "Can't obtain an xar iterator for xar archive "
5928 << XarFilename.c_str() << "\n";
5929 xar_close(xar);
5930 return;
5931 }
5932 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5933 const char *key;
5934 xar_iter_t xp;
5935 const char *member_name, *member_type, *member_size_string;
5936 size_t member_size;
5937
5938 xp = xar_iter_new();
5939 if(!xp){
5940 errs() << "Can't obtain an xar iterator for xar archive "
5941 << XarFilename.c_str() << "\n";
5942 xar_close(xar);
5943 return;
5944 }
5945 member_name = NULL;
5946 member_type = NULL;
5947 member_size_string = NULL;
5948 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5949 const char *val = nullptr;
5950 xar_prop_get(xf, key, &val);
5951#if 0 // Useful for debugging.
5952 outs() << "key: " << key << " value: " << val << "\n";
5953#endif
5954 if(strcmp(key, "name") == 0)
5955 member_name = val;
5956 if(strcmp(key, "type") == 0)
5957 member_type = val;
5958 if(strcmp(key, "data/size") == 0)
5959 member_size_string = val;
5960 }
5961 /*
5962 * If we find a file with a name, date/size and type properties
5963 * and with the type being "file" see if that is a xar file.
5964 */
5965 if (member_name != NULL && member_type != NULL &&
5966 strcmp(member_type, "file") == 0 &&
5967 member_size_string != NULL){
5968 // Extract the file into a buffer.
5969 char *endptr;
5970 member_size = strtoul(member_size_string, &endptr, 10);
5971 if (*endptr == '\0' && member_size != 0) {
5972 char *buffer = (char *) ::operator new (member_size);
5973 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
5974#if 0 // Useful for debugging.
5975 outs() << "xar member: " << member_name << " extracted\n";
5976#endif
5977 // Set the XarMemberName we want to see printed in the header.
5978 std::string OldXarMemberName;
5979 // If XarMemberName is already set this is nested. So
5980 // save the old name and create the nested name.
5981 if (!XarMemberName.empty()) {
5982 OldXarMemberName = XarMemberName;
5983 XarMemberName =
5984 (Twine("[") + XarMemberName + "]" + member_name).str();
5985 } else {
5986 OldXarMemberName = "";
5987 XarMemberName = member_name;
5988 }
5989 // See if this is could be a xar file (nested).
5990 if (member_size >= sizeof(struct xar_header)) {
5991#if 0 // Useful for debugging.
5992 outs() << "could be a xar file: " << member_name << "\n";
5993#endif
5994 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
5995 if (sys::IsLittleEndianHost)
5996 swapStruct(XarHeader);
5997 if(XarHeader.magic == XAR_HEADER_MAGIC)
5998 DumpBitcodeSection(O, buffer, member_size, verbose,
5999 PrintXarHeader, PrintXarFileHeaders,
6000 XarMemberName);
6001 }
6002 XarMemberName = OldXarMemberName;
6003 }
6004 delete buffer;
6005 }
6006 }
6007 xar_iter_free(xp);
6008 }
6009 xar_close(xar);
6010}
6011#endif // defined(HAVE_LIBXAR)
6012
Kevin Enderby0fc11822015-04-01 20:57:01 +00006013static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6014 if (O->is64Bit())
6015 printObjc2_64bit_MetaData(O, verbose);
6016 else {
6017 MachO::mach_header H;
6018 H = O->getHeader();
6019 if (H.cputype == MachO::CPU_TYPE_ARM)
6020 printObjc2_32bit_MetaData(O, verbose);
6021 else {
6022 // This is the 32-bit non-arm cputype case. Which is normally
6023 // the first Objective-C ABI. But it may be the case of a
6024 // binary for the iOS simulator which is the second Objective-C
6025 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6026 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006027 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006028 printObjc2_32bit_MetaData(O, verbose);
6029 }
6030 }
6031}
6032
Kevin Enderbybf246f52014-09-24 23:08:22 +00006033// GuessLiteralPointer returns a string which for the item in the Mach-O file
6034// for the address passed in as ReferenceValue for printing as a comment with
6035// the instruction and also returns the corresponding type of that item
6036// indirectly through ReferenceType.
6037//
6038// If ReferenceValue is an address of literal cstring then a pointer to the
6039// cstring is returned and ReferenceType is set to
6040// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6041//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006042// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6043// Class ref that name is returned and the ReferenceType is set accordingly.
6044//
6045// Lastly, literals which are Symbol address in a literal pool are looked for
6046// and if found the symbol name is returned and ReferenceType is set to
6047// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6048//
6049// If there is no item in the Mach-O file for the address passed in as
6050// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006051static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6052 uint64_t ReferencePC,
6053 uint64_t *ReferenceType,
6054 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006055 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006056 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6057 uint64_t sect_addr = info->S.getAddress();
6058 uint64_t sect_offset = ReferencePC - sect_addr;
6059 bool reloc_found = false;
6060 DataRefImpl Rel;
6061 MachO::any_relocation_info RE;
6062 bool isExtern = false;
6063 SymbolRef Symbol;
6064 for (const RelocationRef &Reloc : info->S.relocations()) {
6065 uint64_t RelocOffset = Reloc.getOffset();
6066 if (RelocOffset == sect_offset) {
6067 Rel = Reloc.getRawDataRefImpl();
6068 RE = info->O->getRelocation(Rel);
6069 if (info->O->isRelocationScattered(RE))
6070 continue;
6071 isExtern = info->O->getPlainRelocationExternal(RE);
6072 if (isExtern) {
6073 symbol_iterator RelocSym = Reloc.getSymbol();
6074 Symbol = *RelocSym;
6075 }
6076 reloc_found = true;
6077 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006078 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006079 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006080 // If there is an external relocation entry for a symbol in a section
6081 // then used that symbol's value for the value of the reference.
6082 if (reloc_found && isExtern) {
6083 if (info->O->getAnyRelocationPCRel(RE)) {
6084 unsigned Type = info->O->getAnyRelocationType(RE);
6085 if (Type == MachO::X86_64_RELOC_SIGNED) {
6086 ReferenceValue = Symbol.getValue();
6087 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006088 }
6089 }
6090 }
6091
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006092 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6093 // Message refs and Class refs.
6094 bool classref, selref, msgref, cfstring;
6095 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6096 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006097 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006098 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6099 // And the pointer_value in that section is typically zero as it will be
6100 // set by dyld as part of the "bind information".
6101 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6102 if (name != nullptr) {
6103 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006104 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006105 if (class_name != nullptr && class_name[1] == '_' &&
6106 class_name[2] != '\0') {
6107 info->class_name = class_name + 2;
6108 return name;
6109 }
6110 }
6111 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006112
David Blaikie33dd45d02015-03-23 18:39:02 +00006113 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006114 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6115 const char *name =
6116 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6117 if (name != nullptr)
6118 info->class_name = name;
6119 else
6120 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006121 return name;
6122 }
6123
David Blaikie33dd45d02015-03-23 18:39:02 +00006124 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006125 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6126 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6127 return name;
6128 }
6129
David Blaikie33dd45d02015-03-23 18:39:02 +00006130 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006131 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6132
6133 if (pointer_value != 0)
6134 ReferenceValue = pointer_value;
6135
6136 const char *name = GuessCstringPointer(ReferenceValue, info);
6137 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006138 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006139 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6140 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006141 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006142 info->class_name = nullptr;
6143 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6144 info->selector_name = name;
6145 } else
6146 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6147 return name;
6148 }
6149
6150 // Lastly look for an indirect symbol with this ReferenceValue which is in
6151 // a literal pool. If found return that symbol name.
6152 name = GuessIndirectSymbol(ReferenceValue, info);
6153 if (name) {
6154 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6155 return name;
6156 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006157
6158 return nullptr;
6159}
6160
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006161// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006162// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006163// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6164// is created and returns the symbol name that matches the ReferenceValue or
6165// nullptr if none. The ReferenceType is passed in for the IN type of
6166// reference the instruction is making from the values in defined in the header
6167// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6168// Out type and the ReferenceName will also be set which is added as a comment
6169// to the disassembled instruction.
6170//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006171// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006172// returned through ReferenceName and ReferenceType is set to
6173// LLVMDisassembler_ReferenceType_DeMangled_Name .
6174//
6175// When this is called to get a symbol name for a branch target then the
6176// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6177// SymbolValue will be looked for in the indirect symbol table to determine if
6178// it is an address for a symbol stub. If so then the symbol name for that
6179// stub is returned indirectly through ReferenceName and then ReferenceType is
6180// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6181//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006182// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006183// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6184// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6185// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006186// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006187static const char *SymbolizerSymbolLookUp(void *DisInfo,
6188 uint64_t ReferenceValue,
6189 uint64_t *ReferenceType,
6190 uint64_t ReferencePC,
6191 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006192 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006193 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006194 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006195 *ReferenceName = nullptr;
6196 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006197 return nullptr;
6198 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006199
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006200 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006201
Kevin Enderby85974882014-09-26 22:20:44 +00006202 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6203 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006204 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006205 method_reference(info, ReferenceType, ReferenceName);
6206 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6207 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006208 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006209 if (info->demangled_name != nullptr)
6210 free(info->demangled_name);
6211 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006212 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006213 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006214 if (info->demangled_name != nullptr) {
6215 *ReferenceName = info->demangled_name;
6216 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6217 } else
6218 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6219 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006220 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6221 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6222 *ReferenceName =
6223 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006224 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006225 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006226 else
6227 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006228 // If this is arm64 and the reference is an adrp instruction save the
6229 // instruction, passed in ReferenceValue and the address of the instruction
6230 // for use later if we see and add immediate instruction.
6231 } else if (info->O->getArch() == Triple::aarch64 &&
6232 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6233 info->adrp_inst = ReferenceValue;
6234 info->adrp_addr = ReferencePC;
6235 SymbolName = nullptr;
6236 *ReferenceName = nullptr;
6237 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6238 // If this is arm64 and reference is an add immediate instruction and we
6239 // have
6240 // seen an adrp instruction just before it and the adrp's Xd register
6241 // matches
6242 // this add's Xn register reconstruct the value being referenced and look to
6243 // see if it is a literal pointer. Note the add immediate instruction is
6244 // passed in ReferenceValue.
6245 } else if (info->O->getArch() == Triple::aarch64 &&
6246 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6247 ReferencePC - 4 == info->adrp_addr &&
6248 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6249 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6250 uint32_t addxri_inst;
6251 uint64_t adrp_imm, addxri_imm;
6252
6253 adrp_imm =
6254 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6255 if (info->adrp_inst & 0x0200000)
6256 adrp_imm |= 0xfffffffffc000000LL;
6257
6258 addxri_inst = ReferenceValue;
6259 addxri_imm = (addxri_inst >> 10) & 0xfff;
6260 if (((addxri_inst >> 22) & 0x3) == 1)
6261 addxri_imm <<= 12;
6262
6263 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6264 (adrp_imm << 12) + addxri_imm;
6265
6266 *ReferenceName =
6267 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6268 if (*ReferenceName == nullptr)
6269 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6270 // If this is arm64 and the reference is a load register instruction and we
6271 // have seen an adrp instruction just before it and the adrp's Xd register
6272 // matches this add's Xn register reconstruct the value being referenced and
6273 // look to see if it is a literal pointer. Note the load register
6274 // instruction is passed in ReferenceValue.
6275 } else if (info->O->getArch() == Triple::aarch64 &&
6276 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6277 ReferencePC - 4 == info->adrp_addr &&
6278 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6279 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6280 uint32_t ldrxui_inst;
6281 uint64_t adrp_imm, ldrxui_imm;
6282
6283 adrp_imm =
6284 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6285 if (info->adrp_inst & 0x0200000)
6286 adrp_imm |= 0xfffffffffc000000LL;
6287
6288 ldrxui_inst = ReferenceValue;
6289 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6290
6291 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6292 (adrp_imm << 12) + (ldrxui_imm << 3);
6293
6294 *ReferenceName =
6295 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6296 if (*ReferenceName == nullptr)
6297 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6298 }
6299 // If this arm64 and is an load register (PC-relative) instruction the
6300 // ReferenceValue is the PC plus the immediate value.
6301 else if (info->O->getArch() == Triple::aarch64 &&
6302 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6303 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6304 *ReferenceName =
6305 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6306 if (*ReferenceName == nullptr)
6307 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006308 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006309 if (info->demangled_name != nullptr)
6310 free(info->demangled_name);
6311 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006312 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006313 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006314 if (info->demangled_name != nullptr) {
6315 *ReferenceName = info->demangled_name;
6316 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6317 }
6318 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006319 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006320 *ReferenceName = nullptr;
6321 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6322 }
6323
6324 return SymbolName;
6325}
6326
Kevin Enderbybf246f52014-09-24 23:08:22 +00006327/// \brief Emits the comments that are stored in the CommentStream.
6328/// Each comment in the CommentStream must end with a newline.
6329static void emitComments(raw_svector_ostream &CommentStream,
6330 SmallString<128> &CommentsToEmit,
6331 formatted_raw_ostream &FormattedOS,
6332 const MCAsmInfo &MAI) {
6333 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006334 StringRef Comments = CommentsToEmit.str();
6335 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006336 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006337 unsigned CommentColumn = MAI.getCommentColumn();
6338 bool IsFirst = true;
6339 while (!Comments.empty()) {
6340 if (!IsFirst)
6341 FormattedOS << '\n';
6342 // Emit a line of comments.
6343 FormattedOS.PadToColumn(CommentColumn);
6344 size_t Position = Comments.find('\n');
6345 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6346 // Move after the newline character.
6347 Comments = Comments.substr(Position + 1);
6348 IsFirst = false;
6349 }
6350 FormattedOS.flush();
6351
6352 // Tell the comment stream that the vector changed underneath it.
6353 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006354}
6355
Kevin Enderby95df54c2015-02-04 01:01:38 +00006356static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6357 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006358 const char *McpuDefault = nullptr;
6359 const Target *ThumbTarget = nullptr;
6360 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006361 if (!TheTarget) {
6362 // GetTarget prints out stuff.
6363 return;
6364 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006365 if (MCPU.empty() && McpuDefault)
6366 MCPU = McpuDefault;
6367
Ahmed Charles56440fd2014-03-06 05:51:42 +00006368 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006369 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006370 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006371 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006372
Kevin Enderbyc9595622014-08-06 23:24:41 +00006373 // Package up features to be passed to target/subtarget
6374 std::string FeaturesStr;
6375 if (MAttrs.size()) {
6376 SubtargetFeatures Features;
6377 for (unsigned i = 0; i != MAttrs.size(); ++i)
6378 Features.AddFeature(MAttrs[i]);
6379 FeaturesStr = Features.getString();
6380 }
6381
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006382 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006383 std::unique_ptr<const MCRegisterInfo> MRI(
6384 TheTarget->createMCRegInfo(TripleName));
6385 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006386 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006387 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006388 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006389 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006390 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006391 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006392 std::unique_ptr<MCSymbolizer> Symbolizer;
6393 struct DisassembleInfo SymbolizerInfo;
6394 std::unique_ptr<MCRelocationInfo> RelInfo(
6395 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6396 if (RelInfo) {
6397 Symbolizer.reset(TheTarget->createMCSymbolizer(
6398 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006399 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006400 DisAsm->setSymbolizer(std::move(Symbolizer));
6401 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006402 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006403 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006404 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006405 // Set the display preference for hex vs. decimal immediates.
6406 IP->setPrintImmHex(PrintImmHex);
6407 // Comment stream and backing vector.
6408 SmallString<128> CommentsToEmit;
6409 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006410 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6411 // if it is done then arm64 comments for string literals don't get printed
6412 // and some constant get printed instead and not setting it causes intel
6413 // (32-bit and 64-bit) comments printed with different spacing before the
6414 // comment causing different diffs with the 'C' disassembler library API.
6415 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006416
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006417 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006418 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006419 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006420 return;
6421 }
6422
Tim Northover09ca33e2016-04-22 23:23:31 +00006423 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006424 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6425 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6426 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006427 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006428 std::unique_ptr<MCInstPrinter> ThumbIP;
6429 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006430 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6431 struct DisassembleInfo ThumbSymbolizerInfo;
6432 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006433 if (ThumbTarget) {
6434 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6435 ThumbAsmInfo.reset(
6436 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6437 ThumbSTI.reset(
6438 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6439 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6440 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006441 MCContext *PtrThumbCtx = ThumbCtx.get();
6442 ThumbRelInfo.reset(
6443 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6444 if (ThumbRelInfo) {
6445 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6446 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006447 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006448 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6449 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006450 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6451 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006452 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6453 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006454 // Set the display preference for hex vs. decimal immediates.
6455 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006456 }
6457
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006458 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006459 errs() << "error: couldn't initialize disassembler for target "
6460 << ThumbTripleName << '\n';
6461 return;
6462 }
6463
Charles Davis8bdfafd2013-09-01 04:28:48 +00006464 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006465
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006466 // FIXME: Using the -cfg command line option, this code used to be able to
6467 // annotate relocations with the referenced symbol's name, and if this was
6468 // inside a __[cf]string section, the data it points to. This is now replaced
6469 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006470 std::vector<SectionRef> Sections;
6471 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006472 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006473 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006474
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006475 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006476 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006477
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006478 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006479 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006480
Kevin Enderby273ae012013-06-06 17:20:50 +00006481 // Build a data in code table that is sorted on by the address of each entry.
6482 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006483 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006484 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006485 else
6486 BaseAddress = BaseSegmentAddress;
6487 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006488 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006489 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006490 uint32_t Offset;
6491 DI->getOffset(Offset);
6492 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6493 }
6494 array_pod_sort(Dices.begin(), Dices.end());
6495
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006496#ifndef NDEBUG
6497 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6498#else
6499 raw_ostream &DebugOut = nulls();
6500#endif
6501
Ahmed Charles56440fd2014-03-06 05:51:42 +00006502 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006503 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006504 // Try to find debug info and set up the DIContext for it.
6505 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006506 // A separate DSym file path was specified, parse it as a macho file,
6507 // get the sections and supply it to the section name parsing machinery.
6508 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006509 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006510 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006511 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006512 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006513 return;
6514 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006515 DbgObj =
6516 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6517 .get()
6518 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006519 }
6520
Eric Christopher7370b552012-11-12 21:40:38 +00006521 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006522 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006523 }
6524
Colin LeMahieufcc32762015-07-29 19:08:10 +00006525 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006526 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006527
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006528 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006529 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006530 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6531 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006532
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006533 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006534
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006535 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006536 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006537 continue;
6538
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006539 StringRef BytesStr;
6540 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006541 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6542 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006543 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006544
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006545 bool symbolTableWorked = false;
6546
Kevin Enderbybf246f52014-09-24 23:08:22 +00006547 // Create a map of symbol addresses to symbol names for use by
6548 // the SymbolizerSymbolLookUp() routine.
6549 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006550 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006551 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006552 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006553 if (!STOrErr)
6554 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006555 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006556 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6557 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006558 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006559 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006560 if (!SymNameOrErr)
6561 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006562 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006563 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006564 if (!DisSymName.empty() && DisSymName == SymName)
6565 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006566 }
6567 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006568 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006569 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6570 return;
6571 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006572 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006573 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006574 SymbolizerInfo.O = MachOOF;
6575 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006576 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006577 SymbolizerInfo.Sections = &Sections;
6578 SymbolizerInfo.class_name = nullptr;
6579 SymbolizerInfo.selector_name = nullptr;
6580 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006581 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006582 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006583 SymbolizerInfo.adrp_addr = 0;
6584 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006585 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006586 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006587 ThumbSymbolizerInfo.O = MachOOF;
6588 ThumbSymbolizerInfo.S = Sections[SectIdx];
6589 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6590 ThumbSymbolizerInfo.Sections = &Sections;
6591 ThumbSymbolizerInfo.class_name = nullptr;
6592 ThumbSymbolizerInfo.selector_name = nullptr;
6593 ThumbSymbolizerInfo.method = nullptr;
6594 ThumbSymbolizerInfo.demangled_name = nullptr;
6595 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006596 ThumbSymbolizerInfo.adrp_addr = 0;
6597 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006598
Kevin Enderby4b627be2016-04-28 20:14:13 +00006599 unsigned int Arch = MachOOF->getArch();
6600
Tim Northoverf203ab52016-07-14 22:13:32 +00006601 // Skip all symbols if this is a stubs file.
6602 if (Bytes.size() == 0)
6603 return;
6604
Kevin Enderbyc138da32017-02-06 18:43:18 +00006605 // If the section has symbols but no symbol at the start of the section
6606 // these are used to make sure the bytes before the first symbol are
6607 // disassembled.
6608 bool FirstSymbol = true;
6609 bool FirstSymbolAtSectionStart = true;
6610
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006611 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006612 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006613 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006614 if (!SymNameOrErr)
6615 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006616 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006617
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006618 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006619 if (!STOrErr)
6620 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006621 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006622 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006623 continue;
6624
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006625 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006626 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006627 if (!containsSym) {
6628 if (!DisSymName.empty() && DisSymName == SymName) {
6629 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6630 return;
6631 }
6632 continue;
6633 }
6634 // The __mh_execute_header is special and we need to deal with that fact
6635 // this symbol is before the start of the (__TEXT,__text) section and at the
6636 // address of the start of the __TEXT segment. This is because this symbol
6637 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6638 // start of the section in a standard MH_EXECUTE filetype.
6639 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6640 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6641 return;
6642 }
Tim Northoverfbefee32016-07-14 23:13:03 +00006643 // When this code is trying to disassemble a symbol at a time and in the
6644 // case there is only the __mh_execute_header symbol left as in a stripped
6645 // executable, we need to deal with this by ignoring this symbol so the
6646 // whole section is disassembled and this symbol is then not displayed.
6647 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6648 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6649 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006650 continue;
6651
Kevin Enderby6a221752015-03-17 17:10:57 +00006652 // If we are only disassembling one symbol see if this is that symbol.
6653 if (!DisSymName.empty() && DisSymName != SymName)
6654 continue;
6655
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006656 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00006657 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00006658 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006659 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006660 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006661
Tim Northoverf203ab52016-07-14 22:13:32 +00006662 if (Start > SectSize) {
6663 outs() << "section data ends, " << SymName
6664 << " lies outside valid range\n";
6665 return;
6666 }
6667
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006668 // Stop disassembling either at the beginning of the next symbol or at
6669 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006670 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006671 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006672 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006673 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006674 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006675 if (!STOrErr)
6676 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006677 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006678 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006679 containsNextSym =
6680 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006681 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006682 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006683 break;
6684 }
6685 ++NextSymIdx;
6686 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006687
Tim Northoverf203ab52016-07-14 22:13:32 +00006688 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006689 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006690
6691 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006692
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006693 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006694 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6695
6696 // We only need the dedicated Thumb target if there's a real choice
6697 // (i.e. we're not targeting M-class) and the function is Thumb.
6698 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006699
Kevin Enderbyc138da32017-02-06 18:43:18 +00006700 // If we are not specifying a symbol to start disassembly with and this
6701 // is the first symbol in the section but not at the start of the section
6702 // then move the disassembly index to the start of the section and
6703 // don't print the symbol name just yet. This is so the bytes before the
6704 // first symbol are disassembled.
6705 uint64_t SymbolStart = Start;
6706 if (DisSymName.empty() && FirstSymbol && Start != 0) {
6707 FirstSymbolAtSectionStart = false;
6708 Start = 0;
6709 }
6710 else
6711 outs() << SymName << ":\n";
6712
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006713 DILineInfo lastLine;
6714 for (uint64_t Index = Start; Index < End; Index += Size) {
6715 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006716
Kevin Enderbyc138da32017-02-06 18:43:18 +00006717 // If this is the first symbol in the section and it was not at the
6718 // start of the section, see if we are at its Index now and if so print
6719 // the symbol name.
6720 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
6721 outs() << SymName << ":\n";
6722
Kevin Enderbybf246f52014-09-24 23:08:22 +00006723 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006724 if (!NoLeadingAddr) {
6725 if (FullLeadingAddr) {
6726 if (MachOOF->is64Bit())
6727 outs() << format("%016" PRIx64, PC);
6728 else
6729 outs() << format("%08" PRIx64, PC);
6730 } else {
6731 outs() << format("%8" PRIx64 ":", PC);
6732 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006733 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006734 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006735 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006736
6737 // Check the data in code table here to see if this is data not an
6738 // instruction to be disassembled.
6739 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006740 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006741 dice_table_iterator DTI =
6742 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6743 compareDiceTableEntries);
6744 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006745 uint16_t Length;
6746 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006747 uint16_t Kind;
6748 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006749 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006750 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6751 (PC == (DTI->first + Length - 1)) && (Length & 1))
6752 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006753 continue;
6754 }
6755
Kevin Enderbybf246f52014-09-24 23:08:22 +00006756 SmallVector<char, 64> AnnotationsBytes;
6757 raw_svector_ostream Annotations(AnnotationsBytes);
6758
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006759 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006760 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006761 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006762 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006763 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006764 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006765 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006766 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006767 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006768 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006769 }
6770 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006771 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006772 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006773 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006774 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006775 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006776 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006777
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006778 // Print debug info.
6779 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006780 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006781 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006782 if (dli != lastLine && dli.Line != 0)
6783 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6784 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006785 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006786 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006787 outs() << "\n";
6788 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006789 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006790 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006791 outs() << format("\t.byte 0x%02x #bad opcode\n",
6792 *(Bytes.data() + Index) & 0xff);
6793 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006794 } else if (Arch == Triple::aarch64 ||
6795 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006796 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6797 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6798 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6799 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6800 outs() << format("\t.long\t0x%08x\n", opcode);
6801 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006802 } else if (Arch == Triple::arm) {
6803 assert(IsThumb && "ARM mode should have been dealt with above");
6804 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6805 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6806 outs() << format("\t.short\t0x%04x\n", opcode);
6807 Size = 2;
6808 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006809 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6810 if (Size == 0)
6811 Size = 1; // skip illegible bytes
6812 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006813 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006814 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00006815 // Now that we are done disassembled the first symbol set the bool that
6816 // were doing this to false.
6817 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006818 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006819 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006820 // Reading the symbol table didn't work, disassemble the whole section.
6821 uint64_t SectAddress = Sections[SectIdx].getAddress();
6822 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006823 uint64_t InstSize;
6824 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006825 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006826
Kevin Enderbybf246f52014-09-24 23:08:22 +00006827 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00006828 SmallVector<char, 64> AnnotationsBytes;
6829 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006830 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00006831 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006832 if (!NoLeadingAddr) {
6833 if (FullLeadingAddr) {
6834 if (MachOOF->is64Bit())
6835 outs() << format("%016" PRIx64, PC);
6836 else
6837 outs() << format("%08" PRIx64, PC);
6838 } else {
6839 outs() << format("%8" PRIx64 ":", PC);
6840 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006841 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006842 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006843 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006844 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006845 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00006846 StringRef AnnotationsStr = Annotations.str();
6847 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006848 outs() << "\n";
6849 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006850 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006851 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006852 outs() << format("\t.byte 0x%02x #bad opcode\n",
6853 *(Bytes.data() + Index) & 0xff);
6854 InstSize = 1; // skip exactly one illegible byte and move on.
6855 } else {
6856 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6857 if (InstSize == 0)
6858 InstSize = 1; // skip illegible bytes
6859 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006860 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006861 }
6862 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006863 // The TripleName's need to be reset if we are called again for a different
6864 // archtecture.
6865 TripleName = "";
6866 ThumbTripleName = "";
6867
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006868 if (SymbolizerInfo.method != nullptr)
6869 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006870 if (SymbolizerInfo.demangled_name != nullptr)
6871 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006872 if (ThumbSymbolizerInfo.method != nullptr)
6873 free(ThumbSymbolizerInfo.method);
6874 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6875 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006876 }
6877}
Tim Northover4bd286a2014-08-01 13:07:19 +00006878
Tim Northover39c70bb2014-08-12 11:52:59 +00006879//===----------------------------------------------------------------------===//
6880// __compact_unwind section dumping
6881//===----------------------------------------------------------------------===//
6882
Tim Northover4bd286a2014-08-01 13:07:19 +00006883namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006884
6885template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006886 using llvm::support::little;
6887 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006888
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006889 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6890 Buf += sizeof(T);
6891 return Val;
6892}
Tim Northover39c70bb2014-08-12 11:52:59 +00006893
Tim Northover4bd286a2014-08-01 13:07:19 +00006894struct CompactUnwindEntry {
6895 uint32_t OffsetInSection;
6896
6897 uint64_t FunctionAddr;
6898 uint32_t Length;
6899 uint32_t CompactEncoding;
6900 uint64_t PersonalityAddr;
6901 uint64_t LSDAAddr;
6902
6903 RelocationRef FunctionReloc;
6904 RelocationRef PersonalityReloc;
6905 RelocationRef LSDAReloc;
6906
6907 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006908 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006909 if (Is64)
6910 read<uint64_t>(Contents.data() + Offset);
6911 else
6912 read<uint32_t>(Contents.data() + Offset);
6913 }
6914
6915private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006916 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006917 FunctionAddr = readNext<UIntPtr>(Buf);
6918 Length = readNext<uint32_t>(Buf);
6919 CompactEncoding = readNext<uint32_t>(Buf);
6920 PersonalityAddr = readNext<UIntPtr>(Buf);
6921 LSDAAddr = readNext<UIntPtr>(Buf);
6922 }
6923};
6924}
6925
6926/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6927/// and data being relocated, determine the best base Name and Addend to use for
6928/// display purposes.
6929///
6930/// 1. An Extern relocation will directly reference a symbol (and the data is
6931/// then already an addend), so use that.
6932/// 2. Otherwise the data is an offset in the object file's layout; try to find
6933// a symbol before it in the same section, and use the offset from there.
6934/// 3. Finally, if all that fails, fall back to an offset from the start of the
6935/// referenced section.
6936static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6937 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006938 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006939 StringRef &Name, uint64_t &Addend) {
6940 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006941 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006942 if (!NameOrErr)
6943 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006944 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006945 Addend = Addr;
6946 return;
6947 }
6948
6949 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006950 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006951
Rafael Espindola80291272014-10-08 15:28:58 +00006952 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006953
6954 auto Sym = Symbols.upper_bound(Addr);
6955 if (Sym == Symbols.begin()) {
6956 // The first symbol in the object is after this reference, the best we can
6957 // do is section-relative notation.
6958 RelocSection.getName(Name);
6959 Addend = Addr - SectionAddr;
6960 return;
6961 }
6962
6963 // Go back one so that SymbolAddress <= Addr.
6964 --Sym;
6965
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006966 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006967 if (!SectOrErr)
6968 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006969 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006970 if (RelocSection == *SymSection) {
6971 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006972 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006973 if (!NameOrErr)
6974 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006975 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006976 Addend = Addr - Sym->first;
6977 return;
6978 }
6979
6980 // There is a symbol before this reference, but it's in a different
6981 // section. Probably not helpful to mention it, so use the section name.
6982 RelocSection.getName(Name);
6983 Addend = Addr - SectionAddr;
6984}
6985
6986static void printUnwindRelocDest(const MachOObjectFile *Obj,
6987 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006988 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006989 StringRef Name;
6990 uint64_t Addend;
6991
Rafael Espindola854038e2015-06-26 14:51:16 +00006992 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006993 return;
6994
Tim Northover4bd286a2014-08-01 13:07:19 +00006995 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6996
6997 outs() << Name;
6998 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006999 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007000}
7001
7002static void
7003printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7004 std::map<uint64_t, SymbolRef> &Symbols,
7005 const SectionRef &CompactUnwind) {
7006
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007007 if (!Obj->isLittleEndian()) {
7008 outs() << "Skipping big-endian __compact_unwind section\n";
7009 return;
7010 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007011
7012 bool Is64 = Obj->is64Bit();
7013 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7014 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7015
7016 StringRef Contents;
7017 CompactUnwind.getContents(Contents);
7018
7019 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7020
7021 // First populate the initial raw offsets, encodings and so on from the entry.
7022 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7023 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7024 CompactUnwinds.push_back(Entry);
7025 }
7026
7027 // Next we need to look at the relocations to find out what objects are
7028 // actually being referred to.
7029 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007030 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007031
7032 uint32_t EntryIdx = RelocAddress / EntrySize;
7033 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7034 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7035
7036 if (OffsetInEntry == 0)
7037 Entry.FunctionReloc = Reloc;
7038 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7039 Entry.PersonalityReloc = Reloc;
7040 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7041 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007042 else {
7043 outs() << "Invalid relocation in __compact_unwind section\n";
7044 return;
7045 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007046 }
7047
7048 // Finally, we're ready to print the data we've gathered.
7049 outs() << "Contents of __compact_unwind section:\n";
7050 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007051 outs() << " Entry at offset "
7052 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007053
7054 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007055 outs() << " start: " << format("0x%" PRIx64,
7056 Entry.FunctionAddr) << ' ';
7057 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007058 outs() << '\n';
7059
7060 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007061 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7062 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007063 // 3. The 32-bit compact encoding.
7064 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007065 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007066
7067 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007068 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007069 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007070 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007071 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7072 Entry.PersonalityAddr);
7073 outs() << '\n';
7074 }
7075
7076 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007077 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007078 outs() << " LSDA: " << format("0x%" PRIx64,
7079 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007080 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7081 outs() << '\n';
7082 }
7083 }
7084}
7085
Tim Northover39c70bb2014-08-12 11:52:59 +00007086//===----------------------------------------------------------------------===//
7087// __unwind_info section dumping
7088//===----------------------------------------------------------------------===//
7089
7090static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7091 const char *Pos = PageStart;
7092 uint32_t Kind = readNext<uint32_t>(Pos);
7093 (void)Kind;
7094 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7095
7096 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7097 uint16_t NumEntries = readNext<uint16_t>(Pos);
7098
7099 Pos = PageStart + EntriesStart;
7100 for (unsigned i = 0; i < NumEntries; ++i) {
7101 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7102 uint32_t Encoding = readNext<uint32_t>(Pos);
7103
7104 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007105 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7106 << ", "
7107 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007108 }
7109}
7110
7111static void printCompressedSecondLevelUnwindPage(
7112 const char *PageStart, uint32_t FunctionBase,
7113 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7114 const char *Pos = PageStart;
7115 uint32_t Kind = readNext<uint32_t>(Pos);
7116 (void)Kind;
7117 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7118
7119 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7120 uint16_t NumEntries = readNext<uint16_t>(Pos);
7121
7122 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7123 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007124 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7125 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007126
7127 Pos = PageStart + EntriesStart;
7128 for (unsigned i = 0; i < NumEntries; ++i) {
7129 uint32_t Entry = readNext<uint32_t>(Pos);
7130 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7131 uint32_t EncodingIdx = Entry >> 24;
7132
7133 uint32_t Encoding;
7134 if (EncodingIdx < CommonEncodings.size())
7135 Encoding = CommonEncodings[EncodingIdx];
7136 else
7137 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7138
7139 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007140 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7141 << ", "
7142 << "encoding[" << EncodingIdx
7143 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007144 }
7145}
7146
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007147static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7148 std::map<uint64_t, SymbolRef> &Symbols,
7149 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007150
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007151 if (!Obj->isLittleEndian()) {
7152 outs() << "Skipping big-endian __unwind_info section\n";
7153 return;
7154 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007155
7156 outs() << "Contents of __unwind_info section:\n";
7157
7158 StringRef Contents;
7159 UnwindInfo.getContents(Contents);
7160 const char *Pos = Contents.data();
7161
7162 //===----------------------------------
7163 // Section header
7164 //===----------------------------------
7165
7166 uint32_t Version = readNext<uint32_t>(Pos);
7167 outs() << " Version: "
7168 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007169 if (Version != 1) {
7170 outs() << " Skipping section with unknown version\n";
7171 return;
7172 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007173
7174 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7175 outs() << " Common encodings array section offset: "
7176 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7177 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7178 outs() << " Number of common encodings in array: "
7179 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7180
7181 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7182 outs() << " Personality function array section offset: "
7183 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7184 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7185 outs() << " Number of personality functions in array: "
7186 << format("0x%" PRIx32, NumPersonalities) << '\n';
7187
7188 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7189 outs() << " Index array section offset: "
7190 << format("0x%" PRIx32, IndicesStart) << '\n';
7191 uint32_t NumIndices = readNext<uint32_t>(Pos);
7192 outs() << " Number of indices in array: "
7193 << format("0x%" PRIx32, NumIndices) << '\n';
7194
7195 //===----------------------------------
7196 // A shared list of common encodings
7197 //===----------------------------------
7198
7199 // These occupy indices in the range [0, N] whenever an encoding is referenced
7200 // from a compressed 2nd level index table. In practice the linker only
7201 // creates ~128 of these, so that indices are available to embed encodings in
7202 // the 2nd level index.
7203
7204 SmallVector<uint32_t, 64> CommonEncodings;
7205 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7206 Pos = Contents.data() + CommonEncodingsStart;
7207 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7208 uint32_t Encoding = readNext<uint32_t>(Pos);
7209 CommonEncodings.push_back(Encoding);
7210
7211 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7212 << '\n';
7213 }
7214
Tim Northover39c70bb2014-08-12 11:52:59 +00007215 //===----------------------------------
7216 // Personality functions used in this executable
7217 //===----------------------------------
7218
7219 // There should be only a handful of these (one per source language,
7220 // roughly). Particularly since they only get 2 bits in the compact encoding.
7221
7222 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7223 Pos = Contents.data() + PersonalitiesStart;
7224 for (unsigned i = 0; i < NumPersonalities; ++i) {
7225 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7226 outs() << " personality[" << i + 1
7227 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7228 }
7229
7230 //===----------------------------------
7231 // The level 1 index entries
7232 //===----------------------------------
7233
7234 // These specify an approximate place to start searching for the more detailed
7235 // information, sorted by PC.
7236
7237 struct IndexEntry {
7238 uint32_t FunctionOffset;
7239 uint32_t SecondLevelPageStart;
7240 uint32_t LSDAStart;
7241 };
7242
7243 SmallVector<IndexEntry, 4> IndexEntries;
7244
7245 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7246 Pos = Contents.data() + IndicesStart;
7247 for (unsigned i = 0; i < NumIndices; ++i) {
7248 IndexEntry Entry;
7249
7250 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7251 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7252 Entry.LSDAStart = readNext<uint32_t>(Pos);
7253 IndexEntries.push_back(Entry);
7254
7255 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007256 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7257 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007258 << "2nd level page offset="
7259 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007260 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007261 }
7262
Tim Northover39c70bb2014-08-12 11:52:59 +00007263 //===----------------------------------
7264 // Next come the LSDA tables
7265 //===----------------------------------
7266
7267 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7268 // the first top-level index's LSDAOffset to the last (sentinel).
7269
7270 outs() << " LSDA descriptors:\n";
7271 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7272 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7273 (2 * sizeof(uint32_t));
7274 for (int i = 0; i < NumLSDAs; ++i) {
7275 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7276 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7277 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007278 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7279 << ", "
7280 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007281 }
7282
7283 //===----------------------------------
7284 // Finally, the 2nd level indices
7285 //===----------------------------------
7286
7287 // Generally these are 4K in size, and have 2 possible forms:
7288 // + Regular stores up to 511 entries with disparate encodings
7289 // + Compressed stores up to 1021 entries if few enough compact encoding
7290 // values are used.
7291 outs() << " Second level indices:\n";
7292 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7293 // The final sentinel top-level index has no associated 2nd level page
7294 if (IndexEntries[i].SecondLevelPageStart == 0)
7295 break;
7296
7297 outs() << " Second level index[" << i << "]: "
7298 << "offset in section="
7299 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7300 << ", "
7301 << "base function offset="
7302 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7303
7304 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007305 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007306 if (Kind == 2)
7307 printRegularSecondLevelUnwindPage(Pos);
7308 else if (Kind == 3)
7309 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7310 CommonEncodings);
7311 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007312 outs() << " Skipping 2nd level page with unknown kind " << Kind
7313 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007314 }
7315}
7316
Tim Northover4bd286a2014-08-01 13:07:19 +00007317void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7318 std::map<uint64_t, SymbolRef> Symbols;
7319 for (const SymbolRef &SymRef : Obj->symbols()) {
7320 // Discard any undefined or absolute symbols. They're not going to take part
7321 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007322 auto SectOrErr = SymRef.getSection();
7323 if (!SectOrErr) {
7324 // TODO: Actually report errors helpfully.
7325 consumeError(SectOrErr.takeError());
7326 continue;
7327 }
7328 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007329 if (Section == Obj->section_end())
7330 continue;
7331
Rafael Espindoladea00162015-07-03 17:44:18 +00007332 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007333 Symbols.insert(std::make_pair(Addr, SymRef));
7334 }
7335
7336 for (const SectionRef &Section : Obj->sections()) {
7337 StringRef SectName;
7338 Section.getName(SectName);
7339 if (SectName == "__compact_unwind")
7340 printMachOCompactUnwindSection(Obj, Symbols, Section);
7341 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007342 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007343 }
7344}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007345
7346static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7347 uint32_t cpusubtype, uint32_t filetype,
7348 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7349 bool verbose) {
7350 outs() << "Mach header\n";
7351 outs() << " magic cputype cpusubtype caps filetype ncmds "
7352 "sizeofcmds flags\n";
7353 if (verbose) {
7354 if (magic == MachO::MH_MAGIC)
7355 outs() << " MH_MAGIC";
7356 else if (magic == MachO::MH_MAGIC_64)
7357 outs() << "MH_MAGIC_64";
7358 else
7359 outs() << format(" 0x%08" PRIx32, magic);
7360 switch (cputype) {
7361 case MachO::CPU_TYPE_I386:
7362 outs() << " I386";
7363 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7364 case MachO::CPU_SUBTYPE_I386_ALL:
7365 outs() << " ALL";
7366 break;
7367 default:
7368 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7369 break;
7370 }
7371 break;
7372 case MachO::CPU_TYPE_X86_64:
7373 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007374 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7375 case MachO::CPU_SUBTYPE_X86_64_ALL:
7376 outs() << " ALL";
7377 break;
7378 case MachO::CPU_SUBTYPE_X86_64_H:
7379 outs() << " Haswell";
7380 break;
7381 default:
7382 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7383 break;
7384 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007385 break;
7386 case MachO::CPU_TYPE_ARM:
7387 outs() << " ARM";
7388 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7389 case MachO::CPU_SUBTYPE_ARM_ALL:
7390 outs() << " ALL";
7391 break;
7392 case MachO::CPU_SUBTYPE_ARM_V4T:
7393 outs() << " V4T";
7394 break;
7395 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7396 outs() << " V5TEJ";
7397 break;
7398 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7399 outs() << " XSCALE";
7400 break;
7401 case MachO::CPU_SUBTYPE_ARM_V6:
7402 outs() << " V6";
7403 break;
7404 case MachO::CPU_SUBTYPE_ARM_V6M:
7405 outs() << " V6M";
7406 break;
7407 case MachO::CPU_SUBTYPE_ARM_V7:
7408 outs() << " V7";
7409 break;
7410 case MachO::CPU_SUBTYPE_ARM_V7EM:
7411 outs() << " V7EM";
7412 break;
7413 case MachO::CPU_SUBTYPE_ARM_V7K:
7414 outs() << " V7K";
7415 break;
7416 case MachO::CPU_SUBTYPE_ARM_V7M:
7417 outs() << " V7M";
7418 break;
7419 case MachO::CPU_SUBTYPE_ARM_V7S:
7420 outs() << " V7S";
7421 break;
7422 default:
7423 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7424 break;
7425 }
7426 break;
7427 case MachO::CPU_TYPE_ARM64:
7428 outs() << " ARM64";
7429 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7430 case MachO::CPU_SUBTYPE_ARM64_ALL:
7431 outs() << " ALL";
7432 break;
7433 default:
7434 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7435 break;
7436 }
7437 break;
7438 case MachO::CPU_TYPE_POWERPC:
7439 outs() << " PPC";
7440 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7441 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7442 outs() << " ALL";
7443 break;
7444 default:
7445 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7446 break;
7447 }
7448 break;
7449 case MachO::CPU_TYPE_POWERPC64:
7450 outs() << " PPC64";
7451 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7452 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7453 outs() << " ALL";
7454 break;
7455 default:
7456 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7457 break;
7458 }
7459 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007460 default:
7461 outs() << format(" %7d", cputype);
7462 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7463 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007464 }
7465 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007466 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007467 } else {
7468 outs() << format(" 0x%02" PRIx32,
7469 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7470 }
7471 switch (filetype) {
7472 case MachO::MH_OBJECT:
7473 outs() << " OBJECT";
7474 break;
7475 case MachO::MH_EXECUTE:
7476 outs() << " EXECUTE";
7477 break;
7478 case MachO::MH_FVMLIB:
7479 outs() << " FVMLIB";
7480 break;
7481 case MachO::MH_CORE:
7482 outs() << " CORE";
7483 break;
7484 case MachO::MH_PRELOAD:
7485 outs() << " PRELOAD";
7486 break;
7487 case MachO::MH_DYLIB:
7488 outs() << " DYLIB";
7489 break;
7490 case MachO::MH_DYLIB_STUB:
7491 outs() << " DYLIB_STUB";
7492 break;
7493 case MachO::MH_DYLINKER:
7494 outs() << " DYLINKER";
7495 break;
7496 case MachO::MH_BUNDLE:
7497 outs() << " BUNDLE";
7498 break;
7499 case MachO::MH_DSYM:
7500 outs() << " DSYM";
7501 break;
7502 case MachO::MH_KEXT_BUNDLE:
7503 outs() << " KEXTBUNDLE";
7504 break;
7505 default:
7506 outs() << format(" %10u", filetype);
7507 break;
7508 }
7509 outs() << format(" %5u", ncmds);
7510 outs() << format(" %10u", sizeofcmds);
7511 uint32_t f = flags;
7512 if (f & MachO::MH_NOUNDEFS) {
7513 outs() << " NOUNDEFS";
7514 f &= ~MachO::MH_NOUNDEFS;
7515 }
7516 if (f & MachO::MH_INCRLINK) {
7517 outs() << " INCRLINK";
7518 f &= ~MachO::MH_INCRLINK;
7519 }
7520 if (f & MachO::MH_DYLDLINK) {
7521 outs() << " DYLDLINK";
7522 f &= ~MachO::MH_DYLDLINK;
7523 }
7524 if (f & MachO::MH_BINDATLOAD) {
7525 outs() << " BINDATLOAD";
7526 f &= ~MachO::MH_BINDATLOAD;
7527 }
7528 if (f & MachO::MH_PREBOUND) {
7529 outs() << " PREBOUND";
7530 f &= ~MachO::MH_PREBOUND;
7531 }
7532 if (f & MachO::MH_SPLIT_SEGS) {
7533 outs() << " SPLIT_SEGS";
7534 f &= ~MachO::MH_SPLIT_SEGS;
7535 }
7536 if (f & MachO::MH_LAZY_INIT) {
7537 outs() << " LAZY_INIT";
7538 f &= ~MachO::MH_LAZY_INIT;
7539 }
7540 if (f & MachO::MH_TWOLEVEL) {
7541 outs() << " TWOLEVEL";
7542 f &= ~MachO::MH_TWOLEVEL;
7543 }
7544 if (f & MachO::MH_FORCE_FLAT) {
7545 outs() << " FORCE_FLAT";
7546 f &= ~MachO::MH_FORCE_FLAT;
7547 }
7548 if (f & MachO::MH_NOMULTIDEFS) {
7549 outs() << " NOMULTIDEFS";
7550 f &= ~MachO::MH_NOMULTIDEFS;
7551 }
7552 if (f & MachO::MH_NOFIXPREBINDING) {
7553 outs() << " NOFIXPREBINDING";
7554 f &= ~MachO::MH_NOFIXPREBINDING;
7555 }
7556 if (f & MachO::MH_PREBINDABLE) {
7557 outs() << " PREBINDABLE";
7558 f &= ~MachO::MH_PREBINDABLE;
7559 }
7560 if (f & MachO::MH_ALLMODSBOUND) {
7561 outs() << " ALLMODSBOUND";
7562 f &= ~MachO::MH_ALLMODSBOUND;
7563 }
7564 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7565 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7566 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7567 }
7568 if (f & MachO::MH_CANONICAL) {
7569 outs() << " CANONICAL";
7570 f &= ~MachO::MH_CANONICAL;
7571 }
7572 if (f & MachO::MH_WEAK_DEFINES) {
7573 outs() << " WEAK_DEFINES";
7574 f &= ~MachO::MH_WEAK_DEFINES;
7575 }
7576 if (f & MachO::MH_BINDS_TO_WEAK) {
7577 outs() << " BINDS_TO_WEAK";
7578 f &= ~MachO::MH_BINDS_TO_WEAK;
7579 }
7580 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7581 outs() << " ALLOW_STACK_EXECUTION";
7582 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7583 }
7584 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7585 outs() << " DEAD_STRIPPABLE_DYLIB";
7586 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7587 }
7588 if (f & MachO::MH_PIE) {
7589 outs() << " PIE";
7590 f &= ~MachO::MH_PIE;
7591 }
7592 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7593 outs() << " NO_REEXPORTED_DYLIBS";
7594 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7595 }
7596 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7597 outs() << " MH_HAS_TLV_DESCRIPTORS";
7598 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7599 }
7600 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7601 outs() << " MH_NO_HEAP_EXECUTION";
7602 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7603 }
7604 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7605 outs() << " APP_EXTENSION_SAFE";
7606 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7607 }
7608 if (f != 0 || flags == 0)
7609 outs() << format(" 0x%08" PRIx32, f);
7610 } else {
7611 outs() << format(" 0x%08" PRIx32, magic);
7612 outs() << format(" %7d", cputype);
7613 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7614 outs() << format(" 0x%02" PRIx32,
7615 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7616 outs() << format(" %10u", filetype);
7617 outs() << format(" %5u", ncmds);
7618 outs() << format(" %10u", sizeofcmds);
7619 outs() << format(" 0x%08" PRIx32, flags);
7620 }
7621 outs() << "\n";
7622}
7623
Kevin Enderby956366c2014-08-29 22:30:52 +00007624static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7625 StringRef SegName, uint64_t vmaddr,
7626 uint64_t vmsize, uint64_t fileoff,
7627 uint64_t filesize, uint32_t maxprot,
7628 uint32_t initprot, uint32_t nsects,
7629 uint32_t flags, uint32_t object_size,
7630 bool verbose) {
7631 uint64_t expected_cmdsize;
7632 if (cmd == MachO::LC_SEGMENT) {
7633 outs() << " cmd LC_SEGMENT\n";
7634 expected_cmdsize = nsects;
7635 expected_cmdsize *= sizeof(struct MachO::section);
7636 expected_cmdsize += sizeof(struct MachO::segment_command);
7637 } else {
7638 outs() << " cmd LC_SEGMENT_64\n";
7639 expected_cmdsize = nsects;
7640 expected_cmdsize *= sizeof(struct MachO::section_64);
7641 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7642 }
7643 outs() << " cmdsize " << cmdsize;
7644 if (cmdsize != expected_cmdsize)
7645 outs() << " Inconsistent size\n";
7646 else
7647 outs() << "\n";
7648 outs() << " segname " << SegName << "\n";
7649 if (cmd == MachO::LC_SEGMENT_64) {
7650 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7651 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7652 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007653 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7654 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007655 }
7656 outs() << " fileoff " << fileoff;
7657 if (fileoff > object_size)
7658 outs() << " (past end of file)\n";
7659 else
7660 outs() << "\n";
7661 outs() << " filesize " << filesize;
7662 if (fileoff + filesize > object_size)
7663 outs() << " (past end of file)\n";
7664 else
7665 outs() << "\n";
7666 if (verbose) {
7667 if ((maxprot &
7668 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7669 MachO::VM_PROT_EXECUTE)) != 0)
7670 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7671 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007672 outs() << " maxprot ";
7673 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7674 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7675 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007676 }
7677 if ((initprot &
7678 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7679 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00007680 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007681 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00007682 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00007683 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7684 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7685 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007686 }
7687 } else {
7688 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7689 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7690 }
7691 outs() << " nsects " << nsects << "\n";
7692 if (verbose) {
7693 outs() << " flags";
7694 if (flags == 0)
7695 outs() << " (none)\n";
7696 else {
7697 if (flags & MachO::SG_HIGHVM) {
7698 outs() << " HIGHVM";
7699 flags &= ~MachO::SG_HIGHVM;
7700 }
7701 if (flags & MachO::SG_FVMLIB) {
7702 outs() << " FVMLIB";
7703 flags &= ~MachO::SG_FVMLIB;
7704 }
7705 if (flags & MachO::SG_NORELOC) {
7706 outs() << " NORELOC";
7707 flags &= ~MachO::SG_NORELOC;
7708 }
7709 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7710 outs() << " PROTECTED_VERSION_1";
7711 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7712 }
7713 if (flags)
7714 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7715 else
7716 outs() << "\n";
7717 }
7718 } else {
7719 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7720 }
7721}
7722
7723static void PrintSection(const char *sectname, const char *segname,
7724 uint64_t addr, uint64_t size, uint32_t offset,
7725 uint32_t align, uint32_t reloff, uint32_t nreloc,
7726 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7727 uint32_t cmd, const char *sg_segname,
7728 uint32_t filetype, uint32_t object_size,
7729 bool verbose) {
7730 outs() << "Section\n";
7731 outs() << " sectname " << format("%.16s\n", sectname);
7732 outs() << " segname " << format("%.16s", segname);
7733 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7734 outs() << " (does not match segment)\n";
7735 else
7736 outs() << "\n";
7737 if (cmd == MachO::LC_SEGMENT_64) {
7738 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7739 outs() << " size " << format("0x%016" PRIx64, size);
7740 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007741 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7742 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007743 }
7744 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7745 outs() << " (past end of file)\n";
7746 else
7747 outs() << "\n";
7748 outs() << " offset " << offset;
7749 if (offset > object_size)
7750 outs() << " (past end of file)\n";
7751 else
7752 outs() << "\n";
7753 uint32_t align_shifted = 1 << align;
7754 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7755 outs() << " reloff " << reloff;
7756 if (reloff > object_size)
7757 outs() << " (past end of file)\n";
7758 else
7759 outs() << "\n";
7760 outs() << " nreloc " << nreloc;
7761 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7762 outs() << " (past end of file)\n";
7763 else
7764 outs() << "\n";
7765 uint32_t section_type = flags & MachO::SECTION_TYPE;
7766 if (verbose) {
7767 outs() << " type";
7768 if (section_type == MachO::S_REGULAR)
7769 outs() << " S_REGULAR\n";
7770 else if (section_type == MachO::S_ZEROFILL)
7771 outs() << " S_ZEROFILL\n";
7772 else if (section_type == MachO::S_CSTRING_LITERALS)
7773 outs() << " S_CSTRING_LITERALS\n";
7774 else if (section_type == MachO::S_4BYTE_LITERALS)
7775 outs() << " S_4BYTE_LITERALS\n";
7776 else if (section_type == MachO::S_8BYTE_LITERALS)
7777 outs() << " S_8BYTE_LITERALS\n";
7778 else if (section_type == MachO::S_16BYTE_LITERALS)
7779 outs() << " S_16BYTE_LITERALS\n";
7780 else if (section_type == MachO::S_LITERAL_POINTERS)
7781 outs() << " S_LITERAL_POINTERS\n";
7782 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7783 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7784 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7785 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7786 else if (section_type == MachO::S_SYMBOL_STUBS)
7787 outs() << " S_SYMBOL_STUBS\n";
7788 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7789 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7790 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7791 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7792 else if (section_type == MachO::S_COALESCED)
7793 outs() << " S_COALESCED\n";
7794 else if (section_type == MachO::S_INTERPOSING)
7795 outs() << " S_INTERPOSING\n";
7796 else if (section_type == MachO::S_DTRACE_DOF)
7797 outs() << " S_DTRACE_DOF\n";
7798 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7799 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7800 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7801 outs() << " S_THREAD_LOCAL_REGULAR\n";
7802 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7803 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7804 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7805 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7806 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7807 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7808 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7809 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7810 else
7811 outs() << format("0x%08" PRIx32, section_type) << "\n";
7812 outs() << "attributes";
7813 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7814 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7815 outs() << " PURE_INSTRUCTIONS";
7816 if (section_attributes & MachO::S_ATTR_NO_TOC)
7817 outs() << " NO_TOC";
7818 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7819 outs() << " STRIP_STATIC_SYMS";
7820 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7821 outs() << " NO_DEAD_STRIP";
7822 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7823 outs() << " LIVE_SUPPORT";
7824 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7825 outs() << " SELF_MODIFYING_CODE";
7826 if (section_attributes & MachO::S_ATTR_DEBUG)
7827 outs() << " DEBUG";
7828 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7829 outs() << " SOME_INSTRUCTIONS";
7830 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7831 outs() << " EXT_RELOC";
7832 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7833 outs() << " LOC_RELOC";
7834 if (section_attributes == 0)
7835 outs() << " (none)";
7836 outs() << "\n";
7837 } else
7838 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7839 outs() << " reserved1 " << reserved1;
7840 if (section_type == MachO::S_SYMBOL_STUBS ||
7841 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7842 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7843 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7844 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7845 outs() << " (index into indirect symbol table)\n";
7846 else
7847 outs() << "\n";
7848 outs() << " reserved2 " << reserved2;
7849 if (section_type == MachO::S_SYMBOL_STUBS)
7850 outs() << " (size of stubs)\n";
7851 else
7852 outs() << "\n";
7853}
7854
David Majnemer73cc6ff2014-11-13 19:48:56 +00007855static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007856 uint32_t object_size) {
7857 outs() << " cmd LC_SYMTAB\n";
7858 outs() << " cmdsize " << st.cmdsize;
7859 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7860 outs() << " Incorrect size\n";
7861 else
7862 outs() << "\n";
7863 outs() << " symoff " << st.symoff;
7864 if (st.symoff > object_size)
7865 outs() << " (past end of file)\n";
7866 else
7867 outs() << "\n";
7868 outs() << " nsyms " << st.nsyms;
7869 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007870 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007871 big_size = st.nsyms;
7872 big_size *= sizeof(struct MachO::nlist_64);
7873 big_size += st.symoff;
7874 if (big_size > object_size)
7875 outs() << " (past end of file)\n";
7876 else
7877 outs() << "\n";
7878 } else {
7879 big_size = st.nsyms;
7880 big_size *= sizeof(struct MachO::nlist);
7881 big_size += st.symoff;
7882 if (big_size > object_size)
7883 outs() << " (past end of file)\n";
7884 else
7885 outs() << "\n";
7886 }
7887 outs() << " stroff " << st.stroff;
7888 if (st.stroff > object_size)
7889 outs() << " (past end of file)\n";
7890 else
7891 outs() << "\n";
7892 outs() << " strsize " << st.strsize;
7893 big_size = st.stroff;
7894 big_size += st.strsize;
7895 if (big_size > object_size)
7896 outs() << " (past end of file)\n";
7897 else
7898 outs() << "\n";
7899}
7900
7901static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7902 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007903 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007904 outs() << " cmd LC_DYSYMTAB\n";
7905 outs() << " cmdsize " << dyst.cmdsize;
7906 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7907 outs() << " Incorrect size\n";
7908 else
7909 outs() << "\n";
7910 outs() << " ilocalsym " << dyst.ilocalsym;
7911 if (dyst.ilocalsym > nsyms)
7912 outs() << " (greater than the number of symbols)\n";
7913 else
7914 outs() << "\n";
7915 outs() << " nlocalsym " << dyst.nlocalsym;
7916 uint64_t big_size;
7917 big_size = dyst.ilocalsym;
7918 big_size += dyst.nlocalsym;
7919 if (big_size > nsyms)
7920 outs() << " (past the end of the symbol table)\n";
7921 else
7922 outs() << "\n";
7923 outs() << " iextdefsym " << dyst.iextdefsym;
7924 if (dyst.iextdefsym > nsyms)
7925 outs() << " (greater than the number of symbols)\n";
7926 else
7927 outs() << "\n";
7928 outs() << " nextdefsym " << dyst.nextdefsym;
7929 big_size = dyst.iextdefsym;
7930 big_size += dyst.nextdefsym;
7931 if (big_size > nsyms)
7932 outs() << " (past the end of the symbol table)\n";
7933 else
7934 outs() << "\n";
7935 outs() << " iundefsym " << dyst.iundefsym;
7936 if (dyst.iundefsym > nsyms)
7937 outs() << " (greater than the number of symbols)\n";
7938 else
7939 outs() << "\n";
7940 outs() << " nundefsym " << dyst.nundefsym;
7941 big_size = dyst.iundefsym;
7942 big_size += dyst.nundefsym;
7943 if (big_size > nsyms)
7944 outs() << " (past the end of the symbol table)\n";
7945 else
7946 outs() << "\n";
7947 outs() << " tocoff " << dyst.tocoff;
7948 if (dyst.tocoff > object_size)
7949 outs() << " (past end of file)\n";
7950 else
7951 outs() << "\n";
7952 outs() << " ntoc " << dyst.ntoc;
7953 big_size = dyst.ntoc;
7954 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7955 big_size += dyst.tocoff;
7956 if (big_size > object_size)
7957 outs() << " (past end of file)\n";
7958 else
7959 outs() << "\n";
7960 outs() << " modtaboff " << dyst.modtaboff;
7961 if (dyst.modtaboff > object_size)
7962 outs() << " (past end of file)\n";
7963 else
7964 outs() << "\n";
7965 outs() << " nmodtab " << dyst.nmodtab;
7966 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007967 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007968 modtabend = dyst.nmodtab;
7969 modtabend *= sizeof(struct MachO::dylib_module_64);
7970 modtabend += dyst.modtaboff;
7971 } else {
7972 modtabend = dyst.nmodtab;
7973 modtabend *= sizeof(struct MachO::dylib_module);
7974 modtabend += dyst.modtaboff;
7975 }
7976 if (modtabend > object_size)
7977 outs() << " (past end of file)\n";
7978 else
7979 outs() << "\n";
7980 outs() << " extrefsymoff " << dyst.extrefsymoff;
7981 if (dyst.extrefsymoff > object_size)
7982 outs() << " (past end of file)\n";
7983 else
7984 outs() << "\n";
7985 outs() << " nextrefsyms " << dyst.nextrefsyms;
7986 big_size = dyst.nextrefsyms;
7987 big_size *= sizeof(struct MachO::dylib_reference);
7988 big_size += dyst.extrefsymoff;
7989 if (big_size > object_size)
7990 outs() << " (past end of file)\n";
7991 else
7992 outs() << "\n";
7993 outs() << " indirectsymoff " << dyst.indirectsymoff;
7994 if (dyst.indirectsymoff > object_size)
7995 outs() << " (past end of file)\n";
7996 else
7997 outs() << "\n";
7998 outs() << " nindirectsyms " << dyst.nindirectsyms;
7999 big_size = dyst.nindirectsyms;
8000 big_size *= sizeof(uint32_t);
8001 big_size += dyst.indirectsymoff;
8002 if (big_size > object_size)
8003 outs() << " (past end of file)\n";
8004 else
8005 outs() << "\n";
8006 outs() << " extreloff " << dyst.extreloff;
8007 if (dyst.extreloff > object_size)
8008 outs() << " (past end of file)\n";
8009 else
8010 outs() << "\n";
8011 outs() << " nextrel " << dyst.nextrel;
8012 big_size = dyst.nextrel;
8013 big_size *= sizeof(struct MachO::relocation_info);
8014 big_size += dyst.extreloff;
8015 if (big_size > object_size)
8016 outs() << " (past end of file)\n";
8017 else
8018 outs() << "\n";
8019 outs() << " locreloff " << dyst.locreloff;
8020 if (dyst.locreloff > object_size)
8021 outs() << " (past end of file)\n";
8022 else
8023 outs() << "\n";
8024 outs() << " nlocrel " << dyst.nlocrel;
8025 big_size = dyst.nlocrel;
8026 big_size *= sizeof(struct MachO::relocation_info);
8027 big_size += dyst.locreloff;
8028 if (big_size > object_size)
8029 outs() << " (past end of file)\n";
8030 else
8031 outs() << "\n";
8032}
8033
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008034static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8035 uint32_t object_size) {
8036 if (dc.cmd == MachO::LC_DYLD_INFO)
8037 outs() << " cmd LC_DYLD_INFO\n";
8038 else
8039 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8040 outs() << " cmdsize " << dc.cmdsize;
8041 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8042 outs() << " Incorrect size\n";
8043 else
8044 outs() << "\n";
8045 outs() << " rebase_off " << dc.rebase_off;
8046 if (dc.rebase_off > object_size)
8047 outs() << " (past end of file)\n";
8048 else
8049 outs() << "\n";
8050 outs() << " rebase_size " << dc.rebase_size;
8051 uint64_t big_size;
8052 big_size = dc.rebase_off;
8053 big_size += dc.rebase_size;
8054 if (big_size > object_size)
8055 outs() << " (past end of file)\n";
8056 else
8057 outs() << "\n";
8058 outs() << " bind_off " << dc.bind_off;
8059 if (dc.bind_off > object_size)
8060 outs() << " (past end of file)\n";
8061 else
8062 outs() << "\n";
8063 outs() << " bind_size " << dc.bind_size;
8064 big_size = dc.bind_off;
8065 big_size += dc.bind_size;
8066 if (big_size > object_size)
8067 outs() << " (past end of file)\n";
8068 else
8069 outs() << "\n";
8070 outs() << " weak_bind_off " << dc.weak_bind_off;
8071 if (dc.weak_bind_off > object_size)
8072 outs() << " (past end of file)\n";
8073 else
8074 outs() << "\n";
8075 outs() << " weak_bind_size " << dc.weak_bind_size;
8076 big_size = dc.weak_bind_off;
8077 big_size += dc.weak_bind_size;
8078 if (big_size > object_size)
8079 outs() << " (past end of file)\n";
8080 else
8081 outs() << "\n";
8082 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8083 if (dc.lazy_bind_off > object_size)
8084 outs() << " (past end of file)\n";
8085 else
8086 outs() << "\n";
8087 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8088 big_size = dc.lazy_bind_off;
8089 big_size += dc.lazy_bind_size;
8090 if (big_size > object_size)
8091 outs() << " (past end of file)\n";
8092 else
8093 outs() << "\n";
8094 outs() << " export_off " << dc.export_off;
8095 if (dc.export_off > object_size)
8096 outs() << " (past end of file)\n";
8097 else
8098 outs() << "\n";
8099 outs() << " export_size " << dc.export_size;
8100 big_size = dc.export_off;
8101 big_size += dc.export_size;
8102 if (big_size > object_size)
8103 outs() << " (past end of file)\n";
8104 else
8105 outs() << "\n";
8106}
8107
8108static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8109 const char *Ptr) {
8110 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8111 outs() << " cmd LC_ID_DYLINKER\n";
8112 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8113 outs() << " cmd LC_LOAD_DYLINKER\n";
8114 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8115 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8116 else
8117 outs() << " cmd ?(" << dyld.cmd << ")\n";
8118 outs() << " cmdsize " << dyld.cmdsize;
8119 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8120 outs() << " Incorrect size\n";
8121 else
8122 outs() << "\n";
8123 if (dyld.name >= dyld.cmdsize)
8124 outs() << " name ?(bad offset " << dyld.name << ")\n";
8125 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008126 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008127 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8128 }
8129}
8130
8131static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8132 outs() << " cmd LC_UUID\n";
8133 outs() << " cmdsize " << uuid.cmdsize;
8134 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8135 outs() << " Incorrect size\n";
8136 else
8137 outs() << "\n";
8138 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008139 for (int i = 0; i < 16; ++i) {
8140 outs() << format("%02" PRIX32, uuid.uuid[i]);
8141 if (i == 3 || i == 5 || i == 7 || i == 9)
8142 outs() << "-";
8143 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008144 outs() << "\n";
8145}
8146
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008147static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008148 outs() << " cmd LC_RPATH\n";
8149 outs() << " cmdsize " << rpath.cmdsize;
8150 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8151 outs() << " Incorrect size\n";
8152 else
8153 outs() << "\n";
8154 if (rpath.path >= rpath.cmdsize)
8155 outs() << " path ?(bad offset " << rpath.path << ")\n";
8156 else {
8157 const char *P = (const char *)(Ptr) + rpath.path;
8158 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8159 }
8160}
8161
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008162static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008163 StringRef LoadCmdName;
8164 switch (vd.cmd) {
8165 case MachO::LC_VERSION_MIN_MACOSX:
8166 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8167 break;
8168 case MachO::LC_VERSION_MIN_IPHONEOS:
8169 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8170 break;
8171 case MachO::LC_VERSION_MIN_TVOS:
8172 LoadCmdName = "LC_VERSION_MIN_TVOS";
8173 break;
8174 case MachO::LC_VERSION_MIN_WATCHOS:
8175 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8176 break;
8177 default:
8178 llvm_unreachable("Unknown version min load command");
8179 }
8180
8181 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008182 outs() << " cmdsize " << vd.cmdsize;
8183 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8184 outs() << " Incorrect size\n";
8185 else
8186 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008187 outs() << " version "
8188 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8189 << MachOObjectFile::getVersionMinMinor(vd, false);
8190 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8191 if (Update != 0)
8192 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008193 outs() << "\n";
8194 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008195 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008196 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008197 outs() << " sdk "
8198 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8199 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008200 }
Davide Italiano56baef32015-08-26 12:26:11 +00008201 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8202 if (Update != 0)
8203 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008204 outs() << "\n";
8205}
8206
Kevin Enderbya4579c42017-01-19 17:36:31 +00008207static void PrintNoteLoadCommand(MachO::note_command Nt) {
8208 outs() << " cmd LC_NOTE\n";
8209 outs() << " cmdsize " << Nt.cmdsize;
8210 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8211 outs() << " Incorrect size\n";
8212 else
8213 outs() << "\n";
8214 const char *d = Nt.data_owner;
8215 outs() << "data_owner " << format("%.16s\n", d);
8216 outs() << " offset " << Nt.offset << "\n";
8217 outs() << " size " << Nt.size << "\n";
8218}
8219
Steven Wu5b54a422017-01-23 20:07:55 +00008220static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8221 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8222 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8223 << "\n";
8224}
8225
8226static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8227 MachO::build_version_command bd) {
8228 outs() << " cmd LC_BUILD_VERSION\n";
8229 outs() << " cmdsize " << bd.cmdsize;
8230 if (bd.cmdsize !=
8231 sizeof(struct MachO::build_version_command) +
8232 bd.ntools * sizeof(struct MachO::build_tool_version))
8233 outs() << " Incorrect size\n";
8234 else
8235 outs() << "\n";
8236 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8237 << "\n";
8238 if (bd.sdk)
8239 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8240 << "\n";
8241 else
8242 outs() << " sdk n/a\n";
8243 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8244 << "\n";
8245 outs() << " ntools " << bd.ntools << "\n";
8246 for (unsigned i = 0; i < bd.ntools; ++i) {
8247 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8248 PrintBuildToolVersion(bv);
8249 }
8250}
8251
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008252static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8253 outs() << " cmd LC_SOURCE_VERSION\n";
8254 outs() << " cmdsize " << sd.cmdsize;
8255 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8256 outs() << " Incorrect size\n";
8257 else
8258 outs() << "\n";
8259 uint64_t a = (sd.version >> 40) & 0xffffff;
8260 uint64_t b = (sd.version >> 30) & 0x3ff;
8261 uint64_t c = (sd.version >> 20) & 0x3ff;
8262 uint64_t d = (sd.version >> 10) & 0x3ff;
8263 uint64_t e = sd.version & 0x3ff;
8264 outs() << " version " << a << "." << b;
8265 if (e != 0)
8266 outs() << "." << c << "." << d << "." << e;
8267 else if (d != 0)
8268 outs() << "." << c << "." << d;
8269 else if (c != 0)
8270 outs() << "." << c;
8271 outs() << "\n";
8272}
8273
8274static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8275 outs() << " cmd LC_MAIN\n";
8276 outs() << " cmdsize " << ep.cmdsize;
8277 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8278 outs() << " Incorrect size\n";
8279 else
8280 outs() << "\n";
8281 outs() << " entryoff " << ep.entryoff << "\n";
8282 outs() << " stacksize " << ep.stacksize << "\n";
8283}
8284
Kevin Enderby0804f4672014-12-16 23:25:52 +00008285static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8286 uint32_t object_size) {
8287 outs() << " cmd LC_ENCRYPTION_INFO\n";
8288 outs() << " cmdsize " << ec.cmdsize;
8289 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8290 outs() << " Incorrect size\n";
8291 else
8292 outs() << "\n";
8293 outs() << " cryptoff " << ec.cryptoff;
8294 if (ec.cryptoff > object_size)
8295 outs() << " (past end of file)\n";
8296 else
8297 outs() << "\n";
8298 outs() << " cryptsize " << ec.cryptsize;
8299 if (ec.cryptsize > object_size)
8300 outs() << " (past end of file)\n";
8301 else
8302 outs() << "\n";
8303 outs() << " cryptid " << ec.cryptid << "\n";
8304}
8305
Kevin Enderby57538292014-12-17 01:01:30 +00008306static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008307 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008308 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8309 outs() << " cmdsize " << ec.cmdsize;
8310 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8311 outs() << " Incorrect size\n";
8312 else
8313 outs() << "\n";
8314 outs() << " cryptoff " << ec.cryptoff;
8315 if (ec.cryptoff > object_size)
8316 outs() << " (past end of file)\n";
8317 else
8318 outs() << "\n";
8319 outs() << " cryptsize " << ec.cryptsize;
8320 if (ec.cryptsize > object_size)
8321 outs() << " (past end of file)\n";
8322 else
8323 outs() << "\n";
8324 outs() << " cryptid " << ec.cryptid << "\n";
8325 outs() << " pad " << ec.pad << "\n";
8326}
8327
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008328static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8329 const char *Ptr) {
8330 outs() << " cmd LC_LINKER_OPTION\n";
8331 outs() << " cmdsize " << lo.cmdsize;
8332 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8333 outs() << " Incorrect size\n";
8334 else
8335 outs() << "\n";
8336 outs() << " count " << lo.count << "\n";
8337 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8338 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8339 uint32_t i = 0;
8340 while (left > 0) {
8341 while (*string == '\0' && left > 0) {
8342 string++;
8343 left--;
8344 }
8345 if (left > 0) {
8346 i++;
8347 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008348 uint32_t NullPos = StringRef(string, left).find('\0');
8349 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008350 string += len;
8351 left -= len;
8352 }
8353 }
8354 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008355 outs() << " count " << lo.count << " does not match number of strings "
8356 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008357}
8358
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008359static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8360 const char *Ptr) {
8361 outs() << " cmd LC_SUB_FRAMEWORK\n";
8362 outs() << " cmdsize " << sub.cmdsize;
8363 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8364 outs() << " Incorrect size\n";
8365 else
8366 outs() << "\n";
8367 if (sub.umbrella < sub.cmdsize) {
8368 const char *P = Ptr + sub.umbrella;
8369 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8370 } else {
8371 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8372 }
8373}
8374
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008375static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8376 const char *Ptr) {
8377 outs() << " cmd LC_SUB_UMBRELLA\n";
8378 outs() << " cmdsize " << sub.cmdsize;
8379 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8380 outs() << " Incorrect size\n";
8381 else
8382 outs() << "\n";
8383 if (sub.sub_umbrella < sub.cmdsize) {
8384 const char *P = Ptr + sub.sub_umbrella;
8385 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8386 } else {
8387 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8388 }
8389}
8390
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008391static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008392 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008393 outs() << " cmd LC_SUB_LIBRARY\n";
8394 outs() << " cmdsize " << sub.cmdsize;
8395 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8396 outs() << " Incorrect size\n";
8397 else
8398 outs() << "\n";
8399 if (sub.sub_library < sub.cmdsize) {
8400 const char *P = Ptr + sub.sub_library;
8401 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8402 } else {
8403 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8404 }
8405}
8406
Kevin Enderby186eac32014-12-19 21:06:24 +00008407static void PrintSubClientCommand(MachO::sub_client_command sub,
8408 const char *Ptr) {
8409 outs() << " cmd LC_SUB_CLIENT\n";
8410 outs() << " cmdsize " << sub.cmdsize;
8411 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8412 outs() << " Incorrect size\n";
8413 else
8414 outs() << "\n";
8415 if (sub.client < sub.cmdsize) {
8416 const char *P = Ptr + sub.client;
8417 outs() << " client " << P << " (offset " << sub.client << ")\n";
8418 } else {
8419 outs() << " client ?(bad offset " << sub.client << ")\n";
8420 }
8421}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008422
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008423static void PrintRoutinesCommand(MachO::routines_command r) {
8424 outs() << " cmd LC_ROUTINES\n";
8425 outs() << " cmdsize " << r.cmdsize;
8426 if (r.cmdsize != sizeof(struct MachO::routines_command))
8427 outs() << " Incorrect size\n";
8428 else
8429 outs() << "\n";
8430 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8431 outs() << " init_module " << r.init_module << "\n";
8432 outs() << " reserved1 " << r.reserved1 << "\n";
8433 outs() << " reserved2 " << r.reserved2 << "\n";
8434 outs() << " reserved3 " << r.reserved3 << "\n";
8435 outs() << " reserved4 " << r.reserved4 << "\n";
8436 outs() << " reserved5 " << r.reserved5 << "\n";
8437 outs() << " reserved6 " << r.reserved6 << "\n";
8438}
8439
8440static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8441 outs() << " cmd LC_ROUTINES_64\n";
8442 outs() << " cmdsize " << r.cmdsize;
8443 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8444 outs() << " Incorrect size\n";
8445 else
8446 outs() << "\n";
8447 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8448 outs() << " init_module " << r.init_module << "\n";
8449 outs() << " reserved1 " << r.reserved1 << "\n";
8450 outs() << " reserved2 " << r.reserved2 << "\n";
8451 outs() << " reserved3 " << r.reserved3 << "\n";
8452 outs() << " reserved4 " << r.reserved4 << "\n";
8453 outs() << " reserved5 " << r.reserved5 << "\n";
8454 outs() << " reserved6 " << r.reserved6 << "\n";
8455}
8456
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008457static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8458 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8459 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8460 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8461 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8462 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8463 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8464 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8465 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8466 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8467 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8468 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8469 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8470 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8471 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8472 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8473 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8474}
8475
Kevin Enderby48ef5342014-12-23 22:56:39 +00008476static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8477 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8478 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8479 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8480 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8481 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8482 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8483 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8484 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8485 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8486 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8487 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8488 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8489 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8490 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8491 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8492 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8493 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8494 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8495 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8496 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8497 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8498}
8499
Kevin Enderby227df342014-12-23 23:43:59 +00008500static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008501 uint32_t f;
8502 outs() << "\t mmst_reg ";
8503 for (f = 0; f < 10; f++)
8504 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8505 outs() << "\n";
8506 outs() << "\t mmst_rsrv ";
8507 for (f = 0; f < 6; f++)
8508 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8509 outs() << "\n";
8510}
8511
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008512static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008513 uint32_t f;
8514 outs() << "\t xmm_reg ";
8515 for (f = 0; f < 16; f++)
8516 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8517 outs() << "\n";
8518}
8519
8520static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8521 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8522 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8523 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8524 outs() << " denorm " << fpu.fpu_fcw.denorm;
8525 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8526 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8527 outs() << " undfl " << fpu.fpu_fcw.undfl;
8528 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8529 outs() << "\t\t pc ";
8530 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8531 outs() << "FP_PREC_24B ";
8532 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8533 outs() << "FP_PREC_53B ";
8534 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8535 outs() << "FP_PREC_64B ";
8536 else
8537 outs() << fpu.fpu_fcw.pc << " ";
8538 outs() << "rc ";
8539 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8540 outs() << "FP_RND_NEAR ";
8541 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8542 outs() << "FP_RND_DOWN ";
8543 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8544 outs() << "FP_RND_UP ";
8545 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008546 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008547 outs() << "\n";
8548 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8549 outs() << " denorm " << fpu.fpu_fsw.denorm;
8550 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8551 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8552 outs() << " undfl " << fpu.fpu_fsw.undfl;
8553 outs() << " precis " << fpu.fpu_fsw.precis;
8554 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8555 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8556 outs() << " c0 " << fpu.fpu_fsw.c0;
8557 outs() << " c1 " << fpu.fpu_fsw.c1;
8558 outs() << " c2 " << fpu.fpu_fsw.c2;
8559 outs() << " tos " << fpu.fpu_fsw.tos;
8560 outs() << " c3 " << fpu.fpu_fsw.c3;
8561 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8562 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8563 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8564 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8565 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8566 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8567 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8568 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8569 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8570 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8571 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8572 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8573 outs() << "\n";
8574 outs() << "\t fpu_stmm0:\n";
8575 Print_mmst_reg(fpu.fpu_stmm0);
8576 outs() << "\t fpu_stmm1:\n";
8577 Print_mmst_reg(fpu.fpu_stmm1);
8578 outs() << "\t fpu_stmm2:\n";
8579 Print_mmst_reg(fpu.fpu_stmm2);
8580 outs() << "\t fpu_stmm3:\n";
8581 Print_mmst_reg(fpu.fpu_stmm3);
8582 outs() << "\t fpu_stmm4:\n";
8583 Print_mmst_reg(fpu.fpu_stmm4);
8584 outs() << "\t fpu_stmm5:\n";
8585 Print_mmst_reg(fpu.fpu_stmm5);
8586 outs() << "\t fpu_stmm6:\n";
8587 Print_mmst_reg(fpu.fpu_stmm6);
8588 outs() << "\t fpu_stmm7:\n";
8589 Print_mmst_reg(fpu.fpu_stmm7);
8590 outs() << "\t fpu_xmm0:\n";
8591 Print_xmm_reg(fpu.fpu_xmm0);
8592 outs() << "\t fpu_xmm1:\n";
8593 Print_xmm_reg(fpu.fpu_xmm1);
8594 outs() << "\t fpu_xmm2:\n";
8595 Print_xmm_reg(fpu.fpu_xmm2);
8596 outs() << "\t fpu_xmm3:\n";
8597 Print_xmm_reg(fpu.fpu_xmm3);
8598 outs() << "\t fpu_xmm4:\n";
8599 Print_xmm_reg(fpu.fpu_xmm4);
8600 outs() << "\t fpu_xmm5:\n";
8601 Print_xmm_reg(fpu.fpu_xmm5);
8602 outs() << "\t fpu_xmm6:\n";
8603 Print_xmm_reg(fpu.fpu_xmm6);
8604 outs() << "\t fpu_xmm7:\n";
8605 Print_xmm_reg(fpu.fpu_xmm7);
8606 outs() << "\t fpu_xmm8:\n";
8607 Print_xmm_reg(fpu.fpu_xmm8);
8608 outs() << "\t fpu_xmm9:\n";
8609 Print_xmm_reg(fpu.fpu_xmm9);
8610 outs() << "\t fpu_xmm10:\n";
8611 Print_xmm_reg(fpu.fpu_xmm10);
8612 outs() << "\t fpu_xmm11:\n";
8613 Print_xmm_reg(fpu.fpu_xmm11);
8614 outs() << "\t fpu_xmm12:\n";
8615 Print_xmm_reg(fpu.fpu_xmm12);
8616 outs() << "\t fpu_xmm13:\n";
8617 Print_xmm_reg(fpu.fpu_xmm13);
8618 outs() << "\t fpu_xmm14:\n";
8619 Print_xmm_reg(fpu.fpu_xmm14);
8620 outs() << "\t fpu_xmm15:\n";
8621 Print_xmm_reg(fpu.fpu_xmm15);
8622 outs() << "\t fpu_rsrv4:\n";
8623 for (uint32_t f = 0; f < 6; f++) {
8624 outs() << "\t ";
8625 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008626 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008627 outs() << "\n";
8628 }
8629 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8630 outs() << "\n";
8631}
8632
8633static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8634 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8635 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8636 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8637}
8638
Kevin Enderby41c9c002016-10-21 18:22:35 +00008639static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
8640 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
8641 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
8642 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
8643 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
8644 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
8645 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
8646 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
8647 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
8648 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
8649 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
8650 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
8651 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
8652 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
8653 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
8654 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
8655 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
8656 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
8657}
8658
Kevin Enderby7747cb52016-11-03 20:51:28 +00008659static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
8660 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
8661 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
8662 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
8663 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
8664 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
8665 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
8666 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
8667 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
8668 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
8669 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
8670 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
8671 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
8672 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
8673 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
8674 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
8675 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
8676 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
8677 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
8678 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
8679 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
8680 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
8681 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
8682 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
8683 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
8684 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
8685 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
8686 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
8687 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
8688 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
8689 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
8690 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
8691 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
8692 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
8693 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
8694}
8695
Kevin Enderby48ef5342014-12-23 22:56:39 +00008696static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8697 bool isLittleEndian, uint32_t cputype) {
8698 if (t.cmd == MachO::LC_THREAD)
8699 outs() << " cmd LC_THREAD\n";
8700 else if (t.cmd == MachO::LC_UNIXTHREAD)
8701 outs() << " cmd LC_UNIXTHREAD\n";
8702 else
8703 outs() << " cmd " << t.cmd << " (unknown)\n";
8704 outs() << " cmdsize " << t.cmdsize;
8705 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8706 outs() << " Incorrect size\n";
8707 else
8708 outs() << "\n";
8709
8710 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8711 const char *end = Ptr + t.cmdsize;
8712 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008713 if (cputype == MachO::CPU_TYPE_I386) {
8714 while (begin < end) {
8715 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8716 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8717 begin += sizeof(uint32_t);
8718 } else {
8719 flavor = 0;
8720 begin = end;
8721 }
8722 if (isLittleEndian != sys::IsLittleEndianHost)
8723 sys::swapByteOrder(flavor);
8724 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8725 memcpy((char *)&count, begin, sizeof(uint32_t));
8726 begin += sizeof(uint32_t);
8727 } else {
8728 count = 0;
8729 begin = end;
8730 }
8731 if (isLittleEndian != sys::IsLittleEndianHost)
8732 sys::swapByteOrder(count);
8733 if (flavor == MachO::x86_THREAD_STATE32) {
8734 outs() << " flavor i386_THREAD_STATE\n";
8735 if (count == MachO::x86_THREAD_STATE32_COUNT)
8736 outs() << " count i386_THREAD_STATE_COUNT\n";
8737 else
8738 outs() << " count " << count
8739 << " (not x86_THREAD_STATE32_COUNT)\n";
8740 MachO::x86_thread_state32_t cpu32;
8741 left = end - begin;
8742 if (left >= sizeof(MachO::x86_thread_state32_t)) {
8743 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
8744 begin += sizeof(MachO::x86_thread_state32_t);
8745 } else {
8746 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
8747 memcpy(&cpu32, begin, left);
8748 begin += left;
8749 }
8750 if (isLittleEndian != sys::IsLittleEndianHost)
8751 swapStruct(cpu32);
8752 Print_x86_thread_state32_t(cpu32);
8753 } else if (flavor == MachO::x86_THREAD_STATE) {
8754 outs() << " flavor x86_THREAD_STATE\n";
8755 if (count == MachO::x86_THREAD_STATE_COUNT)
8756 outs() << " count x86_THREAD_STATE_COUNT\n";
8757 else
8758 outs() << " count " << count
8759 << " (not x86_THREAD_STATE_COUNT)\n";
8760 struct MachO::x86_thread_state_t ts;
8761 left = end - begin;
8762 if (left >= sizeof(MachO::x86_thread_state_t)) {
8763 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8764 begin += sizeof(MachO::x86_thread_state_t);
8765 } else {
8766 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8767 memcpy(&ts, begin, left);
8768 begin += left;
8769 }
8770 if (isLittleEndian != sys::IsLittleEndianHost)
8771 swapStruct(ts);
8772 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
8773 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
8774 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
8775 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
8776 else
8777 outs() << "tsh.count " << ts.tsh.count
8778 << " (not x86_THREAD_STATE32_COUNT\n";
8779 Print_x86_thread_state32_t(ts.uts.ts32);
8780 } else {
8781 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8782 << ts.tsh.count << "\n";
8783 }
8784 } else {
8785 outs() << " flavor " << flavor << " (unknown)\n";
8786 outs() << " count " << count << "\n";
8787 outs() << " state (unknown)\n";
8788 begin += count * sizeof(uint32_t);
8789 }
8790 }
8791 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008792 while (begin < end) {
8793 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8794 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8795 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008796 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008797 flavor = 0;
8798 begin = end;
8799 }
8800 if (isLittleEndian != sys::IsLittleEndianHost)
8801 sys::swapByteOrder(flavor);
8802 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8803 memcpy((char *)&count, begin, sizeof(uint32_t));
8804 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008805 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008806 count = 0;
8807 begin = end;
8808 }
8809 if (isLittleEndian != sys::IsLittleEndianHost)
8810 sys::swapByteOrder(count);
8811 if (flavor == MachO::x86_THREAD_STATE64) {
8812 outs() << " flavor x86_THREAD_STATE64\n";
8813 if (count == MachO::x86_THREAD_STATE64_COUNT)
8814 outs() << " count x86_THREAD_STATE64_COUNT\n";
8815 else
8816 outs() << " count " << count
8817 << " (not x86_THREAD_STATE64_COUNT)\n";
8818 MachO::x86_thread_state64_t cpu64;
8819 left = end - begin;
8820 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8821 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8822 begin += sizeof(MachO::x86_thread_state64_t);
8823 } else {
8824 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8825 memcpy(&cpu64, begin, left);
8826 begin += left;
8827 }
8828 if (isLittleEndian != sys::IsLittleEndianHost)
8829 swapStruct(cpu64);
8830 Print_x86_thread_state64_t(cpu64);
8831 } else if (flavor == MachO::x86_THREAD_STATE) {
8832 outs() << " flavor x86_THREAD_STATE\n";
8833 if (count == MachO::x86_THREAD_STATE_COUNT)
8834 outs() << " count x86_THREAD_STATE_COUNT\n";
8835 else
8836 outs() << " count " << count
8837 << " (not x86_THREAD_STATE_COUNT)\n";
8838 struct MachO::x86_thread_state_t ts;
8839 left = end - begin;
8840 if (left >= sizeof(MachO::x86_thread_state_t)) {
8841 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8842 begin += sizeof(MachO::x86_thread_state_t);
8843 } else {
8844 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8845 memcpy(&ts, begin, left);
8846 begin += left;
8847 }
8848 if (isLittleEndian != sys::IsLittleEndianHost)
8849 swapStruct(ts);
8850 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8851 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8852 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8853 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8854 else
8855 outs() << "tsh.count " << ts.tsh.count
8856 << " (not x86_THREAD_STATE64_COUNT\n";
8857 Print_x86_thread_state64_t(ts.uts.ts64);
8858 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008859 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8860 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008861 }
8862 } else if (flavor == MachO::x86_FLOAT_STATE) {
8863 outs() << " flavor x86_FLOAT_STATE\n";
8864 if (count == MachO::x86_FLOAT_STATE_COUNT)
8865 outs() << " count x86_FLOAT_STATE_COUNT\n";
8866 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008867 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008868 struct MachO::x86_float_state_t fs;
8869 left = end - begin;
8870 if (left >= sizeof(MachO::x86_float_state_t)) {
8871 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8872 begin += sizeof(MachO::x86_float_state_t);
8873 } else {
8874 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8875 memcpy(&fs, begin, left);
8876 begin += left;
8877 }
8878 if (isLittleEndian != sys::IsLittleEndianHost)
8879 swapStruct(fs);
8880 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8881 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008882 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008883 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8884 else
8885 outs() << "fsh.count " << fs.fsh.count
8886 << " (not x86_FLOAT_STATE64_COUNT\n";
8887 Print_x86_float_state_t(fs.ufs.fs64);
8888 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008889 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8890 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008891 }
8892 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8893 outs() << " flavor x86_EXCEPTION_STATE\n";
8894 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8895 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8896 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008897 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008898 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8899 struct MachO::x86_exception_state_t es;
8900 left = end - begin;
8901 if (left >= sizeof(MachO::x86_exception_state_t)) {
8902 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8903 begin += sizeof(MachO::x86_exception_state_t);
8904 } else {
8905 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8906 memcpy(&es, begin, left);
8907 begin += left;
8908 }
8909 if (isLittleEndian != sys::IsLittleEndianHost)
8910 swapStruct(es);
8911 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8912 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008913 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008914 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8915 else
8916 outs() << "\t esh.count " << es.esh.count
8917 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8918 Print_x86_exception_state_t(es.ues.es64);
8919 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008920 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8921 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008922 }
8923 } else {
8924 outs() << " flavor " << flavor << " (unknown)\n";
8925 outs() << " count " << count << "\n";
8926 outs() << " state (unknown)\n";
8927 begin += count * sizeof(uint32_t);
8928 }
8929 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00008930 } else if (cputype == MachO::CPU_TYPE_ARM) {
8931 while (begin < end) {
8932 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8933 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8934 begin += sizeof(uint32_t);
8935 } else {
8936 flavor = 0;
8937 begin = end;
8938 }
8939 if (isLittleEndian != sys::IsLittleEndianHost)
8940 sys::swapByteOrder(flavor);
8941 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8942 memcpy((char *)&count, begin, sizeof(uint32_t));
8943 begin += sizeof(uint32_t);
8944 } else {
8945 count = 0;
8946 begin = end;
8947 }
8948 if (isLittleEndian != sys::IsLittleEndianHost)
8949 sys::swapByteOrder(count);
8950 if (flavor == MachO::ARM_THREAD_STATE) {
8951 outs() << " flavor ARM_THREAD_STATE\n";
8952 if (count == MachO::ARM_THREAD_STATE_COUNT)
8953 outs() << " count ARM_THREAD_STATE_COUNT\n";
8954 else
8955 outs() << " count " << count
8956 << " (not ARM_THREAD_STATE_COUNT)\n";
8957 MachO::arm_thread_state32_t cpu32;
8958 left = end - begin;
8959 if (left >= sizeof(MachO::arm_thread_state32_t)) {
8960 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
8961 begin += sizeof(MachO::arm_thread_state32_t);
8962 } else {
8963 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
8964 memcpy(&cpu32, begin, left);
8965 begin += left;
8966 }
8967 if (isLittleEndian != sys::IsLittleEndianHost)
8968 swapStruct(cpu32);
8969 Print_arm_thread_state32_t(cpu32);
8970 } else {
8971 outs() << " flavor " << flavor << " (unknown)\n";
8972 outs() << " count " << count << "\n";
8973 outs() << " state (unknown)\n";
8974 begin += count * sizeof(uint32_t);
8975 }
8976 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00008977 } else if (cputype == MachO::CPU_TYPE_ARM64) {
8978 while (begin < end) {
8979 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8980 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8981 begin += sizeof(uint32_t);
8982 } else {
8983 flavor = 0;
8984 begin = end;
8985 }
8986 if (isLittleEndian != sys::IsLittleEndianHost)
8987 sys::swapByteOrder(flavor);
8988 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8989 memcpy((char *)&count, begin, sizeof(uint32_t));
8990 begin += sizeof(uint32_t);
8991 } else {
8992 count = 0;
8993 begin = end;
8994 }
8995 if (isLittleEndian != sys::IsLittleEndianHost)
8996 sys::swapByteOrder(count);
8997 if (flavor == MachO::ARM_THREAD_STATE64) {
8998 outs() << " flavor ARM_THREAD_STATE64\n";
8999 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9000 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9001 else
9002 outs() << " count " << count
9003 << " (not ARM_THREAD_STATE64_COUNT)\n";
9004 MachO::arm_thread_state64_t cpu64;
9005 left = end - begin;
9006 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9007 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9008 begin += sizeof(MachO::arm_thread_state64_t);
9009 } else {
9010 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9011 memcpy(&cpu64, begin, left);
9012 begin += left;
9013 }
9014 if (isLittleEndian != sys::IsLittleEndianHost)
9015 swapStruct(cpu64);
9016 Print_arm_thread_state64_t(cpu64);
9017 } else {
9018 outs() << " flavor " << flavor << " (unknown)\n";
9019 outs() << " count " << count << "\n";
9020 outs() << " state (unknown)\n";
9021 begin += count * sizeof(uint32_t);
9022 }
9023 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009024 } else {
9025 while (begin < end) {
9026 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9027 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9028 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009029 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009030 flavor = 0;
9031 begin = end;
9032 }
9033 if (isLittleEndian != sys::IsLittleEndianHost)
9034 sys::swapByteOrder(flavor);
9035 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9036 memcpy((char *)&count, begin, sizeof(uint32_t));
9037 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009038 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009039 count = 0;
9040 begin = end;
9041 }
9042 if (isLittleEndian != sys::IsLittleEndianHost)
9043 sys::swapByteOrder(count);
9044 outs() << " flavor " << flavor << "\n";
9045 outs() << " count " << count << "\n";
9046 outs() << " state (Unknown cputype/cpusubtype)\n";
9047 begin += count * sizeof(uint32_t);
9048 }
9049 }
9050}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009051
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009052static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9053 if (dl.cmd == MachO::LC_ID_DYLIB)
9054 outs() << " cmd LC_ID_DYLIB\n";
9055 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9056 outs() << " cmd LC_LOAD_DYLIB\n";
9057 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9058 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9059 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9060 outs() << " cmd LC_REEXPORT_DYLIB\n";
9061 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9062 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9063 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9064 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9065 else
9066 outs() << " cmd " << dl.cmd << " (unknown)\n";
9067 outs() << " cmdsize " << dl.cmdsize;
9068 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9069 outs() << " Incorrect size\n";
9070 else
9071 outs() << "\n";
9072 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009073 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009074 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9075 } else {
9076 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9077 }
9078 outs() << " time stamp " << dl.dylib.timestamp << " ";
9079 time_t t = dl.dylib.timestamp;
9080 outs() << ctime(&t);
9081 outs() << " current version ";
9082 if (dl.dylib.current_version == 0xffffffff)
9083 outs() << "n/a\n";
9084 else
9085 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9086 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9087 << (dl.dylib.current_version & 0xff) << "\n";
9088 outs() << "compatibility version ";
9089 if (dl.dylib.compatibility_version == 0xffffffff)
9090 outs() << "n/a\n";
9091 else
9092 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9093 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9094 << (dl.dylib.compatibility_version & 0xff) << "\n";
9095}
9096
9097static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9098 uint32_t object_size) {
9099 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009100 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009101 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9102 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9103 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9104 outs() << " cmd LC_FUNCTION_STARTS\n";
9105 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9106 outs() << " cmd LC_DATA_IN_CODE\n";
9107 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9108 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9109 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9110 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9111 else
9112 outs() << " cmd " << ld.cmd << " (?)\n";
9113 outs() << " cmdsize " << ld.cmdsize;
9114 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9115 outs() << " Incorrect size\n";
9116 else
9117 outs() << "\n";
9118 outs() << " dataoff " << ld.dataoff;
9119 if (ld.dataoff > object_size)
9120 outs() << " (past end of file)\n";
9121 else
9122 outs() << "\n";
9123 outs() << " datasize " << ld.datasize;
9124 uint64_t big_size = ld.dataoff;
9125 big_size += ld.datasize;
9126 if (big_size > object_size)
9127 outs() << " (past end of file)\n";
9128 else
9129 outs() << "\n";
9130}
9131
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009132static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9133 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009134 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009135 unsigned Index = 0;
9136 for (const auto &Command : Obj->load_commands()) {
9137 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009138 if (Command.C.cmd == MachO::LC_SEGMENT) {
9139 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9140 const char *sg_segname = SLC.segname;
9141 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9142 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9143 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9144 verbose);
9145 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009146 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009147 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9148 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9149 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9150 }
9151 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9152 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9153 const char *sg_segname = SLC_64.segname;
9154 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9155 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9156 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9157 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9158 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9159 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9160 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9161 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9162 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9163 sg_segname, filetype, Buf.size(), verbose);
9164 }
9165 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9166 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009167 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009168 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9169 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9170 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009171 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9172 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009173 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9174 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9175 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9176 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9177 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9178 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9179 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9180 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9181 PrintDyldLoadCommand(Dyld, Command.Ptr);
9182 } else if (Command.C.cmd == MachO::LC_UUID) {
9183 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9184 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009185 } else if (Command.C.cmd == MachO::LC_RPATH) {
9186 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9187 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009188 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009189 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9190 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9191 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009192 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9193 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009194 } else if (Command.C.cmd == MachO::LC_NOTE) {
9195 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9196 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009197 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9198 MachO::build_version_command Bv =
9199 Obj->getBuildVersionLoadCommand(Command);
9200 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009201 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9202 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9203 PrintSourceVersionCommand(Sd);
9204 } else if (Command.C.cmd == MachO::LC_MAIN) {
9205 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9206 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009207 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009208 MachO::encryption_info_command Ei =
9209 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009210 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009211 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009212 MachO::encryption_info_command_64 Ei =
9213 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009214 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009215 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009216 MachO::linker_option_command Lo =
9217 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009218 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009219 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9220 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9221 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009222 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9223 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9224 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009225 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9226 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9227 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009228 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9229 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9230 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009231 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9232 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9233 PrintRoutinesCommand(Rc);
9234 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9235 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9236 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009237 } else if (Command.C.cmd == MachO::LC_THREAD ||
9238 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9239 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9240 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009241 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9242 Command.C.cmd == MachO::LC_ID_DYLIB ||
9243 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9244 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9245 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9246 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009247 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9248 PrintDylibCommand(Dl, Command.Ptr);
9249 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9250 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9251 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9252 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9253 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9254 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9255 MachO::linkedit_data_command Ld =
9256 Obj->getLinkeditDataLoadCommand(Command);
9257 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009258 } else {
9259 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9260 << ")\n";
9261 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9262 // TODO: get and print the raw bytes of the load command.
9263 }
9264 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009265 }
9266}
9267
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009268static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009269 if (Obj->is64Bit()) {
9270 MachO::mach_header_64 H_64;
9271 H_64 = Obj->getHeader64();
9272 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9273 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9274 } else {
9275 MachO::mach_header H;
9276 H = Obj->getHeader();
9277 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9278 H.sizeofcmds, H.flags, verbose);
9279 }
9280}
9281
9282void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9283 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009284 PrintMachHeader(file, !NonVerbose);
9285}
9286
9287void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9288 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009289 uint32_t filetype = 0;
9290 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009291 if (file->is64Bit()) {
9292 MachO::mach_header_64 H_64;
9293 H_64 = file->getHeader64();
9294 filetype = H_64.filetype;
9295 cputype = H_64.cputype;
9296 } else {
9297 MachO::mach_header H;
9298 H = file->getHeader();
9299 filetype = H.filetype;
9300 cputype = H.cputype;
9301 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009302 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009303}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009304
9305//===----------------------------------------------------------------------===//
9306// export trie dumping
9307//===----------------------------------------------------------------------===//
9308
9309void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009310 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9311 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009312 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9313 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9314 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9315 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9316 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9317 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9318 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9319 if (ReExport)
9320 outs() << "[re-export] ";
9321 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009322 outs() << format("0x%08llX ",
9323 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009324 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009325 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009326 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009327 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009328 if (WeakDef) {
9329 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009330 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009331 }
9332 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009333 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009334 outs() << ", ";
9335 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009336 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009337 }
9338 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009339 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009340 outs() << ", ";
9341 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009342 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009343 }
9344 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009345 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009346 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009347 outs() << format("resolver=0x%08llX", Entry.other());
9348 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009349 }
9350 outs() << "]";
9351 }
9352 if (ReExport) {
9353 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009354 int Ordinal = Entry.other() - 1;
9355 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9356 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009357 outs() << " (from " << DylibName << ")";
9358 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009359 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009360 }
9361 outs() << "\n";
9362 }
9363}
Nick Kledzikac431442014-09-12 21:34:15 +00009364
Nick Kledzikac431442014-09-12 21:34:15 +00009365//===----------------------------------------------------------------------===//
9366// rebase table dumping
9367//===----------------------------------------------------------------------===//
9368
9369namespace {
9370class SegInfo {
9371public:
9372 SegInfo(const object::MachOObjectFile *Obj);
9373
9374 StringRef segmentName(uint32_t SegIndex);
9375 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9376 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009377 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00009378
9379private:
9380 struct SectionInfo {
9381 uint64_t Address;
9382 uint64_t Size;
9383 StringRef SectionName;
9384 StringRef SegmentName;
9385 uint64_t OffsetInSegment;
9386 uint64_t SegmentStartAddress;
9387 uint32_t SegmentIndex;
9388 };
9389 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9390 SmallVector<SectionInfo, 32> Sections;
9391};
9392}
9393
9394SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9395 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00009396 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00009397 StringRef CurSegName;
9398 uint64_t CurSegAddress;
9399 for (const SectionRef &Section : Obj->sections()) {
9400 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00009401 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00009402 Info.Address = Section.getAddress();
9403 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00009404 Info.SegmentName =
9405 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9406 if (!Info.SegmentName.equals(CurSegName)) {
9407 ++CurSegIndex;
9408 CurSegName = Info.SegmentName;
9409 CurSegAddress = Info.Address;
9410 }
9411 Info.SegmentIndex = CurSegIndex - 1;
9412 Info.OffsetInSegment = Info.Address - CurSegAddress;
9413 Info.SegmentStartAddress = CurSegAddress;
9414 Sections.push_back(Info);
9415 }
9416}
9417
9418StringRef SegInfo::segmentName(uint32_t SegIndex) {
9419 for (const SectionInfo &SI : Sections) {
9420 if (SI.SegmentIndex == SegIndex)
9421 return SI.SegmentName;
9422 }
9423 llvm_unreachable("invalid segIndex");
9424}
9425
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009426bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9427 uint64_t OffsetInSeg) {
9428 for (const SectionInfo &SI : Sections) {
9429 if (SI.SegmentIndex != SegIndex)
9430 continue;
9431 if (SI.OffsetInSegment > OffsetInSeg)
9432 continue;
9433 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9434 continue;
9435 return true;
9436 }
9437 return false;
9438}
9439
Nick Kledzikac431442014-09-12 21:34:15 +00009440const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9441 uint64_t OffsetInSeg) {
9442 for (const SectionInfo &SI : Sections) {
9443 if (SI.SegmentIndex != SegIndex)
9444 continue;
9445 if (SI.OffsetInSegment > OffsetInSeg)
9446 continue;
9447 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9448 continue;
9449 return SI;
9450 }
9451 llvm_unreachable("segIndex and offset not in any section");
9452}
9453
9454StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9455 return findSection(SegIndex, OffsetInSeg).SectionName;
9456}
9457
9458uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9459 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9460 return SI.SegmentStartAddress + OffsetInSeg;
9461}
9462
9463void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9464 // Build table of sections so names can used in final output.
9465 SegInfo sectionTable(Obj);
9466
9467 outs() << "segment section address type\n";
9468 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9469 uint32_t SegIndex = Entry.segmentIndex();
9470 uint64_t OffsetInSeg = Entry.segmentOffset();
9471 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9472 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9473 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9474
9475 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009476 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9477 SegmentName.str().c_str(), SectionName.str().c_str(),
9478 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009479 }
9480}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009481
9482static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9483 StringRef DylibName;
9484 switch (Ordinal) {
9485 case MachO::BIND_SPECIAL_DYLIB_SELF:
9486 return "this-image";
9487 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9488 return "main-executable";
9489 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9490 return "flat-namespace";
9491 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009492 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009493 std::error_code EC =
9494 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009495 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009496 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009497 return DylibName;
9498 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009499 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009500 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009501}
9502
9503//===----------------------------------------------------------------------===//
9504// bind table dumping
9505//===----------------------------------------------------------------------===//
9506
9507void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9508 // Build table of sections so names can used in final output.
9509 SegInfo sectionTable(Obj);
9510
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009511 outs() << "segment section address type "
9512 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009513 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9514 uint32_t SegIndex = Entry.segmentIndex();
9515 uint64_t OffsetInSeg = Entry.segmentOffset();
9516 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9517 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9518 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9519
9520 // Table lines look like:
9521 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009522 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009523 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009524 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009525 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009526 << left_justify(SectionName, 18) << " "
9527 << format_hex(Address, 10, true) << " "
9528 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009529 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009530 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009531 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009532 }
9533}
9534
9535//===----------------------------------------------------------------------===//
9536// lazy bind table dumping
9537//===----------------------------------------------------------------------===//
9538
9539void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9540 // Build table of sections so names can used in final output.
9541 SegInfo sectionTable(Obj);
9542
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009543 outs() << "segment section address "
9544 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009545 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9546 uint32_t SegIndex = Entry.segmentIndex();
9547 uint64_t OffsetInSeg = Entry.segmentOffset();
9548 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9549 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9550 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9551
9552 // Table lines look like:
9553 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009554 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009555 << left_justify(SectionName, 18) << " "
9556 << format_hex(Address, 10, true) << " "
9557 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009558 << Entry.symbolName() << "\n";
9559 }
9560}
9561
Nick Kledzik56ebef42014-09-16 01:41:51 +00009562//===----------------------------------------------------------------------===//
9563// weak bind table dumping
9564//===----------------------------------------------------------------------===//
9565
9566void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9567 // Build table of sections so names can used in final output.
9568 SegInfo sectionTable(Obj);
9569
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009570 outs() << "segment section address "
9571 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009572 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9573 // Strong symbols don't have a location to update.
9574 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009575 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009576 << Entry.symbolName() << "\n";
9577 continue;
9578 }
9579 uint32_t SegIndex = Entry.segmentIndex();
9580 uint64_t OffsetInSeg = Entry.segmentOffset();
9581 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9582 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9583 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9584
9585 // Table lines look like:
9586 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009587 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009588 << left_justify(SectionName, 18) << " "
9589 << format_hex(Address, 10, true) << " "
9590 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009591 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9592 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009593 }
9594}
9595
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009596// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9597// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9598// information for that address. If the address is found its binding symbol
9599// name is returned. If not nullptr is returned.
9600static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9601 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009602 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009603 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009604 SegInfo sectionTable(info->O);
9605 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9606 uint32_t SegIndex = Entry.segmentIndex();
9607 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009608 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
Kevin Enderby6de201e2017-02-03 18:22:04 +00009609 return nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009610 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009611 StringRef name = Entry.symbolName();
9612 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009613 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009614 }
9615 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009616 auto name = info->bindtable->lookup(ReferenceValue);
9617 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009618}