blob: 031427cf4d91bb689c0f397d5da93c421bc8f13c [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
14#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000015#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000016#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000017#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000019#include "llvm/BinaryFormat/MachO.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"
Zachary Turner264b5d92017-06-07 03:48:56 +000033#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000034#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000035#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000038#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000042#include "llvm/Support/LEB128.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 Enderbyf9d60f02016-11-29 21:43:40 +000071static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
72 cl::desc("Print no leading headers"));
73
Kevin Enderby13023a12015-01-15 23:19:11 +000074cl::opt<bool> llvm::UniversalHeaders("universal-headers",
75 cl::desc("Print Mach-O universal headers "
76 "(requires -macho)"));
77
Kevin Enderby131d1772015-01-09 19:22:37 +000078cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000079 llvm::ArchiveHeaders("archive-headers",
80 cl::desc("Print archive headers for Mach-O archives "
81 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000082
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000083cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000084 ArchiveMemberOffsets("archive-member-offsets",
85 cl::desc("Print the offset to each archive member for "
86 "Mach-O archives (requires -macho and "
87 "-archive-headers)"));
88
89cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000090 llvm::IndirectSymbols("indirect-symbols",
91 cl::desc("Print indirect symbol table for Mach-O "
92 "objects (requires -macho)"));
93
Kevin Enderby69fe98d2015-01-23 18:52:17 +000094cl::opt<bool>
95 llvm::DataInCode("data-in-code",
96 cl::desc("Print the data in code table for Mach-O objects "
97 "(requires -macho)"));
98
Kevin Enderby9a509442015-01-27 21:28:24 +000099cl::opt<bool>
100 llvm::LinkOptHints("link-opt-hints",
101 cl::desc("Print the linker optimization hints for "
102 "Mach-O objects (requires -macho)"));
103
Kevin Enderbycd66be52015-03-11 22:06:32 +0000104cl::opt<bool>
105 llvm::InfoPlist("info-plist",
106 cl::desc("Print the info plist section as strings for "
107 "Mach-O objects (requires -macho)"));
108
Kevin Enderbyf0640752015-03-13 17:56:32 +0000109cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000110 llvm::DylibsUsed("dylibs-used",
111 cl::desc("Print the shared libraries used for linked "
112 "Mach-O files (requires -macho)"));
113
114cl::opt<bool>
115 llvm::DylibId("dylib-id",
116 cl::desc("Print the shared library's id for the dylib Mach-O "
117 "file (requires -macho)"));
118
119cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000120 llvm::NonVerbose("non-verbose",
121 cl::desc("Print the info for Mach-O objects in "
122 "non-verbose or numeric form (requires -macho)"));
123
Kevin Enderby0fc11822015-04-01 20:57:01 +0000124cl::opt<bool>
125 llvm::ObjcMetaData("objc-meta-data",
126 cl::desc("Print the Objective-C runtime meta data for "
127 "Mach-O files (requires -macho)"));
128
Kevin Enderby6a221752015-03-17 17:10:57 +0000129cl::opt<std::string> llvm::DisSymName(
130 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000131 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000132
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000133static cl::opt<bool> NoSymbolicOperands(
134 "no-symbolic-operands",
135 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
136
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137static cl::list<std::string>
138 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
139 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000140
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000141bool ArchAll = false;
142
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000143static std::string ThumbTripleName;
144
145static const Target *GetTarget(const MachOObjectFile *MachOObj,
146 const char **McpuDefault,
147 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000148 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000149 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000150 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000151 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000152 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000153 }
154
155 if (TT.getArch() == Triple::arm) {
156 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
157 // that support ARM are also capable of Thumb mode.
158 llvm::Triple ThumbTriple = TT;
159 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
160 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000161 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000162 }
163
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000164 // Get the target specific parser.
165 std::string Error;
166 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000167 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000168 return TheTarget;
169
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
171 if (*ThumbTarget)
172 return TheTarget;
173
174 errs() << "llvm-objdump: error: unable to get target for '";
175 if (!TheTarget)
176 errs() << TripleName;
177 else
178 errs() << ThumbTripleName;
179 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000180 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000181}
182
Owen Andersond9243c42011-10-17 21:37:35 +0000183struct SymbolSorter {
184 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000185 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000186 if (!ATypeOrErr)
187 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000188 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000189 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000190 if (!BTypeOrErr)
191 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000192 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000193 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
194 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000195 return AAddr < BAddr;
196 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000197};
198
Kevin Enderby273ae012013-06-06 17:20:50 +0000199// Types for the storted data in code table that is built before disassembly
200// and the predicate function to sort them.
201typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
202typedef std::vector<DiceTableEntry> DiceTable;
203typedef DiceTable::iterator dice_table_iterator;
204
Francis Ricci6f942972017-10-06 15:33:28 +0000205namespace {
206struct ScopedXarFile {
207 xar_t xar;
208 ScopedXarFile(const char *filename, int32_t flags) {
209 xar = xar_open(filename, flags);
210 }
211 ~ScopedXarFile() {
212 if (xar)
213 xar_close(xar);
214 }
215 ScopedXarFile(const ScopedXarFile &) = delete;
216 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
217 operator xar_t() { return xar; }
218};
219
220struct ScopedXarIter {
221 xar_iter_t iter;
222 ScopedXarIter() { iter = xar_iter_new(); }
223 ~ScopedXarIter() {
224 if (iter)
225 xar_iter_free(iter);
226 }
227 ScopedXarIter(const ScopedXarIter &) = delete;
228 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
229 operator xar_iter_t() { return iter; }
230};
231} // namespace
232
Kevin Enderby930fdc72014-11-06 19:00:13 +0000233// This is used to search for a data in code table entry for the PC being
234// disassembled. The j parameter has the PC in j.first. A single data in code
235// table entry can cover many bytes for each of its Kind's. So if the offset,
236// aka the i.first value, of the data in code table entry plus its Length
237// covers the PC being searched for this will return true. If not it will
238// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000239static bool compareDiceTableEntries(const DiceTableEntry &i,
240 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000241 uint16_t Length;
242 i.second.getLength(Length);
243
244 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000245}
246
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000247static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 unsigned short Kind) {
249 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000250
251 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000252 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000253 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000254 if (Length >= 4) {
255 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000256 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000257 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000258 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000259 Size = 4;
260 } else if (Length >= 2) {
261 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 Enderby273ae012013-06-06 17:20:50 +0000264 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000265 Size = 2;
266 } else {
267 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000268 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000269 Value = bytes[0];
270 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000271 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000272 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000273 if (Kind == MachO::DICE_KIND_DATA)
274 outs() << "\t@ KIND_DATA\n";
275 else
276 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000277 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000278 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000279 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000280 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000281 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000282 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
283 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000284 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000285 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000286 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000287 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000288 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000289 outs() << "\t.short " << format("%5u", Value & 0xffff)
290 << "\t@ KIND_JUMP_TABLE16\n";
291 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000292 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000293 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000294 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
295 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000296 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000297 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000298 outs() << "\t.long " << Value;
299 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
300 outs() << "\t@ KIND_JUMP_TABLE32\n";
301 else
302 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
303 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000304 break;
305 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000306 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000307}
308
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000309static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000310 std::vector<SectionRef> &Sections,
311 std::vector<SymbolRef> &Symbols,
312 SmallVectorImpl<uint64_t> &FoundFns,
313 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000314 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000315 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000316 if (!SymName)
317 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000318 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000319 Symbols.push_back(Symbol);
320 }
Owen Andersond9243c42011-10-17 21:37:35 +0000321
Alexey Samsonov48803e52014-03-13 14:37:36 +0000322 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000323 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000324 Section.getName(SectName);
325 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000326 }
327
Kevin Enderby273ae012013-06-06 17:20:50 +0000328 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000329 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000330 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000331 // We found a function starts segment, parse the addresses for later
332 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000333 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000334 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000335
Charles Davis8bdfafd2013-09-01 04:28:48 +0000336 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000337 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
338 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000339 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000340 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000341 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000342 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000343 }
344 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000345 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000346}
347
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000348static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
349 uint32_t n, uint32_t count,
350 uint32_t stride, uint64_t addr) {
351 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
352 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
353 if (n > nindirectsyms)
354 outs() << " (entries start past the end of the indirect symbol "
355 "table) (reserved1 field greater than the table size)";
356 else if (n + count > nindirectsyms)
357 outs() << " (entries extends past the end of the indirect symbol "
358 "table)";
359 outs() << "\n";
360 uint32_t cputype = O->getHeader().cputype;
361 if (cputype & MachO::CPU_ARCH_ABI64)
362 outs() << "address index";
363 else
364 outs() << "address index";
365 if (verbose)
366 outs() << " name\n";
367 else
368 outs() << "\n";
369 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
370 if (cputype & MachO::CPU_ARCH_ABI64)
371 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
372 else
Tim Northover43978372016-04-26 18:29:16 +0000373 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000374 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
375 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
376 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
377 outs() << "LOCAL\n";
378 continue;
379 }
380 if (indirect_symbol ==
381 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
382 outs() << "LOCAL ABSOLUTE\n";
383 continue;
384 }
385 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
386 outs() << "ABSOLUTE\n";
387 continue;
388 }
389 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000390 if (verbose) {
391 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
392 if (indirect_symbol < Symtab.nsyms) {
393 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
394 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000395 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000396 if (!SymName)
397 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000398 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000399 } else {
400 outs() << "?";
401 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000402 }
403 outs() << "\n";
404 }
405}
406
407static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000408 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000409 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
410 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
411 for (unsigned J = 0; J < Seg.nsects; ++J) {
412 MachO::section_64 Sec = O->getSection64(Load, J);
413 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
414 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
415 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
416 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
417 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
418 section_type == MachO::S_SYMBOL_STUBS) {
419 uint32_t stride;
420 if (section_type == MachO::S_SYMBOL_STUBS)
421 stride = Sec.reserved2;
422 else
423 stride = 8;
424 if (stride == 0) {
425 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
426 << Sec.sectname << ") "
427 << "(size of stubs in reserved2 field is zero)\n";
428 continue;
429 }
430 uint32_t count = Sec.size / stride;
431 outs() << "Indirect symbols for (" << Sec.segname << ","
432 << Sec.sectname << ") " << count << " entries";
433 uint32_t n = Sec.reserved1;
434 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
435 }
436 }
437 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
438 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
439 for (unsigned J = 0; J < Seg.nsects; ++J) {
440 MachO::section Sec = O->getSection(Load, J);
441 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
442 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
443 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
444 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
445 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
446 section_type == MachO::S_SYMBOL_STUBS) {
447 uint32_t stride;
448 if (section_type == MachO::S_SYMBOL_STUBS)
449 stride = Sec.reserved2;
450 else
451 stride = 4;
452 if (stride == 0) {
453 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
454 << Sec.sectname << ") "
455 << "(size of stubs in reserved2 field is zero)\n";
456 continue;
457 }
458 uint32_t count = Sec.size / stride;
459 outs() << "Indirect symbols for (" << Sec.segname << ","
460 << Sec.sectname << ") " << count << " entries";
461 uint32_t n = Sec.reserved1;
462 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
463 }
464 }
465 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000466 }
467}
468
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000469static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
470 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
471 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
472 outs() << "Data in code table (" << nentries << " entries)\n";
473 outs() << "offset length kind\n";
474 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
475 ++DI) {
476 uint32_t Offset;
477 DI->getOffset(Offset);
478 outs() << format("0x%08" PRIx32, Offset) << " ";
479 uint16_t Length;
480 DI->getLength(Length);
481 outs() << format("%6u", Length) << " ";
482 uint16_t Kind;
483 DI->getKind(Kind);
484 if (verbose) {
485 switch (Kind) {
486 case MachO::DICE_KIND_DATA:
487 outs() << "DATA";
488 break;
489 case MachO::DICE_KIND_JUMP_TABLE8:
490 outs() << "JUMP_TABLE8";
491 break;
492 case MachO::DICE_KIND_JUMP_TABLE16:
493 outs() << "JUMP_TABLE16";
494 break;
495 case MachO::DICE_KIND_JUMP_TABLE32:
496 outs() << "JUMP_TABLE32";
497 break;
498 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
499 outs() << "ABS_JUMP_TABLE32";
500 break;
501 default:
502 outs() << format("0x%04" PRIx32, Kind);
503 break;
504 }
505 } else
506 outs() << format("0x%04" PRIx32, Kind);
507 outs() << "\n";
508 }
509}
510
Kevin Enderby9a509442015-01-27 21:28:24 +0000511static void PrintLinkOptHints(MachOObjectFile *O) {
512 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
513 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
514 uint32_t nloh = LohLC.datasize;
515 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
516 for (uint32_t i = 0; i < nloh;) {
517 unsigned n;
518 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
519 i += n;
520 outs() << " identifier " << identifier << " ";
521 if (i >= nloh)
522 return;
523 switch (identifier) {
524 case 1:
525 outs() << "AdrpAdrp\n";
526 break;
527 case 2:
528 outs() << "AdrpLdr\n";
529 break;
530 case 3:
531 outs() << "AdrpAddLdr\n";
532 break;
533 case 4:
534 outs() << "AdrpLdrGotLdr\n";
535 break;
536 case 5:
537 outs() << "AdrpAddStr\n";
538 break;
539 case 6:
540 outs() << "AdrpLdrGotStr\n";
541 break;
542 case 7:
543 outs() << "AdrpAdd\n";
544 break;
545 case 8:
546 outs() << "AdrpLdrGot\n";
547 break;
548 default:
549 outs() << "Unknown identifier value\n";
550 break;
551 }
552 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
553 i += n;
554 outs() << " narguments " << narguments << "\n";
555 if (i >= nloh)
556 return;
557
558 for (uint32_t j = 0; j < narguments; j++) {
559 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
560 i += n;
561 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
562 if (i >= nloh)
563 return;
564 }
565 }
566}
567
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000568static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000569 unsigned Index = 0;
570 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000571 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
572 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
573 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
574 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
575 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
576 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
577 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
578 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
579 if (dl.dylib.name < dl.cmdsize) {
580 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
581 if (JustId)
582 outs() << p << "\n";
583 else {
584 outs() << "\t" << p;
585 outs() << " (compatibility version "
586 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
587 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
588 << (dl.dylib.compatibility_version & 0xff) << ",";
589 outs() << " current version "
590 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
591 << ((dl.dylib.current_version >> 8) & 0xff) << "."
592 << (dl.dylib.current_version & 0xff) << ")\n";
593 }
594 } else {
595 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
596 if (Load.C.cmd == MachO::LC_ID_DYLIB)
597 outs() << "LC_ID_DYLIB ";
598 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
599 outs() << "LC_LOAD_DYLIB ";
600 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
601 outs() << "LC_LOAD_WEAK_DYLIB ";
602 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
603 outs() << "LC_LAZY_LOAD_DYLIB ";
604 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
605 outs() << "LC_REEXPORT_DYLIB ";
606 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
607 outs() << "LC_LOAD_UPWARD_DYLIB ";
608 else
609 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000610 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000611 }
612 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000613 }
614}
615
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000616typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
617
618static void CreateSymbolAddressMap(MachOObjectFile *O,
619 SymbolAddressMap *AddrMap) {
620 // Create a map of symbol addresses to symbol names.
621 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000622 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000623 if (!STOrErr)
624 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000625 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000626 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
627 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000628 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000629 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000630 if (!SymNameOrErr)
631 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000632 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000633 if (!SymName.startswith(".objc"))
634 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000635 }
636 }
637}
638
639// GuessSymbolName is passed the address of what might be a symbol and a
640// pointer to the SymbolAddressMap. It returns the name of a symbol
641// with that address or nullptr if no symbol is found with that address.
642static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
643 const char *SymbolName = nullptr;
644 // A DenseMap can't lookup up some values.
645 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
646 StringRef name = AddrMap->lookup(value);
647 if (!name.empty())
648 SymbolName = name.data();
649 }
650 return SymbolName;
651}
652
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000653static void DumpCstringChar(const char c) {
654 char p[2];
655 p[0] = c;
656 p[1] = '\0';
657 outs().write_escaped(p);
658}
659
Kevin Enderby10ba0412015-02-04 21:38:42 +0000660static void DumpCstringSection(MachOObjectFile *O, const char *sect,
661 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000662 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000663 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000664 if (print_addresses) {
665 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000666 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000667 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000668 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000669 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000670 for (; i < sect_size && sect[i] != '\0'; i++)
671 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000672 if (i < sect_size && sect[i] == '\0')
673 outs() << "\n";
674 }
675}
676
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000677static void DumpLiteral4(uint32_t l, float f) {
678 outs() << format("0x%08" PRIx32, l);
679 if ((l & 0x7f800000) != 0x7f800000)
680 outs() << format(" (%.16e)\n", f);
681 else {
682 if (l == 0x7f800000)
683 outs() << " (+Infinity)\n";
684 else if (l == 0xff800000)
685 outs() << " (-Infinity)\n";
686 else if ((l & 0x00400000) == 0x00400000)
687 outs() << " (non-signaling Not-a-Number)\n";
688 else
689 outs() << " (signaling Not-a-Number)\n";
690 }
691}
692
693static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
694 uint32_t sect_size, uint64_t sect_addr,
695 bool print_addresses) {
696 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
697 if (print_addresses) {
698 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000699 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000700 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000701 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000702 }
703 float f;
704 memcpy(&f, sect + i, sizeof(float));
705 if (O->isLittleEndian() != sys::IsLittleEndianHost)
706 sys::swapByteOrder(f);
707 uint32_t l;
708 memcpy(&l, sect + i, sizeof(uint32_t));
709 if (O->isLittleEndian() != sys::IsLittleEndianHost)
710 sys::swapByteOrder(l);
711 DumpLiteral4(l, f);
712 }
713}
714
715static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
716 double d) {
717 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
718 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000719 Hi = (O->isLittleEndian()) ? l1 : l0;
720 Lo = (O->isLittleEndian()) ? l0 : l1;
721
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000722 // Hi is the high word, so this is equivalent to if(isfinite(d))
723 if ((Hi & 0x7ff00000) != 0x7ff00000)
724 outs() << format(" (%.16e)\n", d);
725 else {
726 if (Hi == 0x7ff00000 && Lo == 0)
727 outs() << " (+Infinity)\n";
728 else if (Hi == 0xfff00000 && Lo == 0)
729 outs() << " (-Infinity)\n";
730 else if ((Hi & 0x00080000) == 0x00080000)
731 outs() << " (non-signaling Not-a-Number)\n";
732 else
733 outs() << " (signaling Not-a-Number)\n";
734 }
735}
736
737static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
738 uint32_t sect_size, uint64_t sect_addr,
739 bool print_addresses) {
740 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
741 if (print_addresses) {
742 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000743 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000744 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000745 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000746 }
747 double d;
748 memcpy(&d, sect + i, sizeof(double));
749 if (O->isLittleEndian() != sys::IsLittleEndianHost)
750 sys::swapByteOrder(d);
751 uint32_t l0, l1;
752 memcpy(&l0, sect + i, sizeof(uint32_t));
753 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
754 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
755 sys::swapByteOrder(l0);
756 sys::swapByteOrder(l1);
757 }
758 DumpLiteral8(O, l0, l1, d);
759 }
760}
761
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000762static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
763 outs() << format("0x%08" PRIx32, l0) << " ";
764 outs() << format("0x%08" PRIx32, l1) << " ";
765 outs() << format("0x%08" PRIx32, l2) << " ";
766 outs() << format("0x%08" PRIx32, l3) << "\n";
767}
768
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000769static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
770 uint32_t sect_size, uint64_t sect_addr,
771 bool print_addresses) {
772 for (uint32_t i = 0; i < sect_size; i += 16) {
773 if (print_addresses) {
774 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000775 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000776 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000777 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000778 }
779 uint32_t l0, l1, l2, l3;
780 memcpy(&l0, sect + i, sizeof(uint32_t));
781 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
782 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
783 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
784 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
785 sys::swapByteOrder(l0);
786 sys::swapByteOrder(l1);
787 sys::swapByteOrder(l2);
788 sys::swapByteOrder(l3);
789 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000790 DumpLiteral16(l0, l1, l2, l3);
791 }
792}
793
794static void DumpLiteralPointerSection(MachOObjectFile *O,
795 const SectionRef &Section,
796 const char *sect, uint32_t sect_size,
797 uint64_t sect_addr,
798 bool print_addresses) {
799 // Collect the literal sections in this Mach-O file.
800 std::vector<SectionRef> LiteralSections;
801 for (const SectionRef &Section : O->sections()) {
802 DataRefImpl Ref = Section.getRawDataRefImpl();
803 uint32_t section_type;
804 if (O->is64Bit()) {
805 const MachO::section_64 Sec = O->getSection64(Ref);
806 section_type = Sec.flags & MachO::SECTION_TYPE;
807 } else {
808 const MachO::section Sec = O->getSection(Ref);
809 section_type = Sec.flags & MachO::SECTION_TYPE;
810 }
811 if (section_type == MachO::S_CSTRING_LITERALS ||
812 section_type == MachO::S_4BYTE_LITERALS ||
813 section_type == MachO::S_8BYTE_LITERALS ||
814 section_type == MachO::S_16BYTE_LITERALS)
815 LiteralSections.push_back(Section);
816 }
817
818 // Set the size of the literal pointer.
819 uint32_t lp_size = O->is64Bit() ? 8 : 4;
820
Eric Christopher572e03a2015-06-19 01:53:21 +0000821 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000822 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
823 for (const RelocationRef &Reloc : Section.relocations()) {
824 DataRefImpl Rel;
825 MachO::any_relocation_info RE;
826 bool isExtern = false;
827 Rel = Reloc.getRawDataRefImpl();
828 RE = O->getRelocation(Rel);
829 isExtern = O->getPlainRelocationExternal(RE);
830 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000831 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000832 symbol_iterator RelocSym = Reloc.getSymbol();
833 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
834 }
835 }
836 array_pod_sort(Relocs.begin(), Relocs.end());
837
838 // Dump each literal pointer.
839 for (uint32_t i = 0; i < sect_size; i += lp_size) {
840 if (print_addresses) {
841 if (O->is64Bit())
842 outs() << format("%016" PRIx64, sect_addr + i) << " ";
843 else
844 outs() << format("%08" PRIx64, sect_addr + i) << " ";
845 }
846 uint64_t lp;
847 if (O->is64Bit()) {
848 memcpy(&lp, sect + i, sizeof(uint64_t));
849 if (O->isLittleEndian() != sys::IsLittleEndianHost)
850 sys::swapByteOrder(lp);
851 } else {
852 uint32_t li;
853 memcpy(&li, sect + i, sizeof(uint32_t));
854 if (O->isLittleEndian() != sys::IsLittleEndianHost)
855 sys::swapByteOrder(li);
856 lp = li;
857 }
858
859 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +0000860 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
861 return P.first == i;
862 });
David Blaikie33dd45d02015-03-23 18:39:02 +0000863 if (Reloc != Relocs.end()) {
864 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000865 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000866 if (!SymName)
867 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000868 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000869 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000870 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000871
872 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +0000873 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
874 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
875 });
David Blaikie33dd45d02015-03-23 18:39:02 +0000876 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000877 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000878 continue;
879 }
880
881 uint64_t SectAddress = Sect->getAddress();
882 uint64_t SectSize = Sect->getSize();
883
884 StringRef SectName;
885 Sect->getName(SectName);
886 DataRefImpl Ref = Sect->getRawDataRefImpl();
887 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
888 outs() << SegmentName << ":" << SectName << ":";
889
890 uint32_t section_type;
891 if (O->is64Bit()) {
892 const MachO::section_64 Sec = O->getSection64(Ref);
893 section_type = Sec.flags & MachO::SECTION_TYPE;
894 } else {
895 const MachO::section Sec = O->getSection(Ref);
896 section_type = Sec.flags & MachO::SECTION_TYPE;
897 }
898
899 StringRef BytesStr;
900 Sect->getContents(BytesStr);
901 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
902
903 switch (section_type) {
904 case MachO::S_CSTRING_LITERALS:
905 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
906 i++) {
907 DumpCstringChar(Contents[i]);
908 }
909 outs() << "\n";
910 break;
911 case MachO::S_4BYTE_LITERALS:
912 float f;
913 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
914 uint32_t l;
915 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
916 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
917 sys::swapByteOrder(f);
918 sys::swapByteOrder(l);
919 }
920 DumpLiteral4(l, f);
921 break;
922 case MachO::S_8BYTE_LITERALS: {
923 double d;
924 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
925 uint32_t l0, l1;
926 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
927 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
928 sizeof(uint32_t));
929 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
930 sys::swapByteOrder(f);
931 sys::swapByteOrder(l0);
932 sys::swapByteOrder(l1);
933 }
934 DumpLiteral8(O, l0, l1, d);
935 break;
936 }
937 case MachO::S_16BYTE_LITERALS: {
938 uint32_t l0, l1, l2, l3;
939 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
940 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
941 sizeof(uint32_t));
942 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
943 sizeof(uint32_t));
944 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
945 sizeof(uint32_t));
946 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
947 sys::swapByteOrder(l0);
948 sys::swapByteOrder(l1);
949 sys::swapByteOrder(l2);
950 sys::swapByteOrder(l3);
951 }
952 DumpLiteral16(l0, l1, l2, l3);
953 break;
954 }
955 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000956 }
957}
958
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000959static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
960 uint32_t sect_size, uint64_t sect_addr,
961 SymbolAddressMap *AddrMap,
962 bool verbose) {
963 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000964 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000965 for (uint32_t i = 0; i < sect_size; i += stride) {
966 const char *SymbolName = nullptr;
967 if (O->is64Bit()) {
968 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
969 uint64_t pointer_value;
970 memcpy(&pointer_value, sect + i, stride);
971 if (O->isLittleEndian() != sys::IsLittleEndianHost)
972 sys::swapByteOrder(pointer_value);
973 outs() << format("0x%016" PRIx64, pointer_value);
974 if (verbose)
975 SymbolName = GuessSymbolName(pointer_value, AddrMap);
976 } else {
977 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
978 uint32_t pointer_value;
979 memcpy(&pointer_value, sect + i, stride);
980 if (O->isLittleEndian() != sys::IsLittleEndianHost)
981 sys::swapByteOrder(pointer_value);
982 outs() << format("0x%08" PRIx32, pointer_value);
983 if (verbose)
984 SymbolName = GuessSymbolName(pointer_value, AddrMap);
985 }
986 if (SymbolName)
987 outs() << " " << SymbolName;
988 outs() << "\n";
989 }
990}
991
992static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
993 uint32_t size, uint64_t addr) {
994 uint32_t cputype = O->getHeader().cputype;
995 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
996 uint32_t j;
997 for (uint32_t i = 0; i < size; i += j, addr += j) {
998 if (O->is64Bit())
999 outs() << format("%016" PRIx64, addr) << "\t";
1000 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001001 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001002 for (j = 0; j < 16 && i + j < size; j++) {
1003 uint8_t byte_word = *(sect + i + j);
1004 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1005 }
1006 outs() << "\n";
1007 }
1008 } else {
1009 uint32_t j;
1010 for (uint32_t i = 0; i < size; i += j, addr += j) {
1011 if (O->is64Bit())
1012 outs() << format("%016" PRIx64, addr) << "\t";
1013 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001014 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001015 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1016 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001017 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001018 uint32_t long_word;
1019 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1020 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1021 sys::swapByteOrder(long_word);
1022 outs() << format("%08" PRIx32, long_word) << " ";
1023 } else {
1024 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001025 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001026 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1027 }
1028 }
1029 }
1030 outs() << "\n";
1031 }
1032 }
1033}
1034
Kevin Enderby95df54c2015-02-04 01:01:38 +00001035static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1036 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001037static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1038 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001039#ifdef HAVE_LIBXAR
1040static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1041 uint32_t size, bool verbose,
1042 bool PrintXarHeader, bool PrintXarFileHeaders,
1043 std::string XarMemberName);
1044#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001045
1046static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1047 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001048 SymbolAddressMap AddrMap;
1049 if (verbose)
1050 CreateSymbolAddressMap(O, &AddrMap);
1051
Colin LeMahieufcc32762015-07-29 19:08:10 +00001052 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1053 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001054 std::pair<StringRef, StringRef> DumpSegSectName;
1055 DumpSegSectName = DumpSection.split(',');
1056 StringRef DumpSegName, DumpSectName;
1057 if (DumpSegSectName.second.size()) {
1058 DumpSegName = DumpSegSectName.first;
1059 DumpSectName = DumpSegSectName.second;
1060 } else {
1061 DumpSegName = "";
1062 DumpSectName = DumpSegSectName.first;
1063 }
1064 for (const SectionRef &Section : O->sections()) {
1065 StringRef SectName;
1066 Section.getName(SectName);
1067 DataRefImpl Ref = Section.getRawDataRefImpl();
1068 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1069 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1070 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001071
Kevin Enderby95df54c2015-02-04 01:01:38 +00001072 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001073 if (O->is64Bit()) {
1074 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001075 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001076
1077 } else {
1078 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001079 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001080 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001081 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001082
1083 StringRef BytesStr;
1084 Section.getContents(BytesStr);
1085 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1086 uint32_t sect_size = BytesStr.size();
1087 uint64_t sect_addr = Section.getAddress();
1088
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001089 outs() << "Contents of (" << SegName << "," << SectName
1090 << ") section\n";
1091
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001092 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001093 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1094 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1095 DisassembleMachO(Filename, O, SegName, SectName);
1096 continue;
1097 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001098 if (SegName == "__TEXT" && SectName == "__info_plist") {
1099 outs() << sect;
1100 continue;
1101 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001102 if (SegName == "__OBJC" && SectName == "__protocol") {
1103 DumpProtocolSection(O, sect, sect_size, sect_addr);
1104 continue;
1105 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001106#ifdef HAVE_LIBXAR
1107 if (SegName == "__LLVM" && SectName == "__bundle") {
1108 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1109 ArchiveHeaders, "");
1110 continue;
1111 }
1112#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001113 switch (section_type) {
1114 case MachO::S_REGULAR:
1115 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1116 break;
1117 case MachO::S_ZEROFILL:
1118 outs() << "zerofill section and has no contents in the file\n";
1119 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001120 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001121 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001122 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001123 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001124 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001125 break;
1126 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001127 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001128 break;
1129 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001130 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1131 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001132 case MachO::S_LITERAL_POINTERS:
1133 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001134 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001135 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001136 case MachO::S_MOD_INIT_FUNC_POINTERS:
1137 case MachO::S_MOD_TERM_FUNC_POINTERS:
1138 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1139 verbose);
1140 break;
1141 default:
1142 outs() << "Unknown section type ("
1143 << format("0x%08" PRIx32, section_type) << ")\n";
1144 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1145 break;
1146 }
1147 } else {
1148 if (section_type == MachO::S_ZEROFILL)
1149 outs() << "zerofill section and has no contents in the file\n";
1150 else
1151 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1152 }
1153 }
1154 }
1155 }
1156}
1157
Kevin Enderbycd66be52015-03-11 22:06:32 +00001158static void DumpInfoPlistSectionContents(StringRef Filename,
1159 MachOObjectFile *O) {
1160 for (const SectionRef &Section : O->sections()) {
1161 StringRef SectName;
1162 Section.getName(SectName);
1163 DataRefImpl Ref = Section.getRawDataRefImpl();
1164 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1165 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001166 if (!NoLeadingHeaders)
1167 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001168 StringRef BytesStr;
1169 Section.getContents(BytesStr);
1170 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001171 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001172 return;
1173 }
1174 }
1175}
1176
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001177// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1178// and if it is and there is a list of architecture flags is specified then
1179// check to make sure this Mach-O file is one of those architectures or all
1180// architectures were specified. If not then an error is generated and this
1181// routine returns false. Else it returns true.
1182static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001183 auto *MachO = dyn_cast<MachOObjectFile>(O);
1184
1185 if (!MachO || ArchAll || ArchFlags.empty())
1186 return true;
1187
1188 MachO::mach_header H;
1189 MachO::mach_header_64 H_64;
1190 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001191 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001192 if (MachO->is64Bit()) {
1193 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001194 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1195 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001196 } else {
1197 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001198 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1199 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001200 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001201 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001202 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001203 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001204 })) {
1205 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1206 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001207 }
1208 return true;
1209}
1210
Kevin Enderby0fc11822015-04-01 20:57:01 +00001211static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1212
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001213// ProcessMachO() is passed a single opened Mach-O file, which may be an
1214// archive member and or in a slice of a universal file. It prints the
1215// the file name and header info and then processes it according to the
1216// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001217static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001218 StringRef ArchiveMemberName = StringRef(),
1219 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001220 // If we are doing some processing here on the Mach-O file print the header
1221 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001222 // UniversalHeaders or ArchiveHeaders.
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001223 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001224 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001225 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001226 if (!NoLeadingHeaders) {
1227 outs() << Name;
1228 if (!ArchiveMemberName.empty())
1229 outs() << '(' << ArchiveMemberName << ')';
1230 if (!ArchitectureName.empty())
1231 outs() << " (architecture " << ArchitectureName << ")";
1232 outs() << ":\n";
1233 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001234 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001235 // To use the report_error() form with an ArchiveName and FileName set
1236 // these up based on what is passed for Name and ArchiveMemberName.
1237 StringRef ArchiveName;
1238 StringRef FileName;
1239 if (!ArchiveMemberName.empty()) {
1240 ArchiveName = Name;
1241 FileName = ArchiveMemberName;
1242 } else {
1243 ArchiveName = StringRef();
1244 FileName = Name;
1245 }
1246
1247 // If we need the symbol table to do the operation then check it here to
1248 // produce a good error message as to where the Mach-O file comes from in
1249 // the error message.
1250 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1251 UnwindInfo)
1252 if (Error Err = MachOOF->checkSymbolTable())
1253 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001254
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001255 if (Disassemble) {
1256 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001257 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001258 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1259 else
1260 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1261 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001262 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001263 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001264 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001265 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001266 if (LinkOptHints)
1267 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001268 if (Relocations)
1269 PrintRelocations(MachOOF);
1270 if (SectionHeaders)
1271 PrintSectionHeaders(MachOOF);
1272 if (SectionContents)
1273 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001274 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001275 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001276 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001277 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001278 if (DylibsUsed)
1279 PrintDylibs(MachOOF, false);
1280 if (DylibId)
1281 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001282 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001283 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001284 if (UnwindInfo)
1285 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001286 if (PrivateHeaders) {
1287 printMachOFileHeader(MachOOF);
1288 printMachOLoadCommands(MachOOF);
1289 }
1290 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001291 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001292 if (ObjcMetaData)
1293 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001294 if (ExportsTrie)
1295 printExportsTrie(MachOOF);
1296 if (Rebase)
1297 printRebaseTable(MachOOF);
1298 if (Bind)
1299 printBindTable(MachOOF);
1300 if (LazyBind)
1301 printLazyBindTable(MachOOF);
1302 if (WeakBind)
1303 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001304
1305 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001306 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001307 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001308 DIDumpOptions DumpOpts;
1309 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001310 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001311 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001312}
1313
Kevin Enderby131d1772015-01-09 19:22:37 +00001314// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1315static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1316 outs() << " cputype (" << cputype << ")\n";
1317 outs() << " cpusubtype (" << cpusubtype << ")\n";
1318}
1319
1320// printCPUType() helps print_fat_headers by printing the cputype and
1321// pusubtype (symbolically for the one's it knows about).
1322static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1323 switch (cputype) {
1324 case MachO::CPU_TYPE_I386:
1325 switch (cpusubtype) {
1326 case MachO::CPU_SUBTYPE_I386_ALL:
1327 outs() << " cputype CPU_TYPE_I386\n";
1328 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1329 break;
1330 default:
1331 printUnknownCPUType(cputype, cpusubtype);
1332 break;
1333 }
1334 break;
1335 case MachO::CPU_TYPE_X86_64:
1336 switch (cpusubtype) {
1337 case MachO::CPU_SUBTYPE_X86_64_ALL:
1338 outs() << " cputype CPU_TYPE_X86_64\n";
1339 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1340 break;
1341 case MachO::CPU_SUBTYPE_X86_64_H:
1342 outs() << " cputype CPU_TYPE_X86_64\n";
1343 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1344 break;
1345 default:
1346 printUnknownCPUType(cputype, cpusubtype);
1347 break;
1348 }
1349 break;
1350 case MachO::CPU_TYPE_ARM:
1351 switch (cpusubtype) {
1352 case MachO::CPU_SUBTYPE_ARM_ALL:
1353 outs() << " cputype CPU_TYPE_ARM\n";
1354 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1355 break;
1356 case MachO::CPU_SUBTYPE_ARM_V4T:
1357 outs() << " cputype CPU_TYPE_ARM\n";
1358 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1359 break;
1360 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1361 outs() << " cputype CPU_TYPE_ARM\n";
1362 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1363 break;
1364 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1365 outs() << " cputype CPU_TYPE_ARM\n";
1366 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1367 break;
1368 case MachO::CPU_SUBTYPE_ARM_V6:
1369 outs() << " cputype CPU_TYPE_ARM\n";
1370 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1371 break;
1372 case MachO::CPU_SUBTYPE_ARM_V6M:
1373 outs() << " cputype CPU_TYPE_ARM\n";
1374 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1375 break;
1376 case MachO::CPU_SUBTYPE_ARM_V7:
1377 outs() << " cputype CPU_TYPE_ARM\n";
1378 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1379 break;
1380 case MachO::CPU_SUBTYPE_ARM_V7EM:
1381 outs() << " cputype CPU_TYPE_ARM\n";
1382 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1383 break;
1384 case MachO::CPU_SUBTYPE_ARM_V7K:
1385 outs() << " cputype CPU_TYPE_ARM\n";
1386 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1387 break;
1388 case MachO::CPU_SUBTYPE_ARM_V7M:
1389 outs() << " cputype CPU_TYPE_ARM\n";
1390 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1391 break;
1392 case MachO::CPU_SUBTYPE_ARM_V7S:
1393 outs() << " cputype CPU_TYPE_ARM\n";
1394 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1395 break;
1396 default:
1397 printUnknownCPUType(cputype, cpusubtype);
1398 break;
1399 }
1400 break;
1401 case MachO::CPU_TYPE_ARM64:
1402 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1403 case MachO::CPU_SUBTYPE_ARM64_ALL:
1404 outs() << " cputype CPU_TYPE_ARM64\n";
1405 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1406 break;
1407 default:
1408 printUnknownCPUType(cputype, cpusubtype);
1409 break;
1410 }
1411 break;
1412 default:
1413 printUnknownCPUType(cputype, cpusubtype);
1414 break;
1415 }
1416}
1417
1418static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1419 bool verbose) {
1420 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001421 if (verbose) {
1422 if (UB->getMagic() == MachO::FAT_MAGIC)
1423 outs() << "fat_magic FAT_MAGIC\n";
1424 else // UB->getMagic() == MachO::FAT_MAGIC_64
1425 outs() << "fat_magic FAT_MAGIC_64\n";
1426 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001427 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1428
1429 uint32_t nfat_arch = UB->getNumberOfObjects();
1430 StringRef Buf = UB->getData();
1431 uint64_t size = Buf.size();
1432 uint64_t big_size = sizeof(struct MachO::fat_header) +
1433 nfat_arch * sizeof(struct MachO::fat_arch);
1434 outs() << "nfat_arch " << UB->getNumberOfObjects();
1435 if (nfat_arch == 0)
1436 outs() << " (malformed, contains zero architecture types)\n";
1437 else if (big_size > size)
1438 outs() << " (malformed, architectures past end of file)\n";
1439 else
1440 outs() << "\n";
1441
1442 for (uint32_t i = 0; i < nfat_arch; ++i) {
1443 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1444 uint32_t cputype = OFA.getCPUType();
1445 uint32_t cpusubtype = OFA.getCPUSubType();
1446 outs() << "architecture ";
1447 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1448 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1449 uint32_t other_cputype = other_OFA.getCPUType();
1450 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001451 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001452 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001453 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001454 outs() << "(illegal duplicate architecture) ";
1455 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001456 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001457 }
1458 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001459 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001460 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1461 } else {
1462 outs() << i << "\n";
1463 outs() << " cputype " << cputype << "\n";
1464 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1465 << "\n";
1466 }
1467 if (verbose &&
1468 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1469 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1470 else
1471 outs() << " capabilities "
1472 << format("0x%" PRIx32,
1473 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1474 outs() << " offset " << OFA.getOffset();
1475 if (OFA.getOffset() > size)
1476 outs() << " (past end of file)";
1477 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1478 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1479 outs() << "\n";
1480 outs() << " size " << OFA.getSize();
1481 big_size = OFA.getOffset() + OFA.getSize();
1482 if (big_size > size)
1483 outs() << " (past end of file)";
1484 outs() << "\n";
1485 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1486 << ")\n";
1487 }
1488}
1489
Kevin Enderby6524bd82016-07-19 20:47:07 +00001490static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1491 bool verbose, bool print_offset,
1492 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001493 if (print_offset)
1494 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001495 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1496 if (!ModeOrErr)
1497 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1498 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001499 if (verbose) {
1500 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1501 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1502 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001503 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1504 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1505 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1506 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1507 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1508 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1509 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1510 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1511 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001512 } else {
1513 outs() << format("0%o ", Mode);
1514 }
1515
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001516 Expected<unsigned> UIDOrErr = C.getUID();
1517 if (!UIDOrErr)
1518 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1519 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001520 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001521 Expected<unsigned> GIDOrErr = C.getGID();
1522 if (!GIDOrErr)
1523 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1524 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001525 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001526 Expected<uint64_t> Size = C.getRawSize();
1527 if (!Size)
1528 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001529 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001530
1531 StringRef RawLastModified = C.getRawLastModified();
1532 if (verbose) {
1533 unsigned Seconds;
1534 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001535 outs() << "(date: \"" << RawLastModified
1536 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001537 else {
1538 // Since cime(3) returns a 26 character string of the form:
1539 // "Sun Sep 16 01:03:52 1973\n\0"
1540 // just print 24 characters.
1541 time_t t = Seconds;
1542 outs() << format("%.24s ", ctime(&t));
1543 }
1544 } else {
1545 outs() << RawLastModified << " ";
1546 }
1547
1548 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001549 Expected<StringRef> NameOrErr = C.getName();
1550 if (!NameOrErr) {
1551 consumeError(NameOrErr.takeError());
1552 Expected<StringRef> NameOrErr = C.getRawName();
1553 if (!NameOrErr)
1554 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1555 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001556 outs() << RawName << "\n";
1557 } else {
1558 StringRef Name = NameOrErr.get();
1559 outs() << Name << "\n";
1560 }
1561 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001562 Expected<StringRef> NameOrErr = C.getRawName();
1563 if (!NameOrErr)
1564 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1565 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001566 outs() << RawName << "\n";
1567 }
1568}
1569
Kevin Enderby6524bd82016-07-19 20:47:07 +00001570static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1571 bool print_offset,
1572 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001573 Error Err = Error::success();
1574 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001575 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001576 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1577
Lang Hamesfc209622016-07-14 02:24:01 +00001578 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001579 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001580}
1581
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001582// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1583// -arch flags selecting just those slices as specified by them and also parses
1584// archive files. Then for each individual Mach-O file ProcessMachO() is
1585// called to process the file based on the command line options.
1586void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001587 // Check for -arch all and verifiy the -arch flags are valid.
1588 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1589 if (ArchFlags[i] == "all") {
1590 ArchAll = true;
1591 } else {
1592 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1593 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1594 "'for the -arch option\n";
1595 return;
1596 }
1597 }
1598 }
1599
1600 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001601 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001602 if (!BinaryOrErr) {
1603 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1604 report_error(Filename, std::move(E));
1605 else
1606 outs() << Filename << ": is not an object file\n";
1607 return;
1608 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001609 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001610
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001611 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1612 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001613 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001614 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1615
Mehdi Amini41af4302016-11-11 04:28:40 +00001616 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001617 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001618 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1619 if (!ChildOrErr) {
1620 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1621 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001622 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001623 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001624 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1625 if (!checkMachOAndArchFlags(O, Filename))
1626 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001627 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001628 }
1629 }
Lang Hamesfc209622016-07-14 02:24:01 +00001630 if (Err)
1631 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001632 return;
1633 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001634 if (UniversalHeaders) {
1635 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001636 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001637 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001638 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1639 // If we have a list of architecture flags specified dump only those.
1640 if (!ArchAll && ArchFlags.size() != 0) {
1641 // Look for a slice in the universal binary that matches each ArchFlag.
1642 bool ArchFound;
1643 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1644 ArchFound = false;
1645 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1646 E = UB->end_objects();
1647 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001648 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001649 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001650 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001651 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001652 std::string ArchitectureName = "";
1653 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +00001654 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001655 if (ObjOrErr) {
1656 ObjectFile &O = *ObjOrErr.get();
1657 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001658 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001659 } else if (auto E = isNotObjectErrorInvalidFileType(
1660 ObjOrErr.takeError())) {
1661 report_error(Filename, StringRef(), std::move(E),
1662 ArchitectureName);
1663 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001664 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001665 I->getAsArchive()) {
1666 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001667 outs() << "Archive : " << Filename;
1668 if (!ArchitectureName.empty())
1669 outs() << " (architecture " << ArchitectureName << ")";
1670 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001671 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001672 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1673 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001674 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001675 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001676 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1677 if (!ChildOrErr) {
1678 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001679 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001680 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001681 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001682 if (MachOObjectFile *O =
1683 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001684 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001685 }
Lang Hamesfc209622016-07-14 02:24:01 +00001686 if (Err)
1687 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001688 } else {
1689 consumeError(AOrErr.takeError());
1690 error("Mach-O universal file: " + Filename + " for " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001691 "architecture " + StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001692 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001693 }
1694 }
1695 }
1696 if (!ArchFound) {
1697 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1698 << "architecture: " + ArchFlags[i] + "\n";
1699 return;
1700 }
1701 }
1702 return;
1703 }
1704 // No architecture flags were specified so if this contains a slice that
1705 // matches the host architecture dump only that.
1706 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001707 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1708 E = UB->end_objects();
1709 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001710 if (MachOObjectFile::getHostArch().getArchName() ==
Kevin Enderby59343a92016-12-16 22:54:02 +00001711 I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001712 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001713 std::string ArchiveName;
1714 ArchiveName.clear();
1715 if (ObjOrErr) {
1716 ObjectFile &O = *ObjOrErr.get();
1717 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001718 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001719 } else if (auto E = isNotObjectErrorInvalidFileType(
1720 ObjOrErr.takeError())) {
1721 report_error(Filename, std::move(E));
1722 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001723 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001724 I->getAsArchive()) {
1725 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001726 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001727 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001728 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1729 ArchiveMemberOffsets);
Mehdi Amini41af4302016-11-11 04:28:40 +00001730 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001731 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001732 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1733 if (!ChildOrErr) {
1734 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1735 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001736 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001737 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001738 if (MachOObjectFile *O =
1739 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001740 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001741 }
Lang Hamesfc209622016-07-14 02:24:01 +00001742 if (Err)
1743 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001744 } else {
1745 consumeError(AOrErr.takeError());
1746 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001747 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001748 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001749 }
1750 return;
1751 }
1752 }
1753 }
1754 // Either all architectures have been specified or none have been specified
1755 // and this does not contain the host architecture so dump all the slices.
1756 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1757 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1758 E = UB->end_objects();
1759 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001760 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001761 std::string ArchitectureName = "";
1762 if (moreThanOneArch)
Kevin Enderby59343a92016-12-16 22:54:02 +00001763 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001764 if (ObjOrErr) {
1765 ObjectFile &Obj = *ObjOrErr.get();
1766 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001767 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001768 } else if (auto E = isNotObjectErrorInvalidFileType(
1769 ObjOrErr.takeError())) {
1770 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1771 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001772 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1773 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001774 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001775 outs() << "Archive : " << Filename;
1776 if (!ArchitectureName.empty())
1777 outs() << " (architecture " << ArchitectureName << ")";
1778 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001779 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001780 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1781 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001782 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001783 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001784 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1785 if (!ChildOrErr) {
1786 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001787 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001788 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001789 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001790 if (MachOObjectFile *O =
1791 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1792 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001793 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1794 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001795 }
1796 }
Lang Hamesfc209622016-07-14 02:24:01 +00001797 if (Err)
1798 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001799 } else {
1800 consumeError(AOrErr.takeError());
1801 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001802 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001803 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001804 }
1805 }
1806 return;
1807 }
1808 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1809 if (!checkMachOAndArchFlags(O, Filename))
1810 return;
1811 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001812 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001813 } else
1814 errs() << "llvm-objdump: '" << Filename << "': "
1815 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001816 return;
1817 }
1818 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001819}
1820
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001821// The block of info used by the Symbolizer call backs.
1822struct DisassembleInfo {
1823 bool verbose;
1824 MachOObjectFile *O;
1825 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001826 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001827 std::vector<SectionRef> *Sections;
1828 const char *class_name;
1829 const char *selector_name;
1830 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001831 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001832 uint64_t adrp_addr;
1833 uint32_t adrp_inst;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00001834 std::unique_ptr<SymbolAddressMap> bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001835 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001836};
1837
1838// SymbolizerGetOpInfo() is the operand information call back function.
1839// This is called to get the symbolic information for operand(s) of an
1840// instruction when it is being done. This routine does this from
1841// the relocation information, symbol table, etc. That block of information
1842// is a pointer to the struct DisassembleInfo that was passed when the
1843// disassembler context was created and passed to back to here when
1844// called back by the disassembler for instruction operands that could have
1845// relocation information. The address of the instruction containing operand is
1846// at the Pc parameter. The immediate value the operand has is passed in
1847// op_info->Value and is at Offset past the start of the instruction and has a
1848// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1849// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1850// names and addends of the symbolic expression to add for the operand. The
1851// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1852// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001853static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1854 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001855 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1856 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001857 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001858
1859 // Make sure all fields returned are zero if we don't set them.
1860 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1861 op_info->Value = value;
1862
1863 // If the TagType is not the value 1 which it code knows about or if no
1864 // verbose symbolic information is wanted then just return 0, indicating no
1865 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001866 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001867 return 0;
1868
1869 unsigned int Arch = info->O->getArch();
1870 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001871 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1872 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001873 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1874 // TODO:
1875 // Search the external relocation entries of a fully linked image
1876 // (if any) for an entry that matches this segment offset.
1877 // uint32_t seg_offset = (Pc + Offset);
1878 return 0;
1879 }
1880 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1881 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001882 uint32_t sect_addr = info->S.getAddress();
1883 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1884 bool reloc_found = false;
1885 DataRefImpl Rel;
1886 MachO::any_relocation_info RE;
1887 bool isExtern = false;
1888 SymbolRef Symbol;
1889 bool r_scattered = false;
1890 uint32_t r_value, pair_r_value, r_type;
1891 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001892 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001893 if (RelocOffset == sect_offset) {
1894 Rel = Reloc.getRawDataRefImpl();
1895 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001896 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001897 r_scattered = info->O->isRelocationScattered(RE);
1898 if (r_scattered) {
1899 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001900 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1901 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1902 DataRefImpl RelNext = Rel;
1903 info->O->moveRelocationNext(RelNext);
1904 MachO::any_relocation_info RENext;
1905 RENext = info->O->getRelocation(RelNext);
1906 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001907 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001908 else
1909 return 0;
1910 }
1911 } else {
1912 isExtern = info->O->getPlainRelocationExternal(RE);
1913 if (isExtern) {
1914 symbol_iterator RelocSym = Reloc.getSymbol();
1915 Symbol = *RelocSym;
1916 }
1917 }
1918 reloc_found = true;
1919 break;
1920 }
1921 }
1922 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001923 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001924 if (!SymName)
1925 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001926 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001927 op_info->AddSymbol.Present = 1;
1928 op_info->AddSymbol.Name = name;
1929 // For i386 extern relocation entries the value in the instruction is
1930 // the offset from the symbol, and value is already set in op_info->Value.
1931 return 1;
1932 }
1933 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1934 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001935 const char *add = GuessSymbolName(r_value, info->AddrMap);
1936 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001937 uint32_t offset = value - (r_value - pair_r_value);
1938 op_info->AddSymbol.Present = 1;
1939 if (add != nullptr)
1940 op_info->AddSymbol.Name = add;
1941 else
1942 op_info->AddSymbol.Value = r_value;
1943 op_info->SubtractSymbol.Present = 1;
1944 if (sub != nullptr)
1945 op_info->SubtractSymbol.Name = sub;
1946 else
1947 op_info->SubtractSymbol.Value = pair_r_value;
1948 op_info->Value = offset;
1949 return 1;
1950 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001951 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001952 }
1953 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001954 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1955 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00001956 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
1957 // relocation entries of a linked image (if any) for an entry that matches
1958 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001959 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00001960 uint64_t seg_offset = Pc + Offset;
1961 bool reloc_found = false;
1962 DataRefImpl Rel;
1963 MachO::any_relocation_info RE;
1964 bool isExtern = false;
1965 SymbolRef Symbol;
1966 for (const RelocationRef &Reloc : info->O->external_relocations()) {
1967 uint64_t RelocOffset = Reloc.getOffset();
1968 if (RelocOffset == seg_offset) {
1969 Rel = Reloc.getRawDataRefImpl();
1970 RE = info->O->getRelocation(Rel);
1971 // external relocation entries should always be external.
1972 isExtern = info->O->getPlainRelocationExternal(RE);
1973 if (isExtern) {
1974 symbol_iterator RelocSym = Reloc.getSymbol();
1975 Symbol = *RelocSym;
1976 }
1977 reloc_found = true;
1978 break;
1979 }
1980 }
1981 if (reloc_found && isExtern) {
1982 // The Value passed in will be adjusted by the Pc if the instruction
1983 // adds the Pc. But for x86_64 external relocation entries the Value
1984 // is the offset from the external symbol.
1985 if (info->O->getAnyRelocationPCRel(RE))
1986 op_info->Value -= Pc + Offset + Size;
1987 Expected<StringRef> SymName = Symbol.getName();
1988 if (!SymName)
1989 report_error(info->O->getFileName(), SymName.takeError());
1990 const char *name = SymName->data();
1991 op_info->AddSymbol.Present = 1;
1992 op_info->AddSymbol.Name = name;
1993 return 1;
1994 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001995 return 0;
1996 }
1997 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1998 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001999 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002000 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2001 bool reloc_found = false;
2002 DataRefImpl Rel;
2003 MachO::any_relocation_info RE;
2004 bool isExtern = false;
2005 SymbolRef Symbol;
2006 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002007 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002008 if (RelocOffset == sect_offset) {
2009 Rel = Reloc.getRawDataRefImpl();
2010 RE = info->O->getRelocation(Rel);
2011 // NOTE: Scattered relocations don't exist on x86_64.
2012 isExtern = info->O->getPlainRelocationExternal(RE);
2013 if (isExtern) {
2014 symbol_iterator RelocSym = Reloc.getSymbol();
2015 Symbol = *RelocSym;
2016 }
2017 reloc_found = true;
2018 break;
2019 }
2020 }
2021 if (reloc_found && isExtern) {
2022 // The Value passed in will be adjusted by the Pc if the instruction
2023 // adds the Pc. But for x86_64 external relocation entries the Value
2024 // is the offset from the external symbol.
2025 if (info->O->getAnyRelocationPCRel(RE))
2026 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002027 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002028 if (!SymName)
2029 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002030 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002031 unsigned Type = info->O->getAnyRelocationType(RE);
2032 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2033 DataRefImpl RelNext = Rel;
2034 info->O->moveRelocationNext(RelNext);
2035 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2036 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2037 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2038 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2039 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2040 op_info->SubtractSymbol.Present = 1;
2041 op_info->SubtractSymbol.Name = name;
2042 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2043 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002044 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002045 if (!SymNameNext)
2046 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002047 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002048 }
2049 }
2050 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2051 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2052 op_info->AddSymbol.Present = 1;
2053 op_info->AddSymbol.Name = name;
2054 return 1;
2055 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002056 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002057 }
2058 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002059 if (Offset != 0 || (Size != 4 && Size != 2))
2060 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002061 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2062 // TODO:
2063 // Search the external relocation entries of a fully linked image
2064 // (if any) for an entry that matches this segment offset.
2065 // uint32_t seg_offset = (Pc + Offset);
2066 return 0;
2067 }
2068 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2069 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002070 uint32_t sect_addr = info->S.getAddress();
2071 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002072 DataRefImpl Rel;
2073 MachO::any_relocation_info RE;
2074 bool isExtern = false;
2075 SymbolRef Symbol;
2076 bool r_scattered = false;
2077 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002078 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002079 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2080 uint64_t RelocOffset = Reloc.getOffset();
2081 return RelocOffset == sect_offset;
2082 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002083
2084 if (Reloc == info->S.relocations().end())
2085 return 0;
2086
2087 Rel = Reloc->getRawDataRefImpl();
2088 RE = info->O->getRelocation(Rel);
2089 r_length = info->O->getAnyRelocationLength(RE);
2090 r_scattered = info->O->isRelocationScattered(RE);
2091 if (r_scattered) {
2092 r_value = info->O->getScatteredRelocationValue(RE);
2093 r_type = info->O->getScatteredRelocationType(RE);
2094 } else {
2095 r_type = info->O->getAnyRelocationType(RE);
2096 isExtern = info->O->getPlainRelocationExternal(RE);
2097 if (isExtern) {
2098 symbol_iterator RelocSym = Reloc->getSymbol();
2099 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002100 }
2101 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002102 if (r_type == MachO::ARM_RELOC_HALF ||
2103 r_type == MachO::ARM_RELOC_SECTDIFF ||
2104 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2105 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2106 DataRefImpl RelNext = Rel;
2107 info->O->moveRelocationNext(RelNext);
2108 MachO::any_relocation_info RENext;
2109 RENext = info->O->getRelocation(RelNext);
2110 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2111 if (info->O->isRelocationScattered(RENext))
2112 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2113 }
2114
2115 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002116 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002117 if (!SymName)
2118 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002119 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002120 op_info->AddSymbol.Present = 1;
2121 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002122 switch (r_type) {
2123 case MachO::ARM_RELOC_HALF:
2124 if ((r_length & 0x1) == 1) {
2125 op_info->Value = value << 16 | other_half;
2126 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2127 } else {
2128 op_info->Value = other_half << 16 | value;
2129 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002130 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002131 break;
2132 default:
2133 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002134 }
2135 return 1;
2136 }
2137 // If we have a branch that is not an external relocation entry then
2138 // return 0 so the code in tryAddingSymbolicOperand() can use the
2139 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002140 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002141 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2142 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002143 return 0;
2144
2145 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002146 if (r_type == MachO::ARM_RELOC_HALF ||
2147 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2148 if ((r_length & 0x1) == 1)
2149 value = value << 16 | other_half;
2150 else
2151 value = other_half << 16 | value;
2152 }
2153 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2154 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2155 offset = value - r_value;
2156 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002157 }
2158
David Blaikie33dd45d02015-03-23 18:39:02 +00002159 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002160 if ((r_length & 0x1) == 1)
2161 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2162 else
2163 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002164 const char *add = GuessSymbolName(r_value, info->AddrMap);
2165 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002166 int32_t offset = value - (r_value - pair_r_value);
2167 op_info->AddSymbol.Present = 1;
2168 if (add != nullptr)
2169 op_info->AddSymbol.Name = add;
2170 else
2171 op_info->AddSymbol.Value = r_value;
2172 op_info->SubtractSymbol.Present = 1;
2173 if (sub != nullptr)
2174 op_info->SubtractSymbol.Name = sub;
2175 else
2176 op_info->SubtractSymbol.Value = pair_r_value;
2177 op_info->Value = offset;
2178 return 1;
2179 }
2180
Kevin Enderby930fdc72014-11-06 19:00:13 +00002181 op_info->AddSymbol.Present = 1;
2182 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002183 if (r_type == MachO::ARM_RELOC_HALF) {
2184 if ((r_length & 0x1) == 1)
2185 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2186 else
2187 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002188 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002189 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002190 if (add != nullptr) {
2191 op_info->AddSymbol.Name = add;
2192 return 1;
2193 }
2194 op_info->AddSymbol.Value = value;
2195 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002196 }
2197 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002198 if (Offset != 0 || Size != 4)
2199 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002200 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2201 // TODO:
2202 // Search the external relocation entries of a fully linked image
2203 // (if any) for an entry that matches this segment offset.
2204 // uint64_t seg_offset = (Pc + Offset);
2205 return 0;
2206 }
2207 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2208 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002209 uint64_t sect_addr = info->S.getAddress();
2210 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002211 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002212 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2213 uint64_t RelocOffset = Reloc.getOffset();
2214 return RelocOffset == sect_offset;
2215 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002216
David Blaikie33dd45d02015-03-23 18:39:02 +00002217 if (Reloc == info->S.relocations().end())
2218 return 0;
2219
2220 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2221 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2222 uint32_t r_type = info->O->getAnyRelocationType(RE);
2223 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2224 DataRefImpl RelNext = Rel;
2225 info->O->moveRelocationNext(RelNext);
2226 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2227 if (value == 0) {
2228 value = info->O->getPlainRelocationSymbolNum(RENext);
2229 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002230 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002231 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002232 // NOTE: Scattered relocations don't exist on arm64.
2233 if (!info->O->getPlainRelocationExternal(RE))
2234 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002235 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002236 if (!SymName)
2237 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002238 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002239 op_info->AddSymbol.Present = 1;
2240 op_info->AddSymbol.Name = name;
2241
2242 switch (r_type) {
2243 case MachO::ARM64_RELOC_PAGE21:
2244 /* @page */
2245 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2246 break;
2247 case MachO::ARM64_RELOC_PAGEOFF12:
2248 /* @pageoff */
2249 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2250 break;
2251 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2252 /* @gotpage */
2253 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2254 break;
2255 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2256 /* @gotpageoff */
2257 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2258 break;
2259 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2260 /* @tvlppage is not implemented in llvm-mc */
2261 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2262 break;
2263 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2264 /* @tvlppageoff is not implemented in llvm-mc */
2265 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2266 break;
2267 default:
2268 case MachO::ARM64_RELOC_BRANCH26:
2269 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2270 break;
2271 }
2272 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002273 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002274 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002275}
2276
Kevin Enderbybf246f52014-09-24 23:08:22 +00002277// GuessCstringPointer is passed the address of what might be a pointer to a
2278// literal string in a cstring section. If that address is in a cstring section
2279// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002280static const char *GuessCstringPointer(uint64_t ReferenceValue,
2281 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002282 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002283 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2284 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2285 for (unsigned J = 0; J < Seg.nsects; ++J) {
2286 MachO::section_64 Sec = info->O->getSection64(Load, J);
2287 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2288 if (section_type == MachO::S_CSTRING_LITERALS &&
2289 ReferenceValue >= Sec.addr &&
2290 ReferenceValue < Sec.addr + Sec.size) {
2291 uint64_t sect_offset = ReferenceValue - Sec.addr;
2292 uint64_t object_offset = Sec.offset + sect_offset;
2293 StringRef MachOContents = info->O->getData();
2294 uint64_t object_size = MachOContents.size();
2295 const char *object_addr = (const char *)MachOContents.data();
2296 if (object_offset < object_size) {
2297 const char *name = object_addr + object_offset;
2298 return name;
2299 } else {
2300 return nullptr;
2301 }
2302 }
2303 }
2304 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2305 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2306 for (unsigned J = 0; J < Seg.nsects; ++J) {
2307 MachO::section Sec = info->O->getSection(Load, J);
2308 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2309 if (section_type == MachO::S_CSTRING_LITERALS &&
2310 ReferenceValue >= Sec.addr &&
2311 ReferenceValue < Sec.addr + Sec.size) {
2312 uint64_t sect_offset = ReferenceValue - Sec.addr;
2313 uint64_t object_offset = Sec.offset + sect_offset;
2314 StringRef MachOContents = info->O->getData();
2315 uint64_t object_size = MachOContents.size();
2316 const char *object_addr = (const char *)MachOContents.data();
2317 if (object_offset < object_size) {
2318 const char *name = object_addr + object_offset;
2319 return name;
2320 } else {
2321 return nullptr;
2322 }
2323 }
2324 }
2325 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002326 }
2327 return nullptr;
2328}
2329
Kevin Enderby85974882014-09-26 22:20:44 +00002330// GuessIndirectSymbol returns the name of the indirect symbol for the
2331// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2332// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2333// symbol name being referenced by the stub or pointer.
2334static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2335 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002336 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2337 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002338 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002339 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2340 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2341 for (unsigned J = 0; J < Seg.nsects; ++J) {
2342 MachO::section_64 Sec = info->O->getSection64(Load, J);
2343 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2344 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2345 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2346 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2347 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2348 section_type == MachO::S_SYMBOL_STUBS) &&
2349 ReferenceValue >= Sec.addr &&
2350 ReferenceValue < Sec.addr + Sec.size) {
2351 uint32_t stride;
2352 if (section_type == MachO::S_SYMBOL_STUBS)
2353 stride = Sec.reserved2;
2354 else
2355 stride = 8;
2356 if (stride == 0)
2357 return nullptr;
2358 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2359 if (index < Dysymtab.nindirectsyms) {
2360 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002361 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002362 if (indirect_symbol < Symtab.nsyms) {
2363 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2364 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002365 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002366 if (!SymName)
2367 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002368 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002369 return name;
2370 }
2371 }
2372 }
2373 }
2374 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2375 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2376 for (unsigned J = 0; J < Seg.nsects; ++J) {
2377 MachO::section Sec = info->O->getSection(Load, J);
2378 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2379 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2380 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2381 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2382 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2383 section_type == MachO::S_SYMBOL_STUBS) &&
2384 ReferenceValue >= Sec.addr &&
2385 ReferenceValue < Sec.addr + Sec.size) {
2386 uint32_t stride;
2387 if (section_type == MachO::S_SYMBOL_STUBS)
2388 stride = Sec.reserved2;
2389 else
2390 stride = 4;
2391 if (stride == 0)
2392 return nullptr;
2393 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2394 if (index < Dysymtab.nindirectsyms) {
2395 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002396 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002397 if (indirect_symbol < Symtab.nsyms) {
2398 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2399 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002400 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002401 if (!SymName)
2402 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002403 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002404 return name;
2405 }
2406 }
2407 }
2408 }
2409 }
Kevin Enderby85974882014-09-26 22:20:44 +00002410 }
2411 return nullptr;
2412}
2413
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002414// method_reference() is called passing it the ReferenceName that might be
2415// a reference it to an Objective-C method call. If so then it allocates and
2416// assembles a method call string with the values last seen and saved in
2417// the DisassembleInfo's class_name and selector_name fields. This is saved
2418// into the method field of the info and any previous string is free'ed.
2419// Then the class_name field in the info is set to nullptr. The method call
2420// string is set into ReferenceName and ReferenceType is set to
2421// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2422// then both ReferenceType and ReferenceName are left unchanged.
2423static void method_reference(struct DisassembleInfo *info,
2424 uint64_t *ReferenceType,
2425 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002426 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002427 if (*ReferenceName != nullptr) {
2428 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002429 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002430 if (info->method != nullptr)
2431 free(info->method);
2432 if (info->class_name != nullptr) {
2433 info->method = (char *)malloc(5 + strlen(info->class_name) +
2434 strlen(info->selector_name));
2435 if (info->method != nullptr) {
2436 strcpy(info->method, "+[");
2437 strcat(info->method, info->class_name);
2438 strcat(info->method, " ");
2439 strcat(info->method, info->selector_name);
2440 strcat(info->method, "]");
2441 *ReferenceName = info->method;
2442 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2443 }
2444 } else {
2445 info->method = (char *)malloc(9 + strlen(info->selector_name));
2446 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002447 if (Arch == Triple::x86_64)
2448 strcpy(info->method, "-[%rdi ");
2449 else if (Arch == Triple::aarch64)
2450 strcpy(info->method, "-[x0 ");
2451 else
2452 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002453 strcat(info->method, info->selector_name);
2454 strcat(info->method, "]");
2455 *ReferenceName = info->method;
2456 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2457 }
2458 }
2459 info->class_name = nullptr;
2460 }
2461 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002462 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002463 if (info->method != nullptr)
2464 free(info->method);
2465 info->method = (char *)malloc(17 + strlen(info->selector_name));
2466 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002467 if (Arch == Triple::x86_64)
2468 strcpy(info->method, "-[[%rdi super] ");
2469 else if (Arch == Triple::aarch64)
2470 strcpy(info->method, "-[[x0 super] ");
2471 else
2472 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002473 strcat(info->method, info->selector_name);
2474 strcat(info->method, "]");
2475 *ReferenceName = info->method;
2476 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2477 }
2478 info->class_name = nullptr;
2479 }
2480 }
2481 }
2482}
2483
2484// GuessPointerPointer() is passed the address of what might be a pointer to
2485// a reference to an Objective-C class, selector, message ref or cfstring.
2486// If so the value of the pointer is returned and one of the booleans are set
2487// to true. If not zero is returned and all the booleans are set to false.
2488static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2489 struct DisassembleInfo *info,
2490 bool &classref, bool &selref, bool &msgref,
2491 bool &cfstring) {
2492 classref = false;
2493 selref = false;
2494 msgref = false;
2495 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002496 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002497 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2498 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2499 for (unsigned J = 0; J < Seg.nsects; ++J) {
2500 MachO::section_64 Sec = info->O->getSection64(Load, J);
2501 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2502 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2503 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2504 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2505 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2506 ReferenceValue >= Sec.addr &&
2507 ReferenceValue < Sec.addr + Sec.size) {
2508 uint64_t sect_offset = ReferenceValue - Sec.addr;
2509 uint64_t object_offset = Sec.offset + sect_offset;
2510 StringRef MachOContents = info->O->getData();
2511 uint64_t object_size = MachOContents.size();
2512 const char *object_addr = (const char *)MachOContents.data();
2513 if (object_offset < object_size) {
2514 uint64_t pointer_value;
2515 memcpy(&pointer_value, object_addr + object_offset,
2516 sizeof(uint64_t));
2517 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2518 sys::swapByteOrder(pointer_value);
2519 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2520 selref = true;
2521 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2522 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2523 classref = true;
2524 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2525 ReferenceValue + 8 < Sec.addr + Sec.size) {
2526 msgref = true;
2527 memcpy(&pointer_value, object_addr + object_offset + 8,
2528 sizeof(uint64_t));
2529 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2530 sys::swapByteOrder(pointer_value);
2531 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2532 cfstring = true;
2533 return pointer_value;
2534 } else {
2535 return 0;
2536 }
2537 }
2538 }
2539 }
2540 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002541 }
2542 return 0;
2543}
2544
2545// get_pointer_64 returns a pointer to the bytes in the object file at the
2546// Address from a section in the Mach-O file. And indirectly returns the
2547// offset into the section, number of bytes left in the section past the offset
2548// and which section is was being referenced. If the Address is not in a
2549// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002550static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2551 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002552 DisassembleInfo *info,
2553 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002554 offset = 0;
2555 left = 0;
2556 S = SectionRef();
2557 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2558 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2559 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002560 if (SectSize == 0)
2561 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002562 if (objc_only) {
2563 StringRef SectName;
2564 ((*(info->Sections))[SectIdx]).getName(SectName);
2565 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2566 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2567 if (SegName != "__OBJC" && SectName != "__cstring")
2568 continue;
2569 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002570 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2571 S = (*(info->Sections))[SectIdx];
2572 offset = Address - SectAddress;
2573 left = SectSize - offset;
2574 StringRef SectContents;
2575 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2576 return SectContents.data() + offset;
2577 }
2578 }
2579 return nullptr;
2580}
2581
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002582static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2583 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002584 DisassembleInfo *info,
2585 bool objc_only = false) {
2586 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002587}
2588
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002589// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2590// the symbol indirectly through n_value. Based on the relocation information
2591// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002592// If no relocation information is found and a non-zero ReferenceValue for the
2593// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002594static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2595 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002596 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002597 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002598 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002599 return nullptr;
2600
2601 // See if there is an external relocation entry at the sect_offset.
2602 bool reloc_found = false;
2603 DataRefImpl Rel;
2604 MachO::any_relocation_info RE;
2605 bool isExtern = false;
2606 SymbolRef Symbol;
2607 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002608 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002609 if (RelocOffset == sect_offset) {
2610 Rel = Reloc.getRawDataRefImpl();
2611 RE = info->O->getRelocation(Rel);
2612 if (info->O->isRelocationScattered(RE))
2613 continue;
2614 isExtern = info->O->getPlainRelocationExternal(RE);
2615 if (isExtern) {
2616 symbol_iterator RelocSym = Reloc.getSymbol();
2617 Symbol = *RelocSym;
2618 }
2619 reloc_found = true;
2620 break;
2621 }
2622 }
2623 // If there is an external relocation entry for a symbol in this section
2624 // at this section_offset then use that symbol's value for the n_value
2625 // and return its name.
2626 const char *SymbolName = nullptr;
2627 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002628 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002629 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002630 if (!NameOrError)
2631 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002632 StringRef Name = *NameOrError;
2633 if (!Name.empty()) {
2634 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002635 return SymbolName;
2636 }
2637 }
2638
2639 // TODO: For fully linked images, look through the external relocation
2640 // entries off the dynamic symtab command. For these the r_offset is from the
2641 // start of the first writeable segment in the Mach-O file. So the offset
2642 // to this section from that segment is passed to this routine by the caller,
2643 // as the database_offset. Which is the difference of the section's starting
2644 // address and the first writable segment.
2645 //
2646 // NOTE: need add passing the database_offset to this routine.
2647
Kevin Enderby0fc11822015-04-01 20:57:01 +00002648 // We did not find an external relocation entry so look up the ReferenceValue
2649 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002650 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002651
2652 return SymbolName;
2653}
2654
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002655static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2656 DisassembleInfo *info,
2657 uint32_t ReferenceValue) {
2658 uint64_t n_value64;
2659 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2660}
2661
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002662// These are structs in the Objective-C meta data and read to produce the
2663// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00002664// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
2665// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002666
2667// The cfstring object in a 64-bit Mach-O file.
2668struct cfstring64_t {
2669 uint64_t isa; // class64_t * (64-bit pointer)
2670 uint64_t flags; // flag bits
2671 uint64_t characters; // char * (64-bit pointer)
2672 uint64_t length; // number of non-NULL characters in above
2673};
2674
2675// The class object in a 64-bit Mach-O file.
2676struct class64_t {
2677 uint64_t isa; // class64_t * (64-bit pointer)
2678 uint64_t superclass; // class64_t * (64-bit pointer)
2679 uint64_t cache; // Cache (64-bit pointer)
2680 uint64_t vtable; // IMP * (64-bit pointer)
2681 uint64_t data; // class_ro64_t * (64-bit pointer)
2682};
2683
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002684struct class32_t {
2685 uint32_t isa; /* class32_t * (32-bit pointer) */
2686 uint32_t superclass; /* class32_t * (32-bit pointer) */
2687 uint32_t cache; /* Cache (32-bit pointer) */
2688 uint32_t vtable; /* IMP * (32-bit pointer) */
2689 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2690};
2691
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002692struct class_ro64_t {
2693 uint32_t flags;
2694 uint32_t instanceStart;
2695 uint32_t instanceSize;
2696 uint32_t reserved;
2697 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2698 uint64_t name; // const char * (64-bit pointer)
2699 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2700 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2701 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2702 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2703 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2704};
2705
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002706struct class_ro32_t {
2707 uint32_t flags;
2708 uint32_t instanceStart;
2709 uint32_t instanceSize;
2710 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2711 uint32_t name; /* const char * (32-bit pointer) */
2712 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2713 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2714 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2715 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2716 uint32_t baseProperties; /* const struct objc_property_list *
2717 (32-bit pointer) */
2718};
2719
2720/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002721#define RO_META (1 << 0)
2722#define RO_ROOT (1 << 1)
2723#define RO_HAS_CXX_STRUCTORS (1 << 2)
2724
2725struct method_list64_t {
2726 uint32_t entsize;
2727 uint32_t count;
2728 /* struct method64_t first; These structures follow inline */
2729};
2730
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002731struct method_list32_t {
2732 uint32_t entsize;
2733 uint32_t count;
2734 /* struct method32_t first; These structures follow inline */
2735};
2736
Kevin Enderby0fc11822015-04-01 20:57:01 +00002737struct method64_t {
2738 uint64_t name; /* SEL (64-bit pointer) */
2739 uint64_t types; /* const char * (64-bit pointer) */
2740 uint64_t imp; /* IMP (64-bit pointer) */
2741};
2742
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002743struct method32_t {
2744 uint32_t name; /* SEL (32-bit pointer) */
2745 uint32_t types; /* const char * (32-bit pointer) */
2746 uint32_t imp; /* IMP (32-bit pointer) */
2747};
2748
Kevin Enderby0fc11822015-04-01 20:57:01 +00002749struct protocol_list64_t {
2750 uint64_t count; /* uintptr_t (a 64-bit value) */
2751 /* struct protocol64_t * list[0]; These pointers follow inline */
2752};
2753
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002754struct protocol_list32_t {
2755 uint32_t count; /* uintptr_t (a 32-bit value) */
2756 /* struct protocol32_t * list[0]; These pointers follow inline */
2757};
2758
Kevin Enderby0fc11822015-04-01 20:57:01 +00002759struct protocol64_t {
2760 uint64_t isa; /* id * (64-bit pointer) */
2761 uint64_t name; /* const char * (64-bit pointer) */
2762 uint64_t protocols; /* struct protocol_list64_t *
2763 (64-bit pointer) */
2764 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2765 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2766 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2767 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2768 uint64_t instanceProperties; /* struct objc_property_list *
2769 (64-bit pointer) */
2770};
2771
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002772struct protocol32_t {
2773 uint32_t isa; /* id * (32-bit pointer) */
2774 uint32_t name; /* const char * (32-bit pointer) */
2775 uint32_t protocols; /* struct protocol_list_t *
2776 (32-bit pointer) */
2777 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2778 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2779 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2780 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2781 uint32_t instanceProperties; /* struct objc_property_list *
2782 (32-bit pointer) */
2783};
2784
Kevin Enderby0fc11822015-04-01 20:57:01 +00002785struct ivar_list64_t {
2786 uint32_t entsize;
2787 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002788 /* struct ivar64_t first; These structures follow inline */
2789};
2790
2791struct ivar_list32_t {
2792 uint32_t entsize;
2793 uint32_t count;
2794 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002795};
2796
2797struct ivar64_t {
2798 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2799 uint64_t name; /* const char * (64-bit pointer) */
2800 uint64_t type; /* const char * (64-bit pointer) */
2801 uint32_t alignment;
2802 uint32_t size;
2803};
2804
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002805struct ivar32_t {
2806 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2807 uint32_t name; /* const char * (32-bit pointer) */
2808 uint32_t type; /* const char * (32-bit pointer) */
2809 uint32_t alignment;
2810 uint32_t size;
2811};
2812
Kevin Enderby0fc11822015-04-01 20:57:01 +00002813struct objc_property_list64 {
2814 uint32_t entsize;
2815 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002816 /* struct objc_property64 first; These structures follow inline */
2817};
2818
2819struct objc_property_list32 {
2820 uint32_t entsize;
2821 uint32_t count;
2822 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002823};
2824
2825struct objc_property64 {
2826 uint64_t name; /* const char * (64-bit pointer) */
2827 uint64_t attributes; /* const char * (64-bit pointer) */
2828};
2829
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002830struct objc_property32 {
2831 uint32_t name; /* const char * (32-bit pointer) */
2832 uint32_t attributes; /* const char * (32-bit pointer) */
2833};
2834
Kevin Enderby0fc11822015-04-01 20:57:01 +00002835struct category64_t {
2836 uint64_t name; /* const char * (64-bit pointer) */
2837 uint64_t cls; /* struct class_t * (64-bit pointer) */
2838 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2839 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2840 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2841 uint64_t instanceProperties; /* struct objc_property_list *
2842 (64-bit pointer) */
2843};
2844
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002845struct category32_t {
2846 uint32_t name; /* const char * (32-bit pointer) */
2847 uint32_t cls; /* struct class_t * (32-bit pointer) */
2848 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2849 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2850 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2851 uint32_t instanceProperties; /* struct objc_property_list *
2852 (32-bit pointer) */
2853};
2854
Kevin Enderby0fc11822015-04-01 20:57:01 +00002855struct objc_image_info64 {
2856 uint32_t version;
2857 uint32_t flags;
2858};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002859struct objc_image_info32 {
2860 uint32_t version;
2861 uint32_t flags;
2862};
Kevin Enderby846c0002015-04-16 17:19:59 +00002863struct imageInfo_t {
2864 uint32_t version;
2865 uint32_t flags;
2866};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002867/* masks for objc_image_info.flags */
2868#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2869#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2870
2871struct message_ref64 {
2872 uint64_t imp; /* IMP (64-bit pointer) */
2873 uint64_t sel; /* SEL (64-bit pointer) */
2874};
2875
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002876struct message_ref32 {
2877 uint32_t imp; /* IMP (32-bit pointer) */
2878 uint32_t sel; /* SEL (32-bit pointer) */
2879};
2880
Kevin Enderby846c0002015-04-16 17:19:59 +00002881// Objective-C 1 (32-bit only) meta data structs.
2882
2883struct objc_module_t {
2884 uint32_t version;
2885 uint32_t size;
2886 uint32_t name; /* char * (32-bit pointer) */
2887 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2888};
2889
2890struct objc_symtab_t {
2891 uint32_t sel_ref_cnt;
2892 uint32_t refs; /* SEL * (32-bit pointer) */
2893 uint16_t cls_def_cnt;
2894 uint16_t cat_def_cnt;
2895 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2896};
2897
2898struct objc_class_t {
2899 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2900 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2901 uint32_t name; /* const char * (32-bit pointer) */
2902 int32_t version;
2903 int32_t info;
2904 int32_t instance_size;
2905 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2906 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2907 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2908 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2909};
2910
2911#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2912// class is not a metaclass
2913#define CLS_CLASS 0x1
2914// class is a metaclass
2915#define CLS_META 0x2
2916
2917struct objc_category_t {
2918 uint32_t category_name; /* char * (32-bit pointer) */
2919 uint32_t class_name; /* char * (32-bit pointer) */
2920 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2921 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2922 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2923};
2924
2925struct objc_ivar_t {
2926 uint32_t ivar_name; /* char * (32-bit pointer) */
2927 uint32_t ivar_type; /* char * (32-bit pointer) */
2928 int32_t ivar_offset;
2929};
2930
2931struct objc_ivar_list_t {
2932 int32_t ivar_count;
2933 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2934};
2935
2936struct objc_method_list_t {
2937 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2938 int32_t method_count;
2939 // struct objc_method_t method_list[1]; /* variable length structure */
2940};
2941
2942struct objc_method_t {
2943 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2944 uint32_t method_types; /* char * (32-bit pointer) */
2945 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2946 (32-bit pointer) */
2947};
2948
2949struct objc_protocol_list_t {
2950 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2951 int32_t count;
2952 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2953 // (32-bit pointer) */
2954};
2955
2956struct objc_protocol_t {
2957 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2958 uint32_t protocol_name; /* char * (32-bit pointer) */
2959 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2960 uint32_t instance_methods; /* struct objc_method_description_list *
2961 (32-bit pointer) */
2962 uint32_t class_methods; /* struct objc_method_description_list *
2963 (32-bit pointer) */
2964};
2965
2966struct objc_method_description_list_t {
2967 int32_t count;
2968 // struct objc_method_description_t list[1];
2969};
2970
2971struct objc_method_description_t {
2972 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2973 uint32_t types; /* char * (32-bit pointer) */
2974};
2975
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002976inline void swapStruct(struct cfstring64_t &cfs) {
2977 sys::swapByteOrder(cfs.isa);
2978 sys::swapByteOrder(cfs.flags);
2979 sys::swapByteOrder(cfs.characters);
2980 sys::swapByteOrder(cfs.length);
2981}
2982
2983inline void swapStruct(struct class64_t &c) {
2984 sys::swapByteOrder(c.isa);
2985 sys::swapByteOrder(c.superclass);
2986 sys::swapByteOrder(c.cache);
2987 sys::swapByteOrder(c.vtable);
2988 sys::swapByteOrder(c.data);
2989}
2990
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002991inline void swapStruct(struct class32_t &c) {
2992 sys::swapByteOrder(c.isa);
2993 sys::swapByteOrder(c.superclass);
2994 sys::swapByteOrder(c.cache);
2995 sys::swapByteOrder(c.vtable);
2996 sys::swapByteOrder(c.data);
2997}
2998
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002999inline void swapStruct(struct class_ro64_t &cro) {
3000 sys::swapByteOrder(cro.flags);
3001 sys::swapByteOrder(cro.instanceStart);
3002 sys::swapByteOrder(cro.instanceSize);
3003 sys::swapByteOrder(cro.reserved);
3004 sys::swapByteOrder(cro.ivarLayout);
3005 sys::swapByteOrder(cro.name);
3006 sys::swapByteOrder(cro.baseMethods);
3007 sys::swapByteOrder(cro.baseProtocols);
3008 sys::swapByteOrder(cro.ivars);
3009 sys::swapByteOrder(cro.weakIvarLayout);
3010 sys::swapByteOrder(cro.baseProperties);
3011}
3012
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003013inline void swapStruct(struct class_ro32_t &cro) {
3014 sys::swapByteOrder(cro.flags);
3015 sys::swapByteOrder(cro.instanceStart);
3016 sys::swapByteOrder(cro.instanceSize);
3017 sys::swapByteOrder(cro.ivarLayout);
3018 sys::swapByteOrder(cro.name);
3019 sys::swapByteOrder(cro.baseMethods);
3020 sys::swapByteOrder(cro.baseProtocols);
3021 sys::swapByteOrder(cro.ivars);
3022 sys::swapByteOrder(cro.weakIvarLayout);
3023 sys::swapByteOrder(cro.baseProperties);
3024}
3025
Kevin Enderby0fc11822015-04-01 20:57:01 +00003026inline void swapStruct(struct method_list64_t &ml) {
3027 sys::swapByteOrder(ml.entsize);
3028 sys::swapByteOrder(ml.count);
3029}
3030
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003031inline void swapStruct(struct method_list32_t &ml) {
3032 sys::swapByteOrder(ml.entsize);
3033 sys::swapByteOrder(ml.count);
3034}
3035
Kevin Enderby0fc11822015-04-01 20:57:01 +00003036inline void swapStruct(struct method64_t &m) {
3037 sys::swapByteOrder(m.name);
3038 sys::swapByteOrder(m.types);
3039 sys::swapByteOrder(m.imp);
3040}
3041
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003042inline void swapStruct(struct method32_t &m) {
3043 sys::swapByteOrder(m.name);
3044 sys::swapByteOrder(m.types);
3045 sys::swapByteOrder(m.imp);
3046}
3047
Kevin Enderby0fc11822015-04-01 20:57:01 +00003048inline void swapStruct(struct protocol_list64_t &pl) {
3049 sys::swapByteOrder(pl.count);
3050}
3051
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003052inline void swapStruct(struct protocol_list32_t &pl) {
3053 sys::swapByteOrder(pl.count);
3054}
3055
Kevin Enderby0fc11822015-04-01 20:57:01 +00003056inline void swapStruct(struct protocol64_t &p) {
3057 sys::swapByteOrder(p.isa);
3058 sys::swapByteOrder(p.name);
3059 sys::swapByteOrder(p.protocols);
3060 sys::swapByteOrder(p.instanceMethods);
3061 sys::swapByteOrder(p.classMethods);
3062 sys::swapByteOrder(p.optionalInstanceMethods);
3063 sys::swapByteOrder(p.optionalClassMethods);
3064 sys::swapByteOrder(p.instanceProperties);
3065}
3066
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003067inline void swapStruct(struct protocol32_t &p) {
3068 sys::swapByteOrder(p.isa);
3069 sys::swapByteOrder(p.name);
3070 sys::swapByteOrder(p.protocols);
3071 sys::swapByteOrder(p.instanceMethods);
3072 sys::swapByteOrder(p.classMethods);
3073 sys::swapByteOrder(p.optionalInstanceMethods);
3074 sys::swapByteOrder(p.optionalClassMethods);
3075 sys::swapByteOrder(p.instanceProperties);
3076}
3077
Kevin Enderby0fc11822015-04-01 20:57:01 +00003078inline void swapStruct(struct ivar_list64_t &il) {
3079 sys::swapByteOrder(il.entsize);
3080 sys::swapByteOrder(il.count);
3081}
3082
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003083inline void swapStruct(struct ivar_list32_t &il) {
3084 sys::swapByteOrder(il.entsize);
3085 sys::swapByteOrder(il.count);
3086}
3087
Kevin Enderby0fc11822015-04-01 20:57:01 +00003088inline void swapStruct(struct ivar64_t &i) {
3089 sys::swapByteOrder(i.offset);
3090 sys::swapByteOrder(i.name);
3091 sys::swapByteOrder(i.type);
3092 sys::swapByteOrder(i.alignment);
3093 sys::swapByteOrder(i.size);
3094}
3095
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003096inline void swapStruct(struct ivar32_t &i) {
3097 sys::swapByteOrder(i.offset);
3098 sys::swapByteOrder(i.name);
3099 sys::swapByteOrder(i.type);
3100 sys::swapByteOrder(i.alignment);
3101 sys::swapByteOrder(i.size);
3102}
3103
Kevin Enderby0fc11822015-04-01 20:57:01 +00003104inline void swapStruct(struct objc_property_list64 &pl) {
3105 sys::swapByteOrder(pl.entsize);
3106 sys::swapByteOrder(pl.count);
3107}
3108
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003109inline void swapStruct(struct objc_property_list32 &pl) {
3110 sys::swapByteOrder(pl.entsize);
3111 sys::swapByteOrder(pl.count);
3112}
3113
Kevin Enderby0fc11822015-04-01 20:57:01 +00003114inline void swapStruct(struct objc_property64 &op) {
3115 sys::swapByteOrder(op.name);
3116 sys::swapByteOrder(op.attributes);
3117}
3118
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003119inline void swapStruct(struct objc_property32 &op) {
3120 sys::swapByteOrder(op.name);
3121 sys::swapByteOrder(op.attributes);
3122}
3123
Kevin Enderby0fc11822015-04-01 20:57:01 +00003124inline void swapStruct(struct category64_t &c) {
3125 sys::swapByteOrder(c.name);
3126 sys::swapByteOrder(c.cls);
3127 sys::swapByteOrder(c.instanceMethods);
3128 sys::swapByteOrder(c.classMethods);
3129 sys::swapByteOrder(c.protocols);
3130 sys::swapByteOrder(c.instanceProperties);
3131}
3132
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003133inline void swapStruct(struct category32_t &c) {
3134 sys::swapByteOrder(c.name);
3135 sys::swapByteOrder(c.cls);
3136 sys::swapByteOrder(c.instanceMethods);
3137 sys::swapByteOrder(c.classMethods);
3138 sys::swapByteOrder(c.protocols);
3139 sys::swapByteOrder(c.instanceProperties);
3140}
3141
Kevin Enderby0fc11822015-04-01 20:57:01 +00003142inline void swapStruct(struct objc_image_info64 &o) {
3143 sys::swapByteOrder(o.version);
3144 sys::swapByteOrder(o.flags);
3145}
3146
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003147inline void swapStruct(struct objc_image_info32 &o) {
3148 sys::swapByteOrder(o.version);
3149 sys::swapByteOrder(o.flags);
3150}
3151
Kevin Enderby846c0002015-04-16 17:19:59 +00003152inline void swapStruct(struct imageInfo_t &o) {
3153 sys::swapByteOrder(o.version);
3154 sys::swapByteOrder(o.flags);
3155}
3156
Kevin Enderby0fc11822015-04-01 20:57:01 +00003157inline void swapStruct(struct message_ref64 &mr) {
3158 sys::swapByteOrder(mr.imp);
3159 sys::swapByteOrder(mr.sel);
3160}
3161
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003162inline void swapStruct(struct message_ref32 &mr) {
3163 sys::swapByteOrder(mr.imp);
3164 sys::swapByteOrder(mr.sel);
3165}
3166
Kevin Enderby846c0002015-04-16 17:19:59 +00003167inline void swapStruct(struct objc_module_t &module) {
3168 sys::swapByteOrder(module.version);
3169 sys::swapByteOrder(module.size);
3170 sys::swapByteOrder(module.name);
3171 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003172}
Kevin Enderby846c0002015-04-16 17:19:59 +00003173
3174inline void swapStruct(struct objc_symtab_t &symtab) {
3175 sys::swapByteOrder(symtab.sel_ref_cnt);
3176 sys::swapByteOrder(symtab.refs);
3177 sys::swapByteOrder(symtab.cls_def_cnt);
3178 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003179}
Kevin Enderby846c0002015-04-16 17:19:59 +00003180
3181inline void swapStruct(struct objc_class_t &objc_class) {
3182 sys::swapByteOrder(objc_class.isa);
3183 sys::swapByteOrder(objc_class.super_class);
3184 sys::swapByteOrder(objc_class.name);
3185 sys::swapByteOrder(objc_class.version);
3186 sys::swapByteOrder(objc_class.info);
3187 sys::swapByteOrder(objc_class.instance_size);
3188 sys::swapByteOrder(objc_class.ivars);
3189 sys::swapByteOrder(objc_class.methodLists);
3190 sys::swapByteOrder(objc_class.cache);
3191 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003192}
Kevin Enderby846c0002015-04-16 17:19:59 +00003193
3194inline void swapStruct(struct objc_category_t &objc_category) {
3195 sys::swapByteOrder(objc_category.category_name);
3196 sys::swapByteOrder(objc_category.class_name);
3197 sys::swapByteOrder(objc_category.instance_methods);
3198 sys::swapByteOrder(objc_category.class_methods);
3199 sys::swapByteOrder(objc_category.protocols);
3200}
3201
3202inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3203 sys::swapByteOrder(objc_ivar_list.ivar_count);
3204}
3205
3206inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3207 sys::swapByteOrder(objc_ivar.ivar_name);
3208 sys::swapByteOrder(objc_ivar.ivar_type);
3209 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003210}
Kevin Enderby846c0002015-04-16 17:19:59 +00003211
3212inline void swapStruct(struct objc_method_list_t &method_list) {
3213 sys::swapByteOrder(method_list.obsolete);
3214 sys::swapByteOrder(method_list.method_count);
3215}
3216
3217inline void swapStruct(struct objc_method_t &method) {
3218 sys::swapByteOrder(method.method_name);
3219 sys::swapByteOrder(method.method_types);
3220 sys::swapByteOrder(method.method_imp);
3221}
3222
3223inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3224 sys::swapByteOrder(protocol_list.next);
3225 sys::swapByteOrder(protocol_list.count);
3226}
3227
3228inline void swapStruct(struct objc_protocol_t &protocol) {
3229 sys::swapByteOrder(protocol.isa);
3230 sys::swapByteOrder(protocol.protocol_name);
3231 sys::swapByteOrder(protocol.protocol_list);
3232 sys::swapByteOrder(protocol.instance_methods);
3233 sys::swapByteOrder(protocol.class_methods);
3234}
3235
3236inline void swapStruct(struct objc_method_description_list_t &mdl) {
3237 sys::swapByteOrder(mdl.count);
3238}
3239
3240inline void swapStruct(struct objc_method_description_t &md) {
3241 sys::swapByteOrder(md.name);
3242 sys::swapByteOrder(md.types);
3243}
3244
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003245static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3246 struct DisassembleInfo *info);
3247
3248// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3249// to an Objective-C class and returns the class name. It is also passed the
3250// address of the pointer, so when the pointer is zero as it can be in an .o
3251// file, that is used to look for an external relocation entry with a symbol
3252// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003253static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3254 uint64_t ReferenceValue,
3255 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003256 const char *r;
3257 uint32_t offset, left;
3258 SectionRef S;
3259
3260 // The pointer_value can be 0 in an object file and have a relocation
3261 // entry for the class symbol at the ReferenceValue (the address of the
3262 // pointer).
3263 if (pointer_value == 0) {
3264 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3265 if (r == nullptr || left < sizeof(uint64_t))
3266 return nullptr;
3267 uint64_t n_value;
3268 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3269 if (symbol_name == nullptr)
3270 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003271 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003272 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3273 return class_name + 2;
3274 else
3275 return nullptr;
3276 }
3277
3278 // The case were the pointer_value is non-zero and points to a class defined
3279 // in this Mach-O file.
3280 r = get_pointer_64(pointer_value, offset, left, S, info);
3281 if (r == nullptr || left < sizeof(struct class64_t))
3282 return nullptr;
3283 struct class64_t c;
3284 memcpy(&c, r, sizeof(struct class64_t));
3285 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3286 swapStruct(c);
3287 if (c.data == 0)
3288 return nullptr;
3289 r = get_pointer_64(c.data, offset, left, S, info);
3290 if (r == nullptr || left < sizeof(struct class_ro64_t))
3291 return nullptr;
3292 struct class_ro64_t cro;
3293 memcpy(&cro, r, sizeof(struct class_ro64_t));
3294 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3295 swapStruct(cro);
3296 if (cro.name == 0)
3297 return nullptr;
3298 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3299 return name;
3300}
3301
3302// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3303// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003304static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3305 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003306 const char *r, *name;
3307 uint32_t offset, left;
3308 SectionRef S;
3309 struct cfstring64_t cfs;
3310 uint64_t cfs_characters;
3311
3312 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3313 if (r == nullptr || left < sizeof(struct cfstring64_t))
3314 return nullptr;
3315 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3316 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3317 swapStruct(cfs);
3318 if (cfs.characters == 0) {
3319 uint64_t n_value;
3320 const char *symbol_name = get_symbol_64(
3321 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3322 if (symbol_name == nullptr)
3323 return nullptr;
3324 cfs_characters = n_value;
3325 } else
3326 cfs_characters = cfs.characters;
3327 name = get_pointer_64(cfs_characters, offset, left, S, info);
3328
3329 return name;
3330}
3331
3332// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3333// of a pointer to an Objective-C selector reference when the pointer value is
3334// zero as in a .o file and is likely to have a external relocation entry with
3335// who's symbol's n_value is the real pointer to the selector name. If that is
3336// the case the real pointer to the selector name is returned else 0 is
3337// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003338static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3339 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003340 uint32_t offset, left;
3341 SectionRef S;
3342
3343 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3344 if (r == nullptr || left < sizeof(uint64_t))
3345 return 0;
3346 uint64_t n_value;
3347 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3348 if (symbol_name == nullptr)
3349 return 0;
3350 return n_value;
3351}
3352
Kevin Enderby0fc11822015-04-01 20:57:01 +00003353static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3354 const char *sectname) {
3355 for (const SectionRef &Section : O->sections()) {
3356 StringRef SectName;
3357 Section.getName(SectName);
3358 DataRefImpl Ref = Section.getRawDataRefImpl();
3359 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3360 if (SegName == segname && SectName == sectname)
3361 return Section;
3362 }
3363 return SectionRef();
3364}
3365
3366static void
3367walk_pointer_list_64(const char *listname, const SectionRef S,
3368 MachOObjectFile *O, struct DisassembleInfo *info,
3369 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3370 if (S == SectionRef())
3371 return;
3372
3373 StringRef SectName;
3374 S.getName(SectName);
3375 DataRefImpl Ref = S.getRawDataRefImpl();
3376 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3377 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3378
3379 StringRef BytesStr;
3380 S.getContents(BytesStr);
3381 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3382
3383 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3384 uint32_t left = S.getSize() - i;
3385 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3386 uint64_t p = 0;
3387 memcpy(&p, Contents + i, size);
3388 if (i + sizeof(uint64_t) > S.getSize())
3389 outs() << listname << " list pointer extends past end of (" << SegName
3390 << "," << SectName << ") section\n";
3391 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3392
3393 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3394 sys::swapByteOrder(p);
3395
3396 uint64_t n_value = 0;
3397 const char *name = get_symbol_64(i, S, info, n_value, p);
3398 if (name == nullptr)
3399 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3400
3401 if (n_value != 0) {
3402 outs() << format("0x%" PRIx64, n_value);
3403 if (p != 0)
3404 outs() << " + " << format("0x%" PRIx64, p);
3405 } else
3406 outs() << format("0x%" PRIx64, p);
3407 if (name != nullptr)
3408 outs() << " " << name;
3409 outs() << "\n";
3410
3411 p += n_value;
3412 if (func)
3413 func(p, info);
3414 }
3415}
3416
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003417static void
3418walk_pointer_list_32(const char *listname, const SectionRef S,
3419 MachOObjectFile *O, struct DisassembleInfo *info,
3420 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3421 if (S == SectionRef())
3422 return;
3423
3424 StringRef SectName;
3425 S.getName(SectName);
3426 DataRefImpl Ref = S.getRawDataRefImpl();
3427 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3428 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3429
3430 StringRef BytesStr;
3431 S.getContents(BytesStr);
3432 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3433
3434 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3435 uint32_t left = S.getSize() - i;
3436 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3437 uint32_t p = 0;
3438 memcpy(&p, Contents + i, size);
3439 if (i + sizeof(uint32_t) > S.getSize())
3440 outs() << listname << " list pointer extends past end of (" << SegName
3441 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003442 uint32_t Address = S.getAddress() + i;
3443 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003444
3445 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3446 sys::swapByteOrder(p);
3447 outs() << format("0x%" PRIx32, p);
3448
3449 const char *name = get_symbol_32(i, S, info, p);
3450 if (name != nullptr)
3451 outs() << " " << name;
3452 outs() << "\n";
3453
3454 if (func)
3455 func(p, info);
3456 }
3457}
3458
3459static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003460 if (layout_map == nullptr)
3461 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003462 outs() << " layout map: ";
3463 do {
3464 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3465 left--;
3466 layout_map++;
3467 } while (*layout_map != '\0' && left != 0);
3468 outs() << "\n";
3469}
3470
Kevin Enderby0fc11822015-04-01 20:57:01 +00003471static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3472 uint32_t offset, left;
3473 SectionRef S;
3474 const char *layout_map;
3475
3476 if (p == 0)
3477 return;
3478 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003479 print_layout_map(layout_map, left);
3480}
3481
3482static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3483 uint32_t offset, left;
3484 SectionRef S;
3485 const char *layout_map;
3486
3487 if (p == 0)
3488 return;
3489 layout_map = get_pointer_32(p, offset, left, S, info);
3490 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003491}
3492
3493static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3494 const char *indent) {
3495 struct method_list64_t ml;
3496 struct method64_t m;
3497 const char *r;
3498 uint32_t offset, xoffset, left, i;
3499 SectionRef S, xS;
3500 const char *name, *sym_name;
3501 uint64_t n_value;
3502
3503 r = get_pointer_64(p, offset, left, S, info);
3504 if (r == nullptr)
3505 return;
3506 memset(&ml, '\0', sizeof(struct method_list64_t));
3507 if (left < sizeof(struct method_list64_t)) {
3508 memcpy(&ml, r, left);
3509 outs() << " (method_list_t entends past the end of the section)\n";
3510 } else
3511 memcpy(&ml, r, sizeof(struct method_list64_t));
3512 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3513 swapStruct(ml);
3514 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3515 outs() << indent << "\t\t count " << ml.count << "\n";
3516
3517 p += sizeof(struct method_list64_t);
3518 offset += sizeof(struct method_list64_t);
3519 for (i = 0; i < ml.count; i++) {
3520 r = get_pointer_64(p, offset, left, S, info);
3521 if (r == nullptr)
3522 return;
3523 memset(&m, '\0', sizeof(struct method64_t));
3524 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003525 memcpy(&m, r, left);
3526 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003527 } else
3528 memcpy(&m, r, sizeof(struct method64_t));
3529 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3530 swapStruct(m);
3531
3532 outs() << indent << "\t\t name ";
3533 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3534 info, n_value, m.name);
3535 if (n_value != 0) {
3536 if (info->verbose && sym_name != nullptr)
3537 outs() << sym_name;
3538 else
3539 outs() << format("0x%" PRIx64, n_value);
3540 if (m.name != 0)
3541 outs() << " + " << format("0x%" PRIx64, m.name);
3542 } else
3543 outs() << format("0x%" PRIx64, m.name);
3544 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3545 if (name != nullptr)
3546 outs() << format(" %.*s", left, name);
3547 outs() << "\n";
3548
3549 outs() << indent << "\t\t types ";
3550 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3551 info, n_value, m.types);
3552 if (n_value != 0) {
3553 if (info->verbose && sym_name != nullptr)
3554 outs() << sym_name;
3555 else
3556 outs() << format("0x%" PRIx64, n_value);
3557 if (m.types != 0)
3558 outs() << " + " << format("0x%" PRIx64, m.types);
3559 } else
3560 outs() << format("0x%" PRIx64, m.types);
3561 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3562 if (name != nullptr)
3563 outs() << format(" %.*s", left, name);
3564 outs() << "\n";
3565
3566 outs() << indent << "\t\t imp ";
3567 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3568 n_value, m.imp);
3569 if (info->verbose && name == nullptr) {
3570 if (n_value != 0) {
3571 outs() << format("0x%" PRIx64, n_value) << " ";
3572 if (m.imp != 0)
3573 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3574 } else
3575 outs() << format("0x%" PRIx64, m.imp) << " ";
3576 }
3577 if (name != nullptr)
3578 outs() << name;
3579 outs() << "\n";
3580
3581 p += sizeof(struct method64_t);
3582 offset += sizeof(struct method64_t);
3583 }
3584}
3585
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003586static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3587 const char *indent) {
3588 struct method_list32_t ml;
3589 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003590 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003591 uint32_t offset, xoffset, left, i;
3592 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003593
3594 r = get_pointer_32(p, offset, left, S, info);
3595 if (r == nullptr)
3596 return;
3597 memset(&ml, '\0', sizeof(struct method_list32_t));
3598 if (left < sizeof(struct method_list32_t)) {
3599 memcpy(&ml, r, left);
3600 outs() << " (method_list_t entends past the end of the section)\n";
3601 } else
3602 memcpy(&ml, r, sizeof(struct method_list32_t));
3603 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3604 swapStruct(ml);
3605 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3606 outs() << indent << "\t\t count " << ml.count << "\n";
3607
3608 p += sizeof(struct method_list32_t);
3609 offset += sizeof(struct method_list32_t);
3610 for (i = 0; i < ml.count; i++) {
3611 r = get_pointer_32(p, offset, left, S, info);
3612 if (r == nullptr)
3613 return;
3614 memset(&m, '\0', sizeof(struct method32_t));
3615 if (left < sizeof(struct method32_t)) {
3616 memcpy(&ml, r, left);
3617 outs() << indent << " (method_t entends past the end of the section)\n";
3618 } else
3619 memcpy(&m, r, sizeof(struct method32_t));
3620 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3621 swapStruct(m);
3622
3623 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3624 name = get_pointer_32(m.name, xoffset, left, xS, info);
3625 if (name != nullptr)
3626 outs() << format(" %.*s", left, name);
3627 outs() << "\n";
3628
3629 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3630 name = get_pointer_32(m.types, xoffset, left, xS, info);
3631 if (name != nullptr)
3632 outs() << format(" %.*s", left, name);
3633 outs() << "\n";
3634
3635 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3636 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3637 m.imp);
3638 if (name != nullptr)
3639 outs() << " " << name;
3640 outs() << "\n";
3641
3642 p += sizeof(struct method32_t);
3643 offset += sizeof(struct method32_t);
3644 }
3645}
3646
Kevin Enderby846c0002015-04-16 17:19:59 +00003647static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3648 uint32_t offset, left, xleft;
3649 SectionRef S;
3650 struct objc_method_list_t method_list;
3651 struct objc_method_t method;
3652 const char *r, *methods, *name, *SymbolName;
3653 int32_t i;
3654
3655 r = get_pointer_32(p, offset, left, S, info, true);
3656 if (r == nullptr)
3657 return true;
3658
3659 outs() << "\n";
3660 if (left > sizeof(struct objc_method_list_t)) {
3661 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3662 } else {
3663 outs() << "\t\t objc_method_list extends past end of the section\n";
3664 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3665 memcpy(&method_list, r, left);
3666 }
3667 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3668 swapStruct(method_list);
3669
3670 outs() << "\t\t obsolete "
3671 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3672 outs() << "\t\t method_count " << method_list.method_count << "\n";
3673
3674 methods = r + sizeof(struct objc_method_list_t);
3675 for (i = 0; i < method_list.method_count; i++) {
3676 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3677 outs() << "\t\t remaining method's extend past the of the section\n";
3678 break;
3679 }
3680 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3681 sizeof(struct objc_method_t));
3682 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3683 swapStruct(method);
3684
3685 outs() << "\t\t method_name "
3686 << format("0x%08" PRIx32, method.method_name);
3687 if (info->verbose) {
3688 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3689 if (name != nullptr)
3690 outs() << format(" %.*s", xleft, name);
3691 else
3692 outs() << " (not in an __OBJC section)";
3693 }
3694 outs() << "\n";
3695
3696 outs() << "\t\t method_types "
3697 << format("0x%08" PRIx32, method.method_types);
3698 if (info->verbose) {
3699 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3700 if (name != nullptr)
3701 outs() << format(" %.*s", xleft, name);
3702 else
3703 outs() << " (not in an __OBJC section)";
3704 }
3705 outs() << "\n";
3706
3707 outs() << "\t\t method_imp "
3708 << format("0x%08" PRIx32, method.method_imp) << " ";
3709 if (info->verbose) {
3710 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3711 if (SymbolName != nullptr)
3712 outs() << SymbolName;
3713 }
3714 outs() << "\n";
3715 }
3716 return false;
3717}
3718
Kevin Enderby0fc11822015-04-01 20:57:01 +00003719static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3720 struct protocol_list64_t pl;
3721 uint64_t q, n_value;
3722 struct protocol64_t pc;
3723 const char *r;
3724 uint32_t offset, xoffset, left, i;
3725 SectionRef S, xS;
3726 const char *name, *sym_name;
3727
3728 r = get_pointer_64(p, offset, left, S, info);
3729 if (r == nullptr)
3730 return;
3731 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3732 if (left < sizeof(struct protocol_list64_t)) {
3733 memcpy(&pl, r, left);
3734 outs() << " (protocol_list_t entends past the end of the section)\n";
3735 } else
3736 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3737 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3738 swapStruct(pl);
3739 outs() << " count " << pl.count << "\n";
3740
3741 p += sizeof(struct protocol_list64_t);
3742 offset += sizeof(struct protocol_list64_t);
3743 for (i = 0; i < pl.count; i++) {
3744 r = get_pointer_64(p, offset, left, S, info);
3745 if (r == nullptr)
3746 return;
3747 q = 0;
3748 if (left < sizeof(uint64_t)) {
3749 memcpy(&q, r, left);
3750 outs() << " (protocol_t * entends past the end of the section)\n";
3751 } else
3752 memcpy(&q, r, sizeof(uint64_t));
3753 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3754 sys::swapByteOrder(q);
3755
3756 outs() << "\t\t list[" << i << "] ";
3757 sym_name = get_symbol_64(offset, S, info, n_value, q);
3758 if (n_value != 0) {
3759 if (info->verbose && sym_name != nullptr)
3760 outs() << sym_name;
3761 else
3762 outs() << format("0x%" PRIx64, n_value);
3763 if (q != 0)
3764 outs() << " + " << format("0x%" PRIx64, q);
3765 } else
3766 outs() << format("0x%" PRIx64, q);
3767 outs() << " (struct protocol_t *)\n";
3768
3769 r = get_pointer_64(q + n_value, offset, left, S, info);
3770 if (r == nullptr)
3771 return;
3772 memset(&pc, '\0', sizeof(struct protocol64_t));
3773 if (left < sizeof(struct protocol64_t)) {
3774 memcpy(&pc, r, left);
3775 outs() << " (protocol_t entends past the end of the section)\n";
3776 } else
3777 memcpy(&pc, r, sizeof(struct protocol64_t));
3778 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3779 swapStruct(pc);
3780
3781 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3782
3783 outs() << "\t\t\t name ";
3784 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3785 info, n_value, pc.name);
3786 if (n_value != 0) {
3787 if (info->verbose && sym_name != nullptr)
3788 outs() << sym_name;
3789 else
3790 outs() << format("0x%" PRIx64, n_value);
3791 if (pc.name != 0)
3792 outs() << " + " << format("0x%" PRIx64, pc.name);
3793 } else
3794 outs() << format("0x%" PRIx64, pc.name);
3795 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3796 if (name != nullptr)
3797 outs() << format(" %.*s", left, name);
3798 outs() << "\n";
3799
3800 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3801
3802 outs() << "\t\t instanceMethods ";
3803 sym_name =
3804 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3805 S, info, n_value, pc.instanceMethods);
3806 if (n_value != 0) {
3807 if (info->verbose && sym_name != nullptr)
3808 outs() << sym_name;
3809 else
3810 outs() << format("0x%" PRIx64, n_value);
3811 if (pc.instanceMethods != 0)
3812 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3813 } else
3814 outs() << format("0x%" PRIx64, pc.instanceMethods);
3815 outs() << " (struct method_list_t *)\n";
3816 if (pc.instanceMethods + n_value != 0)
3817 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3818
3819 outs() << "\t\t classMethods ";
3820 sym_name =
3821 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3822 info, n_value, pc.classMethods);
3823 if (n_value != 0) {
3824 if (info->verbose && sym_name != nullptr)
3825 outs() << sym_name;
3826 else
3827 outs() << format("0x%" PRIx64, n_value);
3828 if (pc.classMethods != 0)
3829 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3830 } else
3831 outs() << format("0x%" PRIx64, pc.classMethods);
3832 outs() << " (struct method_list_t *)\n";
3833 if (pc.classMethods + n_value != 0)
3834 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3835
3836 outs() << "\t optionalInstanceMethods "
3837 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3838 outs() << "\t optionalClassMethods "
3839 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3840 outs() << "\t instanceProperties "
3841 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3842
3843 p += sizeof(uint64_t);
3844 offset += sizeof(uint64_t);
3845 }
3846}
3847
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003848static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3849 struct protocol_list32_t pl;
3850 uint32_t q;
3851 struct protocol32_t pc;
3852 const char *r;
3853 uint32_t offset, xoffset, left, i;
3854 SectionRef S, xS;
3855 const char *name;
3856
3857 r = get_pointer_32(p, offset, left, S, info);
3858 if (r == nullptr)
3859 return;
3860 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3861 if (left < sizeof(struct protocol_list32_t)) {
3862 memcpy(&pl, r, left);
3863 outs() << " (protocol_list_t entends past the end of the section)\n";
3864 } else
3865 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3866 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3867 swapStruct(pl);
3868 outs() << " count " << pl.count << "\n";
3869
3870 p += sizeof(struct protocol_list32_t);
3871 offset += sizeof(struct protocol_list32_t);
3872 for (i = 0; i < pl.count; i++) {
3873 r = get_pointer_32(p, offset, left, S, info);
3874 if (r == nullptr)
3875 return;
3876 q = 0;
3877 if (left < sizeof(uint32_t)) {
3878 memcpy(&q, r, left);
3879 outs() << " (protocol_t * entends past the end of the section)\n";
3880 } else
3881 memcpy(&q, r, sizeof(uint32_t));
3882 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3883 sys::swapByteOrder(q);
3884 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3885 << " (struct protocol_t *)\n";
3886 r = get_pointer_32(q, offset, left, S, info);
3887 if (r == nullptr)
3888 return;
3889 memset(&pc, '\0', sizeof(struct protocol32_t));
3890 if (left < sizeof(struct protocol32_t)) {
3891 memcpy(&pc, r, left);
3892 outs() << " (protocol_t entends past the end of the section)\n";
3893 } else
3894 memcpy(&pc, r, sizeof(struct protocol32_t));
3895 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3896 swapStruct(pc);
3897 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3898 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3899 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3900 if (name != nullptr)
3901 outs() << format(" %.*s", left, name);
3902 outs() << "\n";
3903 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3904 outs() << "\t\t instanceMethods "
3905 << format("0x%" PRIx32, pc.instanceMethods)
3906 << " (struct method_list_t *)\n";
3907 if (pc.instanceMethods != 0)
3908 print_method_list32_t(pc.instanceMethods, info, "\t");
3909 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3910 << " (struct method_list_t *)\n";
3911 if (pc.classMethods != 0)
3912 print_method_list32_t(pc.classMethods, info, "\t");
3913 outs() << "\t optionalInstanceMethods "
3914 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3915 outs() << "\t optionalClassMethods "
3916 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3917 outs() << "\t instanceProperties "
3918 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3919 p += sizeof(uint32_t);
3920 offset += sizeof(uint32_t);
3921 }
3922}
3923
Kevin Enderby846c0002015-04-16 17:19:59 +00003924static void print_indent(uint32_t indent) {
3925 for (uint32_t i = 0; i < indent;) {
3926 if (indent - i >= 8) {
3927 outs() << "\t";
3928 i += 8;
3929 } else {
3930 for (uint32_t j = i; j < indent; j++)
3931 outs() << " ";
3932 return;
3933 }
3934 }
3935}
3936
3937static bool print_method_description_list(uint32_t p, uint32_t indent,
3938 struct DisassembleInfo *info) {
3939 uint32_t offset, left, xleft;
3940 SectionRef S;
3941 struct objc_method_description_list_t mdl;
3942 struct objc_method_description_t md;
3943 const char *r, *list, *name;
3944 int32_t i;
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_method_description_list_t)) {
3952 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3953 } else {
3954 print_indent(indent);
3955 outs() << " objc_method_description_list extends past end of the section\n";
3956 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3957 memcpy(&mdl, r, left);
3958 }
3959 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3960 swapStruct(mdl);
3961
3962 print_indent(indent);
3963 outs() << " count " << mdl.count << "\n";
3964
3965 list = r + sizeof(struct objc_method_description_list_t);
3966 for (i = 0; i < mdl.count; i++) {
3967 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3968 print_indent(indent);
3969 outs() << " remaining list entries extend past the of the section\n";
3970 break;
3971 }
3972 print_indent(indent);
3973 outs() << " list[" << i << "]\n";
3974 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3975 sizeof(struct objc_method_description_t));
3976 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3977 swapStruct(md);
3978
3979 print_indent(indent);
3980 outs() << " name " << format("0x%08" PRIx32, md.name);
3981 if (info->verbose) {
3982 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3983 if (name != nullptr)
3984 outs() << format(" %.*s", xleft, name);
3985 else
3986 outs() << " (not in an __OBJC section)";
3987 }
3988 outs() << "\n";
3989
3990 print_indent(indent);
3991 outs() << " types " << format("0x%08" PRIx32, md.types);
3992 if (info->verbose) {
3993 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3994 if (name != nullptr)
3995 outs() << format(" %.*s", xleft, name);
3996 else
3997 outs() << " (not in an __OBJC section)";
3998 }
3999 outs() << "\n";
4000 }
4001 return false;
4002}
4003
4004static bool print_protocol_list(uint32_t p, uint32_t indent,
4005 struct DisassembleInfo *info);
4006
4007static bool print_protocol(uint32_t p, uint32_t indent,
4008 struct DisassembleInfo *info) {
4009 uint32_t offset, left;
4010 SectionRef S;
4011 struct objc_protocol_t protocol;
4012 const char *r, *name;
4013
4014 r = get_pointer_32(p, offset, left, S, info, true);
4015 if (r == nullptr)
4016 return true;
4017
4018 outs() << "\n";
4019 if (left >= sizeof(struct objc_protocol_t)) {
4020 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4021 } else {
4022 print_indent(indent);
4023 outs() << " Protocol extends past end of the section\n";
4024 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4025 memcpy(&protocol, r, left);
4026 }
4027 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4028 swapStruct(protocol);
4029
4030 print_indent(indent);
4031 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4032 << "\n";
4033
4034 print_indent(indent);
4035 outs() << " protocol_name "
4036 << format("0x%08" PRIx32, protocol.protocol_name);
4037 if (info->verbose) {
4038 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4039 if (name != nullptr)
4040 outs() << format(" %.*s", left, name);
4041 else
4042 outs() << " (not in an __OBJC section)";
4043 }
4044 outs() << "\n";
4045
4046 print_indent(indent);
4047 outs() << " protocol_list "
4048 << format("0x%08" PRIx32, protocol.protocol_list);
4049 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4050 outs() << " (not in an __OBJC section)\n";
4051
4052 print_indent(indent);
4053 outs() << " instance_methods "
4054 << format("0x%08" PRIx32, protocol.instance_methods);
4055 if (print_method_description_list(protocol.instance_methods, indent, info))
4056 outs() << " (not in an __OBJC section)\n";
4057
4058 print_indent(indent);
4059 outs() << " class_methods "
4060 << format("0x%08" PRIx32, protocol.class_methods);
4061 if (print_method_description_list(protocol.class_methods, indent, info))
4062 outs() << " (not in an __OBJC section)\n";
4063
4064 return false;
4065}
4066
4067static bool print_protocol_list(uint32_t p, uint32_t indent,
4068 struct DisassembleInfo *info) {
4069 uint32_t offset, left, l;
4070 SectionRef S;
4071 struct objc_protocol_list_t protocol_list;
4072 const char *r, *list;
4073 int32_t i;
4074
4075 r = get_pointer_32(p, offset, left, S, info, true);
4076 if (r == nullptr)
4077 return true;
4078
4079 outs() << "\n";
4080 if (left > sizeof(struct objc_protocol_list_t)) {
4081 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4082 } else {
4083 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4084 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4085 memcpy(&protocol_list, r, left);
4086 }
4087 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4088 swapStruct(protocol_list);
4089
4090 print_indent(indent);
4091 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4092 << "\n";
4093 print_indent(indent);
4094 outs() << " count " << protocol_list.count << "\n";
4095
4096 list = r + sizeof(struct objc_protocol_list_t);
4097 for (i = 0; i < protocol_list.count; i++) {
4098 if ((i + 1) * sizeof(uint32_t) > left) {
4099 outs() << "\t\t remaining list entries extend past the of the section\n";
4100 break;
4101 }
4102 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4103 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4104 sys::swapByteOrder(l);
4105
4106 print_indent(indent);
4107 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4108 if (print_protocol(l, indent, info))
4109 outs() << "(not in an __OBJC section)\n";
4110 }
4111 return false;
4112}
4113
Kevin Enderby0fc11822015-04-01 20:57:01 +00004114static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4115 struct ivar_list64_t il;
4116 struct ivar64_t i;
4117 const char *r;
4118 uint32_t offset, xoffset, left, j;
4119 SectionRef S, xS;
4120 const char *name, *sym_name, *ivar_offset_p;
4121 uint64_t ivar_offset, n_value;
4122
4123 r = get_pointer_64(p, offset, left, S, info);
4124 if (r == nullptr)
4125 return;
4126 memset(&il, '\0', sizeof(struct ivar_list64_t));
4127 if (left < sizeof(struct ivar_list64_t)) {
4128 memcpy(&il, r, left);
4129 outs() << " (ivar_list_t entends past the end of the section)\n";
4130 } else
4131 memcpy(&il, r, sizeof(struct ivar_list64_t));
4132 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4133 swapStruct(il);
4134 outs() << " entsize " << il.entsize << "\n";
4135 outs() << " count " << il.count << "\n";
4136
4137 p += sizeof(struct ivar_list64_t);
4138 offset += sizeof(struct ivar_list64_t);
4139 for (j = 0; j < il.count; j++) {
4140 r = get_pointer_64(p, offset, left, S, info);
4141 if (r == nullptr)
4142 return;
4143 memset(&i, '\0', sizeof(struct ivar64_t));
4144 if (left < sizeof(struct ivar64_t)) {
4145 memcpy(&i, r, left);
4146 outs() << " (ivar_t entends past the end of the section)\n";
4147 } else
4148 memcpy(&i, r, sizeof(struct ivar64_t));
4149 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4150 swapStruct(i);
4151
4152 outs() << "\t\t\t offset ";
4153 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4154 info, n_value, i.offset);
4155 if (n_value != 0) {
4156 if (info->verbose && sym_name != nullptr)
4157 outs() << sym_name;
4158 else
4159 outs() << format("0x%" PRIx64, n_value);
4160 if (i.offset != 0)
4161 outs() << " + " << format("0x%" PRIx64, i.offset);
4162 } else
4163 outs() << format("0x%" PRIx64, i.offset);
4164 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4165 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4166 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4167 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4168 sys::swapByteOrder(ivar_offset);
4169 outs() << " " << ivar_offset << "\n";
4170 } else
4171 outs() << "\n";
4172
4173 outs() << "\t\t\t name ";
4174 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4175 n_value, i.name);
4176 if (n_value != 0) {
4177 if (info->verbose && sym_name != nullptr)
4178 outs() << sym_name;
4179 else
4180 outs() << format("0x%" PRIx64, n_value);
4181 if (i.name != 0)
4182 outs() << " + " << format("0x%" PRIx64, i.name);
4183 } else
4184 outs() << format("0x%" PRIx64, i.name);
4185 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4186 if (name != nullptr)
4187 outs() << format(" %.*s", left, name);
4188 outs() << "\n";
4189
4190 outs() << "\t\t\t type ";
4191 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4192 n_value, i.name);
4193 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4194 if (n_value != 0) {
4195 if (info->verbose && sym_name != nullptr)
4196 outs() << sym_name;
4197 else
4198 outs() << format("0x%" PRIx64, n_value);
4199 if (i.type != 0)
4200 outs() << " + " << format("0x%" PRIx64, i.type);
4201 } else
4202 outs() << format("0x%" PRIx64, i.type);
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 ivar64_t);
4211 offset += sizeof(struct ivar64_t);
4212 }
4213}
4214
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004215static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4216 struct ivar_list32_t il;
4217 struct ivar32_t i;
4218 const char *r;
4219 uint32_t offset, xoffset, left, j;
4220 SectionRef S, xS;
4221 const char *name, *ivar_offset_p;
4222 uint32_t ivar_offset;
4223
4224 r = get_pointer_32(p, offset, left, S, info);
4225 if (r == nullptr)
4226 return;
4227 memset(&il, '\0', sizeof(struct ivar_list32_t));
4228 if (left < sizeof(struct ivar_list32_t)) {
4229 memcpy(&il, r, left);
4230 outs() << " (ivar_list_t entends past the end of the section)\n";
4231 } else
4232 memcpy(&il, r, sizeof(struct ivar_list32_t));
4233 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4234 swapStruct(il);
4235 outs() << " entsize " << il.entsize << "\n";
4236 outs() << " count " << il.count << "\n";
4237
4238 p += sizeof(struct ivar_list32_t);
4239 offset += sizeof(struct ivar_list32_t);
4240 for (j = 0; j < il.count; j++) {
4241 r = get_pointer_32(p, offset, left, S, info);
4242 if (r == nullptr)
4243 return;
4244 memset(&i, '\0', sizeof(struct ivar32_t));
4245 if (left < sizeof(struct ivar32_t)) {
4246 memcpy(&i, r, left);
4247 outs() << " (ivar_t entends past the end of the section)\n";
4248 } else
4249 memcpy(&i, r, sizeof(struct ivar32_t));
4250 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4251 swapStruct(i);
4252
4253 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4254 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4255 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4256 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4257 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4258 sys::swapByteOrder(ivar_offset);
4259 outs() << " " << ivar_offset << "\n";
4260 } else
4261 outs() << "\n";
4262
4263 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4264 name = get_pointer_32(i.name, xoffset, left, xS, info);
4265 if (name != nullptr)
4266 outs() << format(" %.*s", left, name);
4267 outs() << "\n";
4268
4269 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4270 name = get_pointer_32(i.type, xoffset, left, xS, info);
4271 if (name != nullptr)
4272 outs() << format(" %.*s", left, name);
4273 outs() << "\n";
4274
4275 outs() << "\t\t\talignment " << i.alignment << "\n";
4276 outs() << "\t\t\t size " << i.size << "\n";
4277
4278 p += sizeof(struct ivar32_t);
4279 offset += sizeof(struct ivar32_t);
4280 }
4281}
4282
Kevin Enderby0fc11822015-04-01 20:57:01 +00004283static void print_objc_property_list64(uint64_t p,
4284 struct DisassembleInfo *info) {
4285 struct objc_property_list64 opl;
4286 struct objc_property64 op;
4287 const char *r;
4288 uint32_t offset, xoffset, left, j;
4289 SectionRef S, xS;
4290 const char *name, *sym_name;
4291 uint64_t n_value;
4292
4293 r = get_pointer_64(p, offset, left, S, info);
4294 if (r == nullptr)
4295 return;
4296 memset(&opl, '\0', sizeof(struct objc_property_list64));
4297 if (left < sizeof(struct objc_property_list64)) {
4298 memcpy(&opl, r, left);
4299 outs() << " (objc_property_list entends past the end of the section)\n";
4300 } else
4301 memcpy(&opl, r, sizeof(struct objc_property_list64));
4302 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4303 swapStruct(opl);
4304 outs() << " entsize " << opl.entsize << "\n";
4305 outs() << " count " << opl.count << "\n";
4306
4307 p += sizeof(struct objc_property_list64);
4308 offset += sizeof(struct objc_property_list64);
4309 for (j = 0; j < opl.count; j++) {
4310 r = get_pointer_64(p, offset, left, S, info);
4311 if (r == nullptr)
4312 return;
4313 memset(&op, '\0', sizeof(struct objc_property64));
4314 if (left < sizeof(struct objc_property64)) {
4315 memcpy(&op, r, left);
4316 outs() << " (objc_property entends past the end of the section)\n";
4317 } else
4318 memcpy(&op, r, sizeof(struct objc_property64));
4319 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4320 swapStruct(op);
4321
4322 outs() << "\t\t\t name ";
4323 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4324 info, n_value, op.name);
4325 if (n_value != 0) {
4326 if (info->verbose && sym_name != nullptr)
4327 outs() << sym_name;
4328 else
4329 outs() << format("0x%" PRIx64, n_value);
4330 if (op.name != 0)
4331 outs() << " + " << format("0x%" PRIx64, op.name);
4332 } else
4333 outs() << format("0x%" PRIx64, op.name);
4334 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4335 if (name != nullptr)
4336 outs() << format(" %.*s", left, name);
4337 outs() << "\n";
4338
4339 outs() << "\t\t\tattributes ";
4340 sym_name =
4341 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4342 info, n_value, op.attributes);
4343 if (n_value != 0) {
4344 if (info->verbose && sym_name != nullptr)
4345 outs() << sym_name;
4346 else
4347 outs() << format("0x%" PRIx64, n_value);
4348 if (op.attributes != 0)
4349 outs() << " + " << format("0x%" PRIx64, op.attributes);
4350 } else
4351 outs() << format("0x%" PRIx64, op.attributes);
4352 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4353 if (name != nullptr)
4354 outs() << format(" %.*s", left, name);
4355 outs() << "\n";
4356
4357 p += sizeof(struct objc_property64);
4358 offset += sizeof(struct objc_property64);
4359 }
4360}
4361
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004362static void print_objc_property_list32(uint32_t p,
4363 struct DisassembleInfo *info) {
4364 struct objc_property_list32 opl;
4365 struct objc_property32 op;
4366 const char *r;
4367 uint32_t offset, xoffset, left, j;
4368 SectionRef S, xS;
4369 const char *name;
4370
4371 r = get_pointer_32(p, offset, left, S, info);
4372 if (r == nullptr)
4373 return;
4374 memset(&opl, '\0', sizeof(struct objc_property_list32));
4375 if (left < sizeof(struct objc_property_list32)) {
4376 memcpy(&opl, r, left);
4377 outs() << " (objc_property_list entends past the end of the section)\n";
4378 } else
4379 memcpy(&opl, r, sizeof(struct objc_property_list32));
4380 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4381 swapStruct(opl);
4382 outs() << " entsize " << opl.entsize << "\n";
4383 outs() << " count " << opl.count << "\n";
4384
4385 p += sizeof(struct objc_property_list32);
4386 offset += sizeof(struct objc_property_list32);
4387 for (j = 0; j < opl.count; j++) {
4388 r = get_pointer_32(p, offset, left, S, info);
4389 if (r == nullptr)
4390 return;
4391 memset(&op, '\0', sizeof(struct objc_property32));
4392 if (left < sizeof(struct objc_property32)) {
4393 memcpy(&op, r, left);
4394 outs() << " (objc_property entends past the end of the section)\n";
4395 } else
4396 memcpy(&op, r, sizeof(struct objc_property32));
4397 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4398 swapStruct(op);
4399
4400 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4401 name = get_pointer_32(op.name, xoffset, left, xS, info);
4402 if (name != nullptr)
4403 outs() << format(" %.*s", left, name);
4404 outs() << "\n";
4405
4406 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4407 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4408 if (name != nullptr)
4409 outs() << format(" %.*s", left, name);
4410 outs() << "\n";
4411
4412 p += sizeof(struct objc_property32);
4413 offset += sizeof(struct objc_property32);
4414 }
4415}
4416
Richard Smith81ff44d2015-10-09 22:09:56 +00004417static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004418 bool &is_meta_class) {
4419 struct class_ro64_t cro;
4420 const char *r;
4421 uint32_t offset, xoffset, left;
4422 SectionRef S, xS;
4423 const char *name, *sym_name;
4424 uint64_t n_value;
4425
4426 r = get_pointer_64(p, offset, left, S, info);
4427 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004428 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004429 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004430 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4431 swapStruct(cro);
4432 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4433 if (cro.flags & RO_META)
4434 outs() << " RO_META";
4435 if (cro.flags & RO_ROOT)
4436 outs() << " RO_ROOT";
4437 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4438 outs() << " RO_HAS_CXX_STRUCTORS";
4439 outs() << "\n";
4440 outs() << " instanceStart " << cro.instanceStart << "\n";
4441 outs() << " instanceSize " << cro.instanceSize << "\n";
4442 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4443 << "\n";
4444 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4445 << "\n";
4446 print_layout_map64(cro.ivarLayout, info);
4447
4448 outs() << " name ";
4449 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4450 info, n_value, cro.name);
4451 if (n_value != 0) {
4452 if (info->verbose && sym_name != nullptr)
4453 outs() << sym_name;
4454 else
4455 outs() << format("0x%" PRIx64, n_value);
4456 if (cro.name != 0)
4457 outs() << " + " << format("0x%" PRIx64, cro.name);
4458 } else
4459 outs() << format("0x%" PRIx64, cro.name);
4460 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4461 if (name != nullptr)
4462 outs() << format(" %.*s", left, name);
4463 outs() << "\n";
4464
4465 outs() << " baseMethods ";
4466 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4467 S, info, n_value, cro.baseMethods);
4468 if (n_value != 0) {
4469 if (info->verbose && sym_name != nullptr)
4470 outs() << sym_name;
4471 else
4472 outs() << format("0x%" PRIx64, n_value);
4473 if (cro.baseMethods != 0)
4474 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4475 } else
4476 outs() << format("0x%" PRIx64, cro.baseMethods);
4477 outs() << " (struct method_list_t *)\n";
4478 if (cro.baseMethods + n_value != 0)
4479 print_method_list64_t(cro.baseMethods + n_value, info, "");
4480
4481 outs() << " baseProtocols ";
4482 sym_name =
4483 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4484 info, n_value, cro.baseProtocols);
4485 if (n_value != 0) {
4486 if (info->verbose && sym_name != nullptr)
4487 outs() << sym_name;
4488 else
4489 outs() << format("0x%" PRIx64, n_value);
4490 if (cro.baseProtocols != 0)
4491 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4492 } else
4493 outs() << format("0x%" PRIx64, cro.baseProtocols);
4494 outs() << "\n";
4495 if (cro.baseProtocols + n_value != 0)
4496 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4497
4498 outs() << " ivars ";
4499 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004500 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004501 if (n_value != 0) {
4502 if (info->verbose && sym_name != nullptr)
4503 outs() << sym_name;
4504 else
4505 outs() << format("0x%" PRIx64, n_value);
4506 if (cro.ivars != 0)
4507 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4508 } else
4509 outs() << format("0x%" PRIx64, cro.ivars);
4510 outs() << "\n";
4511 if (cro.ivars + n_value != 0)
4512 print_ivar_list64_t(cro.ivars + n_value, info);
4513
4514 outs() << " weakIvarLayout ";
4515 sym_name =
4516 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4517 info, n_value, cro.weakIvarLayout);
4518 if (n_value != 0) {
4519 if (info->verbose && sym_name != nullptr)
4520 outs() << sym_name;
4521 else
4522 outs() << format("0x%" PRIx64, n_value);
4523 if (cro.weakIvarLayout != 0)
4524 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4525 } else
4526 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4527 outs() << "\n";
4528 print_layout_map64(cro.weakIvarLayout + n_value, info);
4529
4530 outs() << " baseProperties ";
4531 sym_name =
4532 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4533 info, n_value, cro.baseProperties);
4534 if (n_value != 0) {
4535 if (info->verbose && sym_name != nullptr)
4536 outs() << sym_name;
4537 else
4538 outs() << format("0x%" PRIx64, n_value);
4539 if (cro.baseProperties != 0)
4540 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4541 } else
4542 outs() << format("0x%" PRIx64, cro.baseProperties);
4543 outs() << "\n";
4544 if (cro.baseProperties + n_value != 0)
4545 print_objc_property_list64(cro.baseProperties + n_value, info);
4546
Rafael Espindolab9091322015-10-24 23:19:10 +00004547 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004548 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004549}
4550
Richard Smith81ff44d2015-10-09 22:09:56 +00004551static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004552 bool &is_meta_class) {
4553 struct class_ro32_t cro;
4554 const char *r;
4555 uint32_t offset, xoffset, left;
4556 SectionRef S, xS;
4557 const char *name;
4558
4559 r = get_pointer_32(p, offset, left, S, info);
4560 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004561 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004562 memset(&cro, '\0', sizeof(struct class_ro32_t));
4563 if (left < sizeof(struct class_ro32_t)) {
4564 memcpy(&cro, r, left);
4565 outs() << " (class_ro_t entends past the end of the section)\n";
4566 } else
4567 memcpy(&cro, r, sizeof(struct class_ro32_t));
4568 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4569 swapStruct(cro);
4570 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4571 if (cro.flags & RO_META)
4572 outs() << " RO_META";
4573 if (cro.flags & RO_ROOT)
4574 outs() << " RO_ROOT";
4575 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4576 outs() << " RO_HAS_CXX_STRUCTORS";
4577 outs() << "\n";
4578 outs() << " instanceStart " << cro.instanceStart << "\n";
4579 outs() << " instanceSize " << cro.instanceSize << "\n";
4580 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4581 << "\n";
4582 print_layout_map32(cro.ivarLayout, info);
4583
4584 outs() << " name " << format("0x%" PRIx32, cro.name);
4585 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4586 if (name != nullptr)
4587 outs() << format(" %.*s", left, name);
4588 outs() << "\n";
4589
4590 outs() << " baseMethods "
4591 << format("0x%" PRIx32, cro.baseMethods)
4592 << " (struct method_list_t *)\n";
4593 if (cro.baseMethods != 0)
4594 print_method_list32_t(cro.baseMethods, info, "");
4595
4596 outs() << " baseProtocols "
4597 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4598 if (cro.baseProtocols != 0)
4599 print_protocol_list32_t(cro.baseProtocols, info);
4600 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4601 << "\n";
4602 if (cro.ivars != 0)
4603 print_ivar_list32_t(cro.ivars, info);
4604 outs() << " weakIvarLayout "
4605 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4606 print_layout_map32(cro.weakIvarLayout, info);
4607 outs() << " baseProperties "
4608 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4609 if (cro.baseProperties != 0)
4610 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004611 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004612 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004613}
4614
Kevin Enderby0fc11822015-04-01 20:57:01 +00004615static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4616 struct class64_t c;
4617 const char *r;
4618 uint32_t offset, left;
4619 SectionRef S;
4620 const char *name;
4621 uint64_t isa_n_value, n_value;
4622
4623 r = get_pointer_64(p, offset, left, S, info);
4624 if (r == nullptr || left < sizeof(struct class64_t))
4625 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004626 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004627 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4628 swapStruct(c);
4629
4630 outs() << " isa " << format("0x%" PRIx64, c.isa);
4631 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4632 isa_n_value, c.isa);
4633 if (name != nullptr)
4634 outs() << " " << name;
4635 outs() << "\n";
4636
4637 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4638 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4639 n_value, c.superclass);
4640 if (name != nullptr)
4641 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00004642 else {
4643 name = get_dyld_bind_info_symbolname(S.getAddress() +
4644 offset + offsetof(struct class64_t, superclass), info);
4645 if (name != nullptr)
4646 outs() << " " << name;
4647 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00004648 outs() << "\n";
4649
4650 outs() << " cache " << format("0x%" PRIx64, c.cache);
4651 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4652 n_value, c.cache);
4653 if (name != nullptr)
4654 outs() << " " << name;
4655 outs() << "\n";
4656
4657 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4658 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4659 n_value, c.vtable);
4660 if (name != nullptr)
4661 outs() << " " << name;
4662 outs() << "\n";
4663
4664 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4665 n_value, c.data);
4666 outs() << " data ";
4667 if (n_value != 0) {
4668 if (info->verbose && name != nullptr)
4669 outs() << name;
4670 else
4671 outs() << format("0x%" PRIx64, n_value);
4672 if (c.data != 0)
4673 outs() << " + " << format("0x%" PRIx64, c.data);
4674 } else
4675 outs() << format("0x%" PRIx64, c.data);
4676 outs() << " (struct class_ro_t *)";
4677
4678 // This is a Swift class if some of the low bits of the pointer are set.
4679 if ((c.data + n_value) & 0x7)
4680 outs() << " Swift class";
4681 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004682 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004683 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4684 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004685
Kevin Enderbyaac75382015-10-08 16:56:35 +00004686 if (!is_meta_class &&
4687 c.isa + isa_n_value != p &&
4688 c.isa + isa_n_value != 0 &&
4689 info->depth < 100) {
4690 info->depth++;
4691 outs() << "Meta Class\n";
4692 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004693 }
4694}
4695
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004696static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4697 struct class32_t c;
4698 const char *r;
4699 uint32_t offset, left;
4700 SectionRef S;
4701 const char *name;
4702
4703 r = get_pointer_32(p, offset, left, S, info);
4704 if (r == nullptr)
4705 return;
4706 memset(&c, '\0', sizeof(struct class32_t));
4707 if (left < sizeof(struct class32_t)) {
4708 memcpy(&c, r, left);
4709 outs() << " (class_t entends past the end of the section)\n";
4710 } else
4711 memcpy(&c, r, sizeof(struct class32_t));
4712 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4713 swapStruct(c);
4714
4715 outs() << " isa " << format("0x%" PRIx32, c.isa);
4716 name =
4717 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4718 if (name != nullptr)
4719 outs() << " " << name;
4720 outs() << "\n";
4721
4722 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4723 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4724 c.superclass);
4725 if (name != nullptr)
4726 outs() << " " << name;
4727 outs() << "\n";
4728
4729 outs() << " cache " << format("0x%" PRIx32, c.cache);
4730 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4731 c.cache);
4732 if (name != nullptr)
4733 outs() << " " << name;
4734 outs() << "\n";
4735
4736 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4737 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4738 c.vtable);
4739 if (name != nullptr)
4740 outs() << " " << name;
4741 outs() << "\n";
4742
4743 name =
4744 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4745 outs() << " data " << format("0x%" PRIx32, c.data)
4746 << " (struct class_ro_t *)";
4747
4748 // This is a Swift class if some of the low bits of the pointer are set.
4749 if (c.data & 0x3)
4750 outs() << " Swift class";
4751 outs() << "\n";
4752 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004753 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4754 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004755
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004756 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004757 outs() << "Meta Class\n";
4758 print_class32_t(c.isa, info);
4759 }
4760}
4761
Kevin Enderby846c0002015-04-16 17:19:59 +00004762static void print_objc_class_t(struct objc_class_t *objc_class,
4763 struct DisassembleInfo *info) {
4764 uint32_t offset, left, xleft;
4765 const char *name, *p, *ivar_list;
4766 SectionRef S;
4767 int32_t i;
4768 struct objc_ivar_list_t objc_ivar_list;
4769 struct objc_ivar_t ivar;
4770
4771 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4772 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4773 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4774 if (name != nullptr)
4775 outs() << format(" %.*s", left, name);
4776 else
4777 outs() << " (not in an __OBJC section)";
4778 }
4779 outs() << "\n";
4780
4781 outs() << "\t super_class "
4782 << format("0x%08" PRIx32, objc_class->super_class);
4783 if (info->verbose) {
4784 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4785 if (name != nullptr)
4786 outs() << format(" %.*s", left, name);
4787 else
4788 outs() << " (not in an __OBJC section)";
4789 }
4790 outs() << "\n";
4791
4792 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4793 if (info->verbose) {
4794 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4795 if (name != nullptr)
4796 outs() << format(" %.*s", left, name);
4797 else
4798 outs() << " (not in an __OBJC section)";
4799 }
4800 outs() << "\n";
4801
4802 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4803 << "\n";
4804
4805 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4806 if (info->verbose) {
4807 if (CLS_GETINFO(objc_class, CLS_CLASS))
4808 outs() << " CLS_CLASS";
4809 else if (CLS_GETINFO(objc_class, CLS_META))
4810 outs() << " CLS_META";
4811 }
4812 outs() << "\n";
4813
4814 outs() << "\t instance_size "
4815 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4816
4817 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4818 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4819 if (p != nullptr) {
4820 if (left > sizeof(struct objc_ivar_list_t)) {
4821 outs() << "\n";
4822 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4823 } else {
4824 outs() << " (entends past the end of the section)\n";
4825 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4826 memcpy(&objc_ivar_list, p, left);
4827 }
4828 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4829 swapStruct(objc_ivar_list);
4830 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4831 ivar_list = p + sizeof(struct objc_ivar_list_t);
4832 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4833 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4834 outs() << "\t\t remaining ivar's extend past the of the section\n";
4835 break;
4836 }
4837 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4838 sizeof(struct objc_ivar_t));
4839 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4840 swapStruct(ivar);
4841
4842 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4843 if (info->verbose) {
4844 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4845 if (name != nullptr)
4846 outs() << format(" %.*s", xleft, name);
4847 else
4848 outs() << " (not in an __OBJC section)";
4849 }
4850 outs() << "\n";
4851
4852 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4853 if (info->verbose) {
4854 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4855 if (name != nullptr)
4856 outs() << format(" %.*s", xleft, name);
4857 else
4858 outs() << " (not in an __OBJC section)";
4859 }
4860 outs() << "\n";
4861
4862 outs() << "\t\t ivar_offset "
4863 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4864 }
4865 } else {
4866 outs() << " (not in an __OBJC section)\n";
4867 }
4868
4869 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4870 if (print_method_list(objc_class->methodLists, info))
4871 outs() << " (not in an __OBJC section)\n";
4872
4873 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4874 << "\n";
4875
4876 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4877 if (print_protocol_list(objc_class->protocols, 16, info))
4878 outs() << " (not in an __OBJC section)\n";
4879}
4880
4881static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4882 struct DisassembleInfo *info) {
4883 uint32_t offset, left;
4884 const char *name;
4885 SectionRef S;
4886
4887 outs() << "\t category name "
4888 << format("0x%08" PRIx32, objc_category->category_name);
4889 if (info->verbose) {
4890 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4891 true);
4892 if (name != nullptr)
4893 outs() << format(" %.*s", left, name);
4894 else
4895 outs() << " (not in an __OBJC section)";
4896 }
4897 outs() << "\n";
4898
4899 outs() << "\t\t class name "
4900 << format("0x%08" PRIx32, objc_category->class_name);
4901 if (info->verbose) {
4902 name =
4903 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4904 if (name != nullptr)
4905 outs() << format(" %.*s", left, name);
4906 else
4907 outs() << " (not in an __OBJC section)";
4908 }
4909 outs() << "\n";
4910
4911 outs() << "\t instance methods "
4912 << format("0x%08" PRIx32, objc_category->instance_methods);
4913 if (print_method_list(objc_category->instance_methods, info))
4914 outs() << " (not in an __OBJC section)\n";
4915
4916 outs() << "\t class methods "
4917 << format("0x%08" PRIx32, objc_category->class_methods);
4918 if (print_method_list(objc_category->class_methods, info))
4919 outs() << " (not in an __OBJC section)\n";
4920}
4921
Kevin Enderby0fc11822015-04-01 20:57:01 +00004922static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4923 struct category64_t c;
4924 const char *r;
4925 uint32_t offset, xoffset, left;
4926 SectionRef S, xS;
4927 const char *name, *sym_name;
4928 uint64_t n_value;
4929
4930 r = get_pointer_64(p, offset, left, S, info);
4931 if (r == nullptr)
4932 return;
4933 memset(&c, '\0', sizeof(struct category64_t));
4934 if (left < sizeof(struct category64_t)) {
4935 memcpy(&c, r, left);
4936 outs() << " (category_t entends past the end of the section)\n";
4937 } else
4938 memcpy(&c, r, sizeof(struct category64_t));
4939 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4940 swapStruct(c);
4941
4942 outs() << " name ";
4943 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4944 info, n_value, c.name);
4945 if (n_value != 0) {
4946 if (info->verbose && sym_name != nullptr)
4947 outs() << sym_name;
4948 else
4949 outs() << format("0x%" PRIx64, n_value);
4950 if (c.name != 0)
4951 outs() << " + " << format("0x%" PRIx64, c.name);
4952 } else
4953 outs() << format("0x%" PRIx64, c.name);
4954 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4955 if (name != nullptr)
4956 outs() << format(" %.*s", left, name);
4957 outs() << "\n";
4958
4959 outs() << " cls ";
4960 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4961 n_value, c.cls);
4962 if (n_value != 0) {
4963 if (info->verbose && sym_name != nullptr)
4964 outs() << sym_name;
4965 else
4966 outs() << format("0x%" PRIx64, n_value);
4967 if (c.cls != 0)
4968 outs() << " + " << format("0x%" PRIx64, c.cls);
4969 } else
4970 outs() << format("0x%" PRIx64, c.cls);
4971 outs() << "\n";
4972 if (c.cls + n_value != 0)
4973 print_class64_t(c.cls + n_value, info);
4974
4975 outs() << " instanceMethods ";
4976 sym_name =
4977 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4978 info, n_value, c.instanceMethods);
4979 if (n_value != 0) {
4980 if (info->verbose && sym_name != nullptr)
4981 outs() << sym_name;
4982 else
4983 outs() << format("0x%" PRIx64, n_value);
4984 if (c.instanceMethods != 0)
4985 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4986 } else
4987 outs() << format("0x%" PRIx64, c.instanceMethods);
4988 outs() << "\n";
4989 if (c.instanceMethods + n_value != 0)
4990 print_method_list64_t(c.instanceMethods + n_value, info, "");
4991
4992 outs() << " classMethods ";
4993 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4994 S, info, n_value, c.classMethods);
4995 if (n_value != 0) {
4996 if (info->verbose && sym_name != nullptr)
4997 outs() << sym_name;
4998 else
4999 outs() << format("0x%" PRIx64, n_value);
5000 if (c.classMethods != 0)
5001 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5002 } else
5003 outs() << format("0x%" PRIx64, c.classMethods);
5004 outs() << "\n";
5005 if (c.classMethods + n_value != 0)
5006 print_method_list64_t(c.classMethods + n_value, info, "");
5007
5008 outs() << " protocols ";
5009 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5010 info, n_value, c.protocols);
5011 if (n_value != 0) {
5012 if (info->verbose && sym_name != nullptr)
5013 outs() << sym_name;
5014 else
5015 outs() << format("0x%" PRIx64, n_value);
5016 if (c.protocols != 0)
5017 outs() << " + " << format("0x%" PRIx64, c.protocols);
5018 } else
5019 outs() << format("0x%" PRIx64, c.protocols);
5020 outs() << "\n";
5021 if (c.protocols + n_value != 0)
5022 print_protocol_list64_t(c.protocols + n_value, info);
5023
5024 outs() << "instanceProperties ";
5025 sym_name =
5026 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5027 S, info, n_value, c.instanceProperties);
5028 if (n_value != 0) {
5029 if (info->verbose && sym_name != nullptr)
5030 outs() << sym_name;
5031 else
5032 outs() << format("0x%" PRIx64, n_value);
5033 if (c.instanceProperties != 0)
5034 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5035 } else
5036 outs() << format("0x%" PRIx64, c.instanceProperties);
5037 outs() << "\n";
5038 if (c.instanceProperties + n_value != 0)
5039 print_objc_property_list64(c.instanceProperties + n_value, info);
5040}
5041
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005042static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5043 struct category32_t c;
5044 const char *r;
5045 uint32_t offset, left;
5046 SectionRef S, xS;
5047 const char *name;
5048
5049 r = get_pointer_32(p, offset, left, S, info);
5050 if (r == nullptr)
5051 return;
5052 memset(&c, '\0', sizeof(struct category32_t));
5053 if (left < sizeof(struct category32_t)) {
5054 memcpy(&c, r, left);
5055 outs() << " (category_t entends past the end of the section)\n";
5056 } else
5057 memcpy(&c, r, sizeof(struct category32_t));
5058 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5059 swapStruct(c);
5060
5061 outs() << " name " << format("0x%" PRIx32, c.name);
5062 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5063 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005064 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005065 outs() << " " << name;
5066 outs() << "\n";
5067
5068 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5069 if (c.cls != 0)
5070 print_class32_t(c.cls, info);
5071 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5072 << "\n";
5073 if (c.instanceMethods != 0)
5074 print_method_list32_t(c.instanceMethods, info, "");
5075 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5076 << "\n";
5077 if (c.classMethods != 0)
5078 print_method_list32_t(c.classMethods, info, "");
5079 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5080 if (c.protocols != 0)
5081 print_protocol_list32_t(c.protocols, info);
5082 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5083 << "\n";
5084 if (c.instanceProperties != 0)
5085 print_objc_property_list32(c.instanceProperties, info);
5086}
5087
Kevin Enderby0fc11822015-04-01 20:57:01 +00005088static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5089 uint32_t i, left, offset, xoffset;
5090 uint64_t p, n_value;
5091 struct message_ref64 mr;
5092 const char *name, *sym_name;
5093 const char *r;
5094 SectionRef xS;
5095
5096 if (S == SectionRef())
5097 return;
5098
5099 StringRef SectName;
5100 S.getName(SectName);
5101 DataRefImpl Ref = S.getRawDataRefImpl();
5102 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5103 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5104 offset = 0;
5105 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5106 p = S.getAddress() + i;
5107 r = get_pointer_64(p, offset, left, S, info);
5108 if (r == nullptr)
5109 return;
5110 memset(&mr, '\0', sizeof(struct message_ref64));
5111 if (left < sizeof(struct message_ref64)) {
5112 memcpy(&mr, r, left);
5113 outs() << " (message_ref entends past the end of the section)\n";
5114 } else
5115 memcpy(&mr, r, sizeof(struct message_ref64));
5116 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5117 swapStruct(mr);
5118
5119 outs() << " imp ";
5120 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5121 n_value, mr.imp);
5122 if (n_value != 0) {
5123 outs() << format("0x%" PRIx64, n_value) << " ";
5124 if (mr.imp != 0)
5125 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5126 } else
5127 outs() << format("0x%" PRIx64, mr.imp) << " ";
5128 if (name != nullptr)
5129 outs() << " " << name;
5130 outs() << "\n";
5131
5132 outs() << " sel ";
5133 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5134 info, n_value, mr.sel);
5135 if (n_value != 0) {
5136 if (info->verbose && sym_name != nullptr)
5137 outs() << sym_name;
5138 else
5139 outs() << format("0x%" PRIx64, n_value);
5140 if (mr.sel != 0)
5141 outs() << " + " << format("0x%" PRIx64, mr.sel);
5142 } else
5143 outs() << format("0x%" PRIx64, mr.sel);
5144 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5145 if (name != nullptr)
5146 outs() << format(" %.*s", left, name);
5147 outs() << "\n";
5148
5149 offset += sizeof(struct message_ref64);
5150 }
5151}
5152
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005153static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5154 uint32_t i, left, offset, xoffset, p;
5155 struct message_ref32 mr;
5156 const char *name, *r;
5157 SectionRef xS;
5158
5159 if (S == SectionRef())
5160 return;
5161
5162 StringRef SectName;
5163 S.getName(SectName);
5164 DataRefImpl Ref = S.getRawDataRefImpl();
5165 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5166 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5167 offset = 0;
5168 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5169 p = S.getAddress() + i;
5170 r = get_pointer_32(p, offset, left, S, info);
5171 if (r == nullptr)
5172 return;
5173 memset(&mr, '\0', sizeof(struct message_ref32));
5174 if (left < sizeof(struct message_ref32)) {
5175 memcpy(&mr, r, left);
5176 outs() << " (message_ref entends past the end of the section)\n";
5177 } else
5178 memcpy(&mr, r, sizeof(struct message_ref32));
5179 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5180 swapStruct(mr);
5181
5182 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5183 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5184 mr.imp);
5185 if (name != nullptr)
5186 outs() << " " << name;
5187 outs() << "\n";
5188
5189 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5190 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5191 if (name != nullptr)
5192 outs() << " " << name;
5193 outs() << "\n";
5194
5195 offset += sizeof(struct message_ref32);
5196 }
5197}
5198
Kevin Enderby0fc11822015-04-01 20:57:01 +00005199static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5200 uint32_t left, offset, swift_version;
5201 uint64_t p;
5202 struct objc_image_info64 o;
5203 const char *r;
5204
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005205 if (S == SectionRef())
5206 return;
5207
Kevin Enderby0fc11822015-04-01 20:57:01 +00005208 StringRef SectName;
5209 S.getName(SectName);
5210 DataRefImpl Ref = S.getRawDataRefImpl();
5211 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5212 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5213 p = S.getAddress();
5214 r = get_pointer_64(p, offset, left, S, info);
5215 if (r == nullptr)
5216 return;
5217 memset(&o, '\0', sizeof(struct objc_image_info64));
5218 if (left < sizeof(struct objc_image_info64)) {
5219 memcpy(&o, r, left);
5220 outs() << " (objc_image_info entends past the end of the section)\n";
5221 } else
5222 memcpy(&o, r, sizeof(struct objc_image_info64));
5223 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5224 swapStruct(o);
5225 outs() << " version " << o.version << "\n";
5226 outs() << " flags " << format("0x%" PRIx32, o.flags);
5227 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5228 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5229 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5230 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5231 swift_version = (o.flags >> 8) & 0xff;
5232 if (swift_version != 0) {
5233 if (swift_version == 1)
5234 outs() << " Swift 1.0";
5235 else if (swift_version == 2)
5236 outs() << " Swift 1.1";
5237 else
5238 outs() << " unknown future Swift version (" << swift_version << ")";
5239 }
5240 outs() << "\n";
5241}
5242
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005243static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5244 uint32_t left, offset, swift_version, p;
5245 struct objc_image_info32 o;
5246 const char *r;
5247
Kevin Enderby19be2512016-04-21 19:49:29 +00005248 if (S == SectionRef())
5249 return;
5250
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005251 StringRef SectName;
5252 S.getName(SectName);
5253 DataRefImpl Ref = S.getRawDataRefImpl();
5254 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5255 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5256 p = S.getAddress();
5257 r = get_pointer_32(p, offset, left, S, info);
5258 if (r == nullptr)
5259 return;
5260 memset(&o, '\0', sizeof(struct objc_image_info32));
5261 if (left < sizeof(struct objc_image_info32)) {
5262 memcpy(&o, r, left);
5263 outs() << " (objc_image_info entends past the end of the section)\n";
5264 } else
5265 memcpy(&o, r, sizeof(struct objc_image_info32));
5266 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5267 swapStruct(o);
5268 outs() << " version " << o.version << "\n";
5269 outs() << " flags " << format("0x%" PRIx32, o.flags);
5270 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5271 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5272 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5273 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5274 swift_version = (o.flags >> 8) & 0xff;
5275 if (swift_version != 0) {
5276 if (swift_version == 1)
5277 outs() << " Swift 1.0";
5278 else if (swift_version == 2)
5279 outs() << " Swift 1.1";
5280 else
5281 outs() << " unknown future Swift version (" << swift_version << ")";
5282 }
5283 outs() << "\n";
5284}
5285
Kevin Enderby846c0002015-04-16 17:19:59 +00005286static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5287 uint32_t left, offset, p;
5288 struct imageInfo_t o;
5289 const char *r;
5290
5291 StringRef SectName;
5292 S.getName(SectName);
5293 DataRefImpl Ref = S.getRawDataRefImpl();
5294 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5295 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5296 p = S.getAddress();
5297 r = get_pointer_32(p, offset, left, S, info);
5298 if (r == nullptr)
5299 return;
5300 memset(&o, '\0', sizeof(struct imageInfo_t));
5301 if (left < sizeof(struct imageInfo_t)) {
5302 memcpy(&o, r, left);
5303 outs() << " (imageInfo entends past the end of the section)\n";
5304 } else
5305 memcpy(&o, r, sizeof(struct imageInfo_t));
5306 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5307 swapStruct(o);
5308 outs() << " version " << o.version << "\n";
5309 outs() << " flags " << format("0x%" PRIx32, o.flags);
5310 if (o.flags & 0x1)
5311 outs() << " F&C";
5312 if (o.flags & 0x2)
5313 outs() << " GC";
5314 if (o.flags & 0x4)
5315 outs() << " GC-only";
5316 else
5317 outs() << " RR";
5318 outs() << "\n";
5319}
5320
Kevin Enderby0fc11822015-04-01 20:57:01 +00005321static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5322 SymbolAddressMap AddrMap;
5323 if (verbose)
5324 CreateSymbolAddressMap(O, &AddrMap);
5325
5326 std::vector<SectionRef> Sections;
5327 for (const SectionRef &Section : O->sections()) {
5328 StringRef SectName;
5329 Section.getName(SectName);
5330 Sections.push_back(Section);
5331 }
5332
5333 struct DisassembleInfo info;
5334 // Set up the block of info used by the Symbolizer call backs.
5335 info.verbose = verbose;
5336 info.O = O;
5337 info.AddrMap = &AddrMap;
5338 info.Sections = &Sections;
5339 info.class_name = nullptr;
5340 info.selector_name = nullptr;
5341 info.method = nullptr;
5342 info.demangled_name = nullptr;
5343 info.bindtable = nullptr;
5344 info.adrp_addr = 0;
5345 info.adrp_inst = 0;
5346
Kevin Enderbyaac75382015-10-08 16:56:35 +00005347 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005348 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5349 if (CL == SectionRef())
5350 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005351 if (CL == SectionRef())
5352 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5353 if (CL == SectionRef())
5354 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005355 info.S = CL;
5356 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005357
Davide Italiano62507042015-12-11 22:27:59 +00005358 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5359 if (CR == SectionRef())
5360 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005361 if (CR == SectionRef())
5362 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5363 if (CR == SectionRef())
5364 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005365 info.S = CR;
5366 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005367
Davide Italiano62507042015-12-11 22:27:59 +00005368 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5369 if (SR == SectionRef())
5370 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005371 if (SR == SectionRef())
5372 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5373 if (SR == SectionRef())
5374 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005375 info.S = SR;
5376 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005377
Davide Italiano62507042015-12-11 22:27:59 +00005378 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5379 if (CA == SectionRef())
5380 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005381 if (CA == SectionRef())
5382 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5383 if (CA == SectionRef())
5384 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005385 info.S = CA;
5386 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005387
Davide Italiano62507042015-12-11 22:27:59 +00005388 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5389 if (PL == SectionRef())
5390 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005391 if (PL == SectionRef())
5392 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5393 if (PL == SectionRef())
5394 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005395 info.S = PL;
5396 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005397
Davide Italiano62507042015-12-11 22:27:59 +00005398 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5399 if (MR == SectionRef())
5400 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005401 if (MR == SectionRef())
5402 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5403 if (MR == SectionRef())
5404 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005405 info.S = MR;
5406 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005407
Davide Italiano62507042015-12-11 22:27:59 +00005408 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5409 if (II == SectionRef())
5410 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005411 if (II == SectionRef())
5412 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5413 if (II == SectionRef())
5414 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005415 info.S = II;
5416 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005417}
5418
5419static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005420 SymbolAddressMap AddrMap;
5421 if (verbose)
5422 CreateSymbolAddressMap(O, &AddrMap);
5423
5424 std::vector<SectionRef> Sections;
5425 for (const SectionRef &Section : O->sections()) {
5426 StringRef SectName;
5427 Section.getName(SectName);
5428 Sections.push_back(Section);
5429 }
5430
5431 struct DisassembleInfo info;
5432 // Set up the block of info used by the Symbolizer call backs.
5433 info.verbose = verbose;
5434 info.O = O;
5435 info.AddrMap = &AddrMap;
5436 info.Sections = &Sections;
5437 info.class_name = nullptr;
5438 info.selector_name = nullptr;
5439 info.method = nullptr;
5440 info.demangled_name = nullptr;
5441 info.bindtable = nullptr;
5442 info.adrp_addr = 0;
5443 info.adrp_inst = 0;
5444
Kevin Enderby5879a482017-02-09 17:56:26 +00005445 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5446 if (CL == SectionRef())
5447 CL = get_section(O, "__DATA", "__objc_classlist");
5448 if (CL == SectionRef())
5449 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5450 if (CL == SectionRef())
5451 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5452 info.S = CL;
5453 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005454
Kevin Enderby5879a482017-02-09 17:56:26 +00005455 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5456 if (CR == SectionRef())
5457 CR = get_section(O, "__DATA", "__objc_classrefs");
5458 if (CR == SectionRef())
5459 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5460 if (CR == SectionRef())
5461 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5462 info.S = CR;
5463 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005464
Kevin Enderby5879a482017-02-09 17:56:26 +00005465 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5466 if (SR == SectionRef())
5467 SR = get_section(O, "__DATA", "__objc_superrefs");
5468 if (SR == SectionRef())
5469 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5470 if (SR == SectionRef())
5471 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5472 info.S = SR;
5473 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005474
Kevin Enderby5879a482017-02-09 17:56:26 +00005475 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5476 if (CA == SectionRef())
5477 CA = get_section(O, "__DATA", "__objc_catlist");
5478 if (CA == SectionRef())
5479 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5480 if (CA == SectionRef())
5481 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5482 info.S = CA;
5483 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005484
Kevin Enderby5879a482017-02-09 17:56:26 +00005485 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5486 if (PL == SectionRef())
5487 PL = get_section(O, "__DATA", "__objc_protolist");
5488 if (PL == SectionRef())
5489 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5490 if (PL == SectionRef())
5491 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5492 info.S = PL;
5493 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005494
Kevin Enderby5879a482017-02-09 17:56:26 +00005495 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5496 if (MR == SectionRef())
5497 MR = get_section(O, "__DATA", "__objc_msgrefs");
5498 if (MR == SectionRef())
5499 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5500 if (MR == SectionRef())
5501 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5502 info.S = MR;
5503 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005504
Kevin Enderby5879a482017-02-09 17:56:26 +00005505 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5506 if (II == SectionRef())
5507 II = get_section(O, "__DATA", "__objc_imageinfo");
5508 if (II == SectionRef())
5509 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5510 if (II == SectionRef())
5511 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5512 info.S = II;
5513 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005514}
5515
5516static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005517 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5518 const char *r, *name, *defs;
5519 struct objc_module_t module;
5520 SectionRef S, xS;
5521 struct objc_symtab_t symtab;
5522 struct objc_class_t objc_class;
5523 struct objc_category_t objc_category;
5524
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005525 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005526 S = get_section(O, "__OBJC", "__module_info");
5527 if (S == SectionRef())
5528 return false;
5529
5530 SymbolAddressMap AddrMap;
5531 if (verbose)
5532 CreateSymbolAddressMap(O, &AddrMap);
5533
5534 std::vector<SectionRef> Sections;
5535 for (const SectionRef &Section : O->sections()) {
5536 StringRef SectName;
5537 Section.getName(SectName);
5538 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005539 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005540
5541 struct DisassembleInfo info;
5542 // Set up the block of info used by the Symbolizer call backs.
5543 info.verbose = verbose;
5544 info.O = O;
5545 info.AddrMap = &AddrMap;
5546 info.Sections = &Sections;
5547 info.class_name = nullptr;
5548 info.selector_name = nullptr;
5549 info.method = nullptr;
5550 info.demangled_name = nullptr;
5551 info.bindtable = nullptr;
5552 info.adrp_addr = 0;
5553 info.adrp_inst = 0;
5554
5555 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5556 p = S.getAddress() + i;
5557 r = get_pointer_32(p, offset, left, S, &info, true);
5558 if (r == nullptr)
5559 return true;
5560 memset(&module, '\0', sizeof(struct objc_module_t));
5561 if (left < sizeof(struct objc_module_t)) {
5562 memcpy(&module, r, left);
5563 outs() << " (module extends past end of __module_info section)\n";
5564 } else
5565 memcpy(&module, r, sizeof(struct objc_module_t));
5566 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5567 swapStruct(module);
5568
5569 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5570 outs() << " version " << module.version << "\n";
5571 outs() << " size " << module.size << "\n";
5572 outs() << " name ";
5573 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5574 if (name != nullptr)
5575 outs() << format("%.*s", left, name);
5576 else
5577 outs() << format("0x%08" PRIx32, module.name)
5578 << "(not in an __OBJC section)";
5579 outs() << "\n";
5580
5581 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5582 if (module.symtab == 0 || r == nullptr) {
5583 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5584 << " (not in an __OBJC section)\n";
5585 continue;
5586 }
5587 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5588 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5589 defs_left = 0;
5590 defs = nullptr;
5591 if (left < sizeof(struct objc_symtab_t)) {
5592 memcpy(&symtab, r, left);
5593 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5594 } else {
5595 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5596 if (left > sizeof(struct objc_symtab_t)) {
5597 defs_left = left - sizeof(struct objc_symtab_t);
5598 defs = r + sizeof(struct objc_symtab_t);
5599 }
5600 }
5601 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5602 swapStruct(symtab);
5603
5604 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5605 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5606 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5607 if (r == nullptr)
5608 outs() << " (not in an __OBJC section)";
5609 outs() << "\n";
5610 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5611 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5612 if (symtab.cls_def_cnt > 0)
5613 outs() << "\tClass Definitions\n";
5614 for (j = 0; j < symtab.cls_def_cnt; j++) {
5615 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5616 outs() << "\t(remaining class defs entries entends past the end of the "
5617 << "section)\n";
5618 break;
5619 }
5620 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5621 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5622 sys::swapByteOrder(def);
5623
5624 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5625 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5626 if (r != nullptr) {
5627 if (left > sizeof(struct objc_class_t)) {
5628 outs() << "\n";
5629 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5630 } else {
5631 outs() << " (entends past the end of the section)\n";
5632 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5633 memcpy(&objc_class, r, left);
5634 }
5635 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5636 swapStruct(objc_class);
5637 print_objc_class_t(&objc_class, &info);
5638 } else {
5639 outs() << "(not in an __OBJC section)\n";
5640 }
5641
5642 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5643 outs() << "\tMeta Class";
5644 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5645 if (r != nullptr) {
5646 if (left > sizeof(struct objc_class_t)) {
5647 outs() << "\n";
5648 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5649 } else {
5650 outs() << " (entends past the end of the section)\n";
5651 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5652 memcpy(&objc_class, r, left);
5653 }
5654 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5655 swapStruct(objc_class);
5656 print_objc_class_t(&objc_class, &info);
5657 } else {
5658 outs() << "(not in an __OBJC section)\n";
5659 }
5660 }
5661 }
5662 if (symtab.cat_def_cnt > 0)
5663 outs() << "\tCategory Definitions\n";
5664 for (j = 0; j < symtab.cat_def_cnt; j++) {
5665 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5666 outs() << "\t(remaining category defs entries entends past the end of "
5667 << "the section)\n";
5668 break;
5669 }
5670 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5671 sizeof(uint32_t));
5672 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5673 sys::swapByteOrder(def);
5674
5675 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5676 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5677 << format("0x%08" PRIx32, def);
5678 if (r != nullptr) {
5679 if (left > sizeof(struct objc_category_t)) {
5680 outs() << "\n";
5681 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5682 } else {
5683 outs() << " (entends past the end of the section)\n";
5684 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5685 memcpy(&objc_category, r, left);
5686 }
5687 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5688 swapStruct(objc_category);
5689 print_objc_objc_category_t(&objc_category, &info);
5690 } else {
5691 outs() << "(not in an __OBJC section)\n";
5692 }
5693 }
5694 }
5695 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5696 if (II != SectionRef())
5697 print_image_info(II, &info);
5698
5699 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005700}
5701
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005702static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5703 uint32_t size, uint32_t addr) {
5704 SymbolAddressMap AddrMap;
5705 CreateSymbolAddressMap(O, &AddrMap);
5706
5707 std::vector<SectionRef> Sections;
5708 for (const SectionRef &Section : O->sections()) {
5709 StringRef SectName;
5710 Section.getName(SectName);
5711 Sections.push_back(Section);
5712 }
5713
5714 struct DisassembleInfo info;
5715 // Set up the block of info used by the Symbolizer call backs.
5716 info.verbose = true;
5717 info.O = O;
5718 info.AddrMap = &AddrMap;
5719 info.Sections = &Sections;
5720 info.class_name = nullptr;
5721 info.selector_name = nullptr;
5722 info.method = nullptr;
5723 info.demangled_name = nullptr;
5724 info.bindtable = nullptr;
5725 info.adrp_addr = 0;
5726 info.adrp_inst = 0;
5727
5728 const char *p;
5729 struct objc_protocol_t protocol;
5730 uint32_t left, paddr;
5731 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5732 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5733 left = size - (p - sect);
5734 if (left < sizeof(struct objc_protocol_t)) {
5735 outs() << "Protocol extends past end of __protocol section\n";
5736 memcpy(&protocol, p, left);
5737 } else
5738 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5739 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5740 swapStruct(protocol);
5741 paddr = addr + (p - sect);
5742 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5743 if (print_protocol(paddr, 0, &info))
5744 outs() << "(not in an __OBJC section)\n";
5745 }
5746}
5747
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005748#ifdef HAVE_LIBXAR
5749inline void swapStruct(struct xar_header &xar) {
5750 sys::swapByteOrder(xar.magic);
5751 sys::swapByteOrder(xar.size);
5752 sys::swapByteOrder(xar.version);
5753 sys::swapByteOrder(xar.toc_length_compressed);
5754 sys::swapByteOrder(xar.toc_length_uncompressed);
5755 sys::swapByteOrder(xar.cksum_alg);
5756}
5757
5758static void PrintModeVerbose(uint32_t mode) {
5759 switch(mode & S_IFMT){
5760 case S_IFDIR:
5761 outs() << "d";
5762 break;
5763 case S_IFCHR:
5764 outs() << "c";
5765 break;
5766 case S_IFBLK:
5767 outs() << "b";
5768 break;
5769 case S_IFREG:
5770 outs() << "-";
5771 break;
5772 case S_IFLNK:
5773 outs() << "l";
5774 break;
5775 case S_IFSOCK:
5776 outs() << "s";
5777 break;
5778 default:
5779 outs() << "?";
5780 break;
5781 }
5782
5783 /* owner permissions */
5784 if(mode & S_IREAD)
5785 outs() << "r";
5786 else
5787 outs() << "-";
5788 if(mode & S_IWRITE)
5789 outs() << "w";
5790 else
5791 outs() << "-";
5792 if(mode & S_ISUID)
5793 outs() << "s";
5794 else if(mode & S_IEXEC)
5795 outs() << "x";
5796 else
5797 outs() << "-";
5798
5799 /* group permissions */
5800 if(mode & (S_IREAD >> 3))
5801 outs() << "r";
5802 else
5803 outs() << "-";
5804 if(mode & (S_IWRITE >> 3))
5805 outs() << "w";
5806 else
5807 outs() << "-";
5808 if(mode & S_ISGID)
5809 outs() << "s";
5810 else if(mode & (S_IEXEC >> 3))
5811 outs() << "x";
5812 else
5813 outs() << "-";
5814
5815 /* other permissions */
5816 if(mode & (S_IREAD >> 6))
5817 outs() << "r";
5818 else
5819 outs() << "-";
5820 if(mode & (S_IWRITE >> 6))
5821 outs() << "w";
5822 else
5823 outs() << "-";
5824 if(mode & S_ISVTX)
5825 outs() << "t";
5826 else if(mode & (S_IEXEC >> 6))
5827 outs() << "x";
5828 else
5829 outs() << "-";
5830}
5831
5832static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005833 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005834 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5835 char *endp;
5836 uint32_t mode_value;
5837
Francis Ricci6f942972017-10-06 15:33:28 +00005838 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005839 if (!xi) {
5840 errs() << "Can't obtain an xar iterator for xar archive "
5841 << XarFilename << "\n";
5842 return;
5843 }
5844
5845 // Go through the xar's files.
5846 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00005847 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005848 if(!xp){
5849 errs() << "Can't obtain an xar iterator for xar archive "
5850 << XarFilename << "\n";
5851 return;
5852 }
5853 type = nullptr;
5854 mode = nullptr;
5855 user = nullptr;
5856 group = nullptr;
5857 size = nullptr;
5858 mtime = nullptr;
5859 name = nullptr;
5860 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00005861 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005862 xar_prop_get(xf, key, &val);
5863#if 0 // Useful for debugging.
5864 outs() << "key: " << key << " value: " << val << "\n";
5865#endif
5866 if(strcmp(key, "type") == 0)
5867 type = val;
5868 if(strcmp(key, "mode") == 0)
5869 mode = val;
5870 if(strcmp(key, "user") == 0)
5871 user = val;
5872 if(strcmp(key, "group") == 0)
5873 group = val;
5874 if(strcmp(key, "data/size") == 0)
5875 size = val;
5876 if(strcmp(key, "mtime") == 0)
5877 mtime = val;
5878 if(strcmp(key, "name") == 0)
5879 name = val;
5880 }
5881 if(mode != nullptr){
5882 mode_value = strtoul(mode, &endp, 8);
5883 if(*endp != '\0')
5884 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5885 if(strcmp(type, "file") == 0)
5886 mode_value |= S_IFREG;
5887 PrintModeVerbose(mode_value);
5888 outs() << " ";
5889 }
5890 if(user != nullptr)
5891 outs() << format("%10s/", user);
5892 if(group != nullptr)
5893 outs() << format("%-10s ", group);
5894 if(size != nullptr)
5895 outs() << format("%7s ", size);
5896 if(mtime != nullptr){
5897 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5898 outs() << *m;
5899 if(*m == 'T')
5900 m++;
5901 outs() << " ";
5902 for( ; *m != 'Z' && *m != '\0'; m++)
5903 outs() << *m;
5904 outs() << " ";
5905 }
5906 if(name != nullptr)
5907 outs() << name;
5908 outs() << "\n";
5909 }
5910}
5911
5912static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5913 uint32_t size, bool verbose,
5914 bool PrintXarHeader, bool PrintXarFileHeaders,
5915 std::string XarMemberName) {
5916 if(size < sizeof(struct xar_header)) {
5917 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5918 "of struct xar_header)\n";
5919 return;
5920 }
5921 struct xar_header XarHeader;
5922 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5923 if (sys::IsLittleEndianHost)
5924 swapStruct(XarHeader);
5925 if (PrintXarHeader) {
5926 if (!XarMemberName.empty())
5927 outs() << "In xar member " << XarMemberName << ": ";
5928 else
5929 outs() << "For (__LLVM,__bundle) section: ";
5930 outs() << "xar header\n";
5931 if (XarHeader.magic == XAR_HEADER_MAGIC)
5932 outs() << " magic XAR_HEADER_MAGIC\n";
5933 else
5934 outs() << " magic "
5935 << format_hex(XarHeader.magic, 10, true)
5936 << " (not XAR_HEADER_MAGIC)\n";
5937 outs() << " size " << XarHeader.size << "\n";
5938 outs() << " version " << XarHeader.version << "\n";
5939 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5940 << "\n";
5941 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5942 << "\n";
5943 outs() << " cksum_alg ";
5944 switch (XarHeader.cksum_alg) {
5945 case XAR_CKSUM_NONE:
5946 outs() << "XAR_CKSUM_NONE\n";
5947 break;
5948 case XAR_CKSUM_SHA1:
5949 outs() << "XAR_CKSUM_SHA1\n";
5950 break;
5951 case XAR_CKSUM_MD5:
5952 outs() << "XAR_CKSUM_MD5\n";
5953 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005954#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005955 case XAR_CKSUM_SHA256:
5956 outs() << "XAR_CKSUM_SHA256\n";
5957 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005958#endif
5959#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005960 case XAR_CKSUM_SHA512:
5961 outs() << "XAR_CKSUM_SHA512\n";
5962 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005963#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005964 default:
5965 outs() << XarHeader.cksum_alg << "\n";
5966 }
5967 }
5968
5969 SmallString<128> XarFilename;
5970 int FD;
5971 std::error_code XarEC =
5972 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5973 if (XarEC) {
5974 errs() << XarEC.message() << "\n";
5975 return;
5976 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00005977 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005978 raw_fd_ostream &XarOut = XarFile.os();
5979 StringRef XarContents(sect, size);
5980 XarOut << XarContents;
5981 XarOut.close();
5982 if (XarOut.has_error())
5983 return;
5984
Francis Ricci6f942972017-10-06 15:33:28 +00005985 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005986 if (!xar) {
5987 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5988 return;
5989 }
5990
5991 SmallString<128> TocFilename;
5992 std::error_code TocEC =
5993 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5994 if (TocEC) {
5995 errs() << TocEC.message() << "\n";
5996 return;
5997 }
5998 xar_serialize(xar, TocFilename.c_str());
5999
6000 if (PrintXarFileHeaders) {
6001 if (!XarMemberName.empty())
6002 outs() << "In xar member " << XarMemberName << ": ";
6003 else
6004 outs() << "For (__LLVM,__bundle) section: ";
6005 outs() << "xar archive files:\n";
6006 PrintXarFilesSummary(XarFilename.c_str(), xar);
6007 }
6008
6009 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6010 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6011 if (std::error_code EC = FileOrErr.getError()) {
6012 errs() << EC.message() << "\n";
6013 return;
6014 }
6015 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6016
6017 if (!XarMemberName.empty())
6018 outs() << "In xar member " << XarMemberName << ": ";
6019 else
6020 outs() << "For (__LLVM,__bundle) section: ";
6021 outs() << "xar table of contents:\n";
6022 outs() << Buffer->getBuffer() << "\n";
6023
6024 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006025 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006026 if(!xi){
6027 errs() << "Can't obtain an xar iterator for xar archive "
6028 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006029 return;
6030 }
6031 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6032 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006033 const char *member_name, *member_type, *member_size_string;
6034 size_t member_size;
6035
Francis Ricci6f942972017-10-06 15:33:28 +00006036 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006037 if(!xp){
6038 errs() << "Can't obtain an xar iterator for xar archive "
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006039 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006040 return;
6041 }
6042 member_name = NULL;
6043 member_type = NULL;
6044 member_size_string = NULL;
6045 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006046 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006047 xar_prop_get(xf, key, &val);
6048#if 0 // Useful for debugging.
6049 outs() << "key: " << key << " value: " << val << "\n";
6050#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006051 if (strcmp(key, "name") == 0)
6052 member_name = val;
6053 if (strcmp(key, "type") == 0)
6054 member_type = val;
6055 if (strcmp(key, "data/size") == 0)
6056 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006057 }
6058 /*
6059 * If we find a file with a name, date/size and type properties
6060 * and with the type being "file" see if that is a xar file.
6061 */
6062 if (member_name != NULL && member_type != NULL &&
6063 strcmp(member_type, "file") == 0 &&
6064 member_size_string != NULL){
6065 // Extract the file into a buffer.
6066 char *endptr;
6067 member_size = strtoul(member_size_string, &endptr, 10);
6068 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006069 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006070 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006071#if 0 // Useful for debugging.
6072 outs() << "xar member: " << member_name << " extracted\n";
6073#endif
6074 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006075 std::string OldXarMemberName;
6076 // If XarMemberName is already set this is nested. So
6077 // save the old name and create the nested name.
6078 if (!XarMemberName.empty()) {
6079 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006080 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006081 (Twine("[") + XarMemberName + "]" + member_name).str();
6082 } else {
6083 OldXarMemberName = "";
6084 XarMemberName = member_name;
6085 }
6086 // See if this is could be a xar file (nested).
6087 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006088#if 0 // Useful for debugging.
6089 outs() << "could be a xar file: " << member_name << "\n";
6090#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006091 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006092 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006093 swapStruct(XarHeader);
6094 if (XarHeader.magic == XAR_HEADER_MAGIC)
6095 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006096 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006097 XarMemberName);
6098 }
6099 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006100 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006101 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006102 }
6103 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006104 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006105}
6106#endif // defined(HAVE_LIBXAR)
6107
Kevin Enderby0fc11822015-04-01 20:57:01 +00006108static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6109 if (O->is64Bit())
6110 printObjc2_64bit_MetaData(O, verbose);
6111 else {
6112 MachO::mach_header H;
6113 H = O->getHeader();
6114 if (H.cputype == MachO::CPU_TYPE_ARM)
6115 printObjc2_32bit_MetaData(O, verbose);
6116 else {
6117 // This is the 32-bit non-arm cputype case. Which is normally
6118 // the first Objective-C ABI. But it may be the case of a
6119 // binary for the iOS simulator which is the second Objective-C
6120 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6121 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006122 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006123 printObjc2_32bit_MetaData(O, verbose);
6124 }
6125 }
6126}
6127
Kevin Enderbybf246f52014-09-24 23:08:22 +00006128// GuessLiteralPointer returns a string which for the item in the Mach-O file
6129// for the address passed in as ReferenceValue for printing as a comment with
6130// the instruction and also returns the corresponding type of that item
6131// indirectly through ReferenceType.
6132//
6133// If ReferenceValue is an address of literal cstring then a pointer to the
6134// cstring is returned and ReferenceType is set to
6135// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6136//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006137// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6138// Class ref that name is returned and the ReferenceType is set accordingly.
6139//
6140// Lastly, literals which are Symbol address in a literal pool are looked for
6141// and if found the symbol name is returned and ReferenceType is set to
6142// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6143//
6144// If there is no item in the Mach-O file for the address passed in as
6145// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006146static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6147 uint64_t ReferencePC,
6148 uint64_t *ReferenceType,
6149 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006150 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006151 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6152 uint64_t sect_addr = info->S.getAddress();
6153 uint64_t sect_offset = ReferencePC - sect_addr;
6154 bool reloc_found = false;
6155 DataRefImpl Rel;
6156 MachO::any_relocation_info RE;
6157 bool isExtern = false;
6158 SymbolRef Symbol;
6159 for (const RelocationRef &Reloc : info->S.relocations()) {
6160 uint64_t RelocOffset = Reloc.getOffset();
6161 if (RelocOffset == sect_offset) {
6162 Rel = Reloc.getRawDataRefImpl();
6163 RE = info->O->getRelocation(Rel);
6164 if (info->O->isRelocationScattered(RE))
6165 continue;
6166 isExtern = info->O->getPlainRelocationExternal(RE);
6167 if (isExtern) {
6168 symbol_iterator RelocSym = Reloc.getSymbol();
6169 Symbol = *RelocSym;
6170 }
6171 reloc_found = true;
6172 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006173 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006174 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006175 // If there is an external relocation entry for a symbol in a section
6176 // then used that symbol's value for the value of the reference.
6177 if (reloc_found && isExtern) {
6178 if (info->O->getAnyRelocationPCRel(RE)) {
6179 unsigned Type = info->O->getAnyRelocationType(RE);
6180 if (Type == MachO::X86_64_RELOC_SIGNED) {
6181 ReferenceValue = Symbol.getValue();
6182 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006183 }
6184 }
6185 }
6186
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006187 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6188 // Message refs and Class refs.
6189 bool classref, selref, msgref, cfstring;
6190 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6191 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006192 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006193 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6194 // And the pointer_value in that section is typically zero as it will be
6195 // set by dyld as part of the "bind information".
6196 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6197 if (name != nullptr) {
6198 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006199 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006200 if (class_name != nullptr && class_name[1] == '_' &&
6201 class_name[2] != '\0') {
6202 info->class_name = class_name + 2;
6203 return name;
6204 }
6205 }
6206 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006207
David Blaikie33dd45d02015-03-23 18:39:02 +00006208 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006209 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6210 const char *name =
6211 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6212 if (name != nullptr)
6213 info->class_name = name;
6214 else
6215 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006216 return name;
6217 }
6218
David Blaikie33dd45d02015-03-23 18:39:02 +00006219 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006220 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6221 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6222 return name;
6223 }
6224
David Blaikie33dd45d02015-03-23 18:39:02 +00006225 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006226 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6227
6228 if (pointer_value != 0)
6229 ReferenceValue = pointer_value;
6230
6231 const char *name = GuessCstringPointer(ReferenceValue, info);
6232 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006233 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006234 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6235 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006236 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006237 info->class_name = nullptr;
6238 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6239 info->selector_name = name;
6240 } else
6241 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6242 return name;
6243 }
6244
6245 // Lastly look for an indirect symbol with this ReferenceValue which is in
6246 // a literal pool. If found return that symbol name.
6247 name = GuessIndirectSymbol(ReferenceValue, info);
6248 if (name) {
6249 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6250 return name;
6251 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006252
6253 return nullptr;
6254}
6255
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006256// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006257// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006258// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6259// is created and returns the symbol name that matches the ReferenceValue or
6260// nullptr if none. The ReferenceType is passed in for the IN type of
6261// reference the instruction is making from the values in defined in the header
6262// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6263// Out type and the ReferenceName will also be set which is added as a comment
6264// to the disassembled instruction.
6265//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006266// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006267// returned through ReferenceName and ReferenceType is set to
6268// LLVMDisassembler_ReferenceType_DeMangled_Name .
6269//
6270// When this is called to get a symbol name for a branch target then the
6271// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6272// SymbolValue will be looked for in the indirect symbol table to determine if
6273// it is an address for a symbol stub. If so then the symbol name for that
6274// stub is returned indirectly through ReferenceName and then ReferenceType is
6275// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6276//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006277// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006278// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6279// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6280// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006281// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006282static const char *SymbolizerSymbolLookUp(void *DisInfo,
6283 uint64_t ReferenceValue,
6284 uint64_t *ReferenceType,
6285 uint64_t ReferencePC,
6286 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006287 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006288 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006289 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006290 *ReferenceName = nullptr;
6291 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006292 return nullptr;
6293 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006294
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006295 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006296
Kevin Enderby85974882014-09-26 22:20:44 +00006297 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6298 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006299 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006300 method_reference(info, ReferenceType, ReferenceName);
6301 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6302 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006303 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006304 if (info->demangled_name != nullptr)
6305 free(info->demangled_name);
6306 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006307 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006308 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006309 if (info->demangled_name != nullptr) {
6310 *ReferenceName = info->demangled_name;
6311 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6312 } else
6313 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6314 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006315 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6316 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6317 *ReferenceName =
6318 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006319 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006320 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006321 else
6322 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006323 // If this is arm64 and the reference is an adrp instruction save the
6324 // instruction, passed in ReferenceValue and the address of the instruction
6325 // for use later if we see and add immediate instruction.
6326 } else if (info->O->getArch() == Triple::aarch64 &&
6327 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6328 info->adrp_inst = ReferenceValue;
6329 info->adrp_addr = ReferencePC;
6330 SymbolName = nullptr;
6331 *ReferenceName = nullptr;
6332 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6333 // If this is arm64 and reference is an add immediate instruction and we
6334 // have
6335 // seen an adrp instruction just before it and the adrp's Xd register
6336 // matches
6337 // this add's Xn register reconstruct the value being referenced and look to
6338 // see if it is a literal pointer. Note the add immediate instruction is
6339 // passed in ReferenceValue.
6340 } else if (info->O->getArch() == Triple::aarch64 &&
6341 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6342 ReferencePC - 4 == info->adrp_addr &&
6343 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6344 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6345 uint32_t addxri_inst;
6346 uint64_t adrp_imm, addxri_imm;
6347
6348 adrp_imm =
6349 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6350 if (info->adrp_inst & 0x0200000)
6351 adrp_imm |= 0xfffffffffc000000LL;
6352
6353 addxri_inst = ReferenceValue;
6354 addxri_imm = (addxri_inst >> 10) & 0xfff;
6355 if (((addxri_inst >> 22) & 0x3) == 1)
6356 addxri_imm <<= 12;
6357
6358 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6359 (adrp_imm << 12) + addxri_imm;
6360
6361 *ReferenceName =
6362 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6363 if (*ReferenceName == nullptr)
6364 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6365 // If this is arm64 and the reference is a load register instruction and we
6366 // have seen an adrp instruction just before it and the adrp's Xd register
6367 // matches this add's Xn register reconstruct the value being referenced and
6368 // look to see if it is a literal pointer. Note the load register
6369 // instruction is passed in ReferenceValue.
6370 } else if (info->O->getArch() == Triple::aarch64 &&
6371 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6372 ReferencePC - 4 == info->adrp_addr &&
6373 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6374 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6375 uint32_t ldrxui_inst;
6376 uint64_t adrp_imm, ldrxui_imm;
6377
6378 adrp_imm =
6379 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6380 if (info->adrp_inst & 0x0200000)
6381 adrp_imm |= 0xfffffffffc000000LL;
6382
6383 ldrxui_inst = ReferenceValue;
6384 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6385
6386 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6387 (adrp_imm << 12) + (ldrxui_imm << 3);
6388
6389 *ReferenceName =
6390 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6391 if (*ReferenceName == nullptr)
6392 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6393 }
6394 // If this arm64 and is an load register (PC-relative) instruction the
6395 // ReferenceValue is the PC plus the immediate value.
6396 else if (info->O->getArch() == Triple::aarch64 &&
6397 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6398 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6399 *ReferenceName =
6400 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6401 if (*ReferenceName == nullptr)
6402 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006403 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006404 if (info->demangled_name != nullptr)
6405 free(info->demangled_name);
6406 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006407 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006408 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006409 if (info->demangled_name != nullptr) {
6410 *ReferenceName = info->demangled_name;
6411 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6412 }
6413 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006414 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006415 *ReferenceName = nullptr;
6416 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6417 }
6418
6419 return SymbolName;
6420}
6421
Kevin Enderbybf246f52014-09-24 23:08:22 +00006422/// \brief Emits the comments that are stored in the CommentStream.
6423/// Each comment in the CommentStream must end with a newline.
6424static void emitComments(raw_svector_ostream &CommentStream,
6425 SmallString<128> &CommentsToEmit,
6426 formatted_raw_ostream &FormattedOS,
6427 const MCAsmInfo &MAI) {
6428 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006429 StringRef Comments = CommentsToEmit.str();
6430 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006431 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006432 unsigned CommentColumn = MAI.getCommentColumn();
6433 bool IsFirst = true;
6434 while (!Comments.empty()) {
6435 if (!IsFirst)
6436 FormattedOS << '\n';
6437 // Emit a line of comments.
6438 FormattedOS.PadToColumn(CommentColumn);
6439 size_t Position = Comments.find('\n');
6440 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6441 // Move after the newline character.
6442 Comments = Comments.substr(Position + 1);
6443 IsFirst = false;
6444 }
6445 FormattedOS.flush();
6446
6447 // Tell the comment stream that the vector changed underneath it.
6448 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006449}
6450
Kevin Enderby95df54c2015-02-04 01:01:38 +00006451static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6452 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006453 const char *McpuDefault = nullptr;
6454 const Target *ThumbTarget = nullptr;
6455 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006456 if (!TheTarget) {
6457 // GetTarget prints out stuff.
6458 return;
6459 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00006460 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006461 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00006462 MachOMCPU = McpuDefault;
6463 else
6464 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006465
Ahmed Charles56440fd2014-03-06 05:51:42 +00006466 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006467 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006468 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006469 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006470
Kevin Enderbyc9595622014-08-06 23:24:41 +00006471 // Package up features to be passed to target/subtarget
6472 std::string FeaturesStr;
6473 if (MAttrs.size()) {
6474 SubtargetFeatures Features;
6475 for (unsigned i = 0; i != MAttrs.size(); ++i)
6476 Features.AddFeature(MAttrs[i]);
6477 FeaturesStr = Features.getString();
6478 }
6479
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006480 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006481 std::unique_ptr<const MCRegisterInfo> MRI(
6482 TheTarget->createMCRegInfo(TripleName));
6483 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006484 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006485 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006486 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006487 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006488 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006489 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006490 std::unique_ptr<MCSymbolizer> Symbolizer;
6491 struct DisassembleInfo SymbolizerInfo;
6492 std::unique_ptr<MCRelocationInfo> RelInfo(
6493 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6494 if (RelInfo) {
6495 Symbolizer.reset(TheTarget->createMCSymbolizer(
6496 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006497 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006498 DisAsm->setSymbolizer(std::move(Symbolizer));
6499 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006500 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006501 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006502 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006503 // Set the display preference for hex vs. decimal immediates.
6504 IP->setPrintImmHex(PrintImmHex);
6505 // Comment stream and backing vector.
6506 SmallString<128> CommentsToEmit;
6507 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006508 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6509 // if it is done then arm64 comments for string literals don't get printed
6510 // and some constant get printed instead and not setting it causes intel
6511 // (32-bit and 64-bit) comments printed with different spacing before the
6512 // comment causing different diffs with the 'C' disassembler library API.
6513 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006514
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006515 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006516 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006517 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006518 return;
6519 }
6520
Tim Northover09ca33e2016-04-22 23:23:31 +00006521 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006522 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6523 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6524 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006525 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006526 std::unique_ptr<MCInstPrinter> ThumbIP;
6527 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006528 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6529 struct DisassembleInfo ThumbSymbolizerInfo;
6530 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006531 if (ThumbTarget) {
6532 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6533 ThumbAsmInfo.reset(
6534 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6535 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006536 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6537 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006538 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6539 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006540 MCContext *PtrThumbCtx = ThumbCtx.get();
6541 ThumbRelInfo.reset(
6542 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6543 if (ThumbRelInfo) {
6544 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6545 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006546 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006547 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6548 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006549 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6550 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006551 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6552 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006553 // Set the display preference for hex vs. decimal immediates.
6554 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006555 }
6556
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006557 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006558 errs() << "error: couldn't initialize disassembler for target "
6559 << ThumbTripleName << '\n';
6560 return;
6561 }
6562
Charles Davis8bdfafd2013-09-01 04:28:48 +00006563 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006564
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006565 // FIXME: Using the -cfg command line option, this code used to be able to
6566 // annotate relocations with the referenced symbol's name, and if this was
6567 // inside a __[cf]string section, the data it points to. This is now replaced
6568 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006569 std::vector<SectionRef> Sections;
6570 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006571 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006572 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006573
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006574 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006575 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006576
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006577 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006578 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006579
Kevin Enderby273ae012013-06-06 17:20:50 +00006580 // Build a data in code table that is sorted on by the address of each entry.
6581 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006582 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006583 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006584 else
6585 BaseAddress = BaseSegmentAddress;
6586 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006587 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006588 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006589 uint32_t Offset;
6590 DI->getOffset(Offset);
6591 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6592 }
6593 array_pod_sort(Dices.begin(), Dices.end());
6594
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006595#ifndef NDEBUG
6596 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6597#else
6598 raw_ostream &DebugOut = nulls();
6599#endif
6600
Ahmed Charles56440fd2014-03-06 05:51:42 +00006601 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006602 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006603 // Try to find debug info and set up the DIContext for it.
6604 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006605 // A separate DSym file path was specified, parse it as a macho file,
6606 // get the sections and supply it to the section name parsing machinery.
6607 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006608 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006609 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006610 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006611 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006612 return;
6613 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006614 DbgObj =
6615 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6616 .get()
6617 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006618 }
6619
Eric Christopher7370b552012-11-12 21:40:38 +00006620 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00006621 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00006622 }
6623
Colin LeMahieufcc32762015-07-29 19:08:10 +00006624 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006625 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006626
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006627 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006628 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006629 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6630 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006631
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006632 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006633
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006634 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006635 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006636 continue;
6637
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006638 StringRef BytesStr;
6639 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006640 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6641 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006642 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006643
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006644 bool symbolTableWorked = false;
6645
Kevin Enderbybf246f52014-09-24 23:08:22 +00006646 // Create a map of symbol addresses to symbol names for use by
6647 // the SymbolizerSymbolLookUp() routine.
6648 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006649 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006650 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006651 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006652 if (!STOrErr)
6653 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006654 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006655 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6656 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006657 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006658 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006659 if (!SymNameOrErr)
6660 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006661 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006662 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006663 if (!DisSymName.empty() && DisSymName == SymName)
6664 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006665 }
6666 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006667 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006668 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6669 return;
6670 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006671 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006672 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006673 SymbolizerInfo.O = MachOOF;
6674 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006675 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006676 SymbolizerInfo.Sections = &Sections;
6677 SymbolizerInfo.class_name = nullptr;
6678 SymbolizerInfo.selector_name = nullptr;
6679 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006680 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006681 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006682 SymbolizerInfo.adrp_addr = 0;
6683 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006684 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006685 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006686 ThumbSymbolizerInfo.O = MachOOF;
6687 ThumbSymbolizerInfo.S = Sections[SectIdx];
6688 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6689 ThumbSymbolizerInfo.Sections = &Sections;
6690 ThumbSymbolizerInfo.class_name = nullptr;
6691 ThumbSymbolizerInfo.selector_name = nullptr;
6692 ThumbSymbolizerInfo.method = nullptr;
6693 ThumbSymbolizerInfo.demangled_name = nullptr;
6694 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006695 ThumbSymbolizerInfo.adrp_addr = 0;
6696 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006697
Kevin Enderby4b627be2016-04-28 20:14:13 +00006698 unsigned int Arch = MachOOF->getArch();
6699
Tim Northoverf203ab52016-07-14 22:13:32 +00006700 // Skip all symbols if this is a stubs file.
6701 if (Bytes.size() == 0)
6702 return;
6703
Kevin Enderbyc138da32017-02-06 18:43:18 +00006704 // If the section has symbols but no symbol at the start of the section
6705 // these are used to make sure the bytes before the first symbol are
6706 // disassembled.
6707 bool FirstSymbol = true;
6708 bool FirstSymbolAtSectionStart = true;
6709
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006710 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006711 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006712 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006713 if (!SymNameOrErr)
6714 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006715 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006716
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006717 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006718 if (!STOrErr)
6719 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006720 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006721 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006722 continue;
6723
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006724 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006725 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006726 if (!containsSym) {
6727 if (!DisSymName.empty() && DisSymName == SymName) {
6728 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6729 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006730 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006731 continue;
6732 }
6733 // The __mh_execute_header is special and we need to deal with that fact
6734 // this symbol is before the start of the (__TEXT,__text) section and at the
6735 // address of the start of the __TEXT segment. This is because this symbol
6736 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6737 // start of the section in a standard MH_EXECUTE filetype.
6738 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6739 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6740 return;
6741 }
Tim Northoverfbefee32016-07-14 23:13:03 +00006742 // When this code is trying to disassemble a symbol at a time and in the
6743 // case there is only the __mh_execute_header symbol left as in a stripped
6744 // executable, we need to deal with this by ignoring this symbol so the
6745 // whole section is disassembled and this symbol is then not displayed.
6746 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6747 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6748 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006749 continue;
6750
Kevin Enderby6a221752015-03-17 17:10:57 +00006751 // If we are only disassembling one symbol see if this is that symbol.
6752 if (!DisSymName.empty() && DisSymName != SymName)
6753 continue;
6754
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006755 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00006756 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00006757 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006758 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006759 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006760
Tim Northoverf203ab52016-07-14 22:13:32 +00006761 if (Start > SectSize) {
6762 outs() << "section data ends, " << SymName
6763 << " lies outside valid range\n";
6764 return;
6765 }
6766
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006767 // Stop disassembling either at the beginning of the next symbol or at
6768 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006769 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006770 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006771 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006772 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006773 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006774 if (!STOrErr)
6775 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006776 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006777 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006778 containsNextSym =
6779 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006780 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006781 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006782 break;
6783 }
6784 ++NextSymIdx;
6785 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006786
Tim Northoverf203ab52016-07-14 22:13:32 +00006787 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006788 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006789
6790 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006791
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006792 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006793 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6794
6795 // We only need the dedicated Thumb target if there's a real choice
6796 // (i.e. we're not targeting M-class) and the function is Thumb.
6797 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006798
Kevin Enderbyc138da32017-02-06 18:43:18 +00006799 // If we are not specifying a symbol to start disassembly with and this
6800 // is the first symbol in the section but not at the start of the section
6801 // then move the disassembly index to the start of the section and
6802 // don't print the symbol name just yet. This is so the bytes before the
6803 // first symbol are disassembled.
6804 uint64_t SymbolStart = Start;
6805 if (DisSymName.empty() && FirstSymbol && Start != 0) {
6806 FirstSymbolAtSectionStart = false;
6807 Start = 0;
6808 }
6809 else
6810 outs() << SymName << ":\n";
6811
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006812 DILineInfo lastLine;
6813 for (uint64_t Index = Start; Index < End; Index += Size) {
6814 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006815
Kevin Enderbyc138da32017-02-06 18:43:18 +00006816 // If this is the first symbol in the section and it was not at the
6817 // start of the section, see if we are at its Index now and if so print
6818 // the symbol name.
6819 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
6820 outs() << SymName << ":\n";
6821
Kevin Enderbybf246f52014-09-24 23:08:22 +00006822 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006823 if (!NoLeadingAddr) {
6824 if (FullLeadingAddr) {
6825 if (MachOOF->is64Bit())
6826 outs() << format("%016" PRIx64, PC);
6827 else
6828 outs() << format("%08" PRIx64, PC);
6829 } else {
6830 outs() << format("%8" PRIx64 ":", PC);
6831 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006832 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006833 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006834 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006835
6836 // Check the data in code table here to see if this is data not an
6837 // instruction to be disassembled.
6838 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006839 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006840 dice_table_iterator DTI =
6841 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6842 compareDiceTableEntries);
6843 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006844 uint16_t Length;
6845 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006846 uint16_t Kind;
6847 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006848 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006849 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6850 (PC == (DTI->first + Length - 1)) && (Length & 1))
6851 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006852 continue;
6853 }
6854
Kevin Enderbybf246f52014-09-24 23:08:22 +00006855 SmallVector<char, 64> AnnotationsBytes;
6856 raw_svector_ostream Annotations(AnnotationsBytes);
6857
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006858 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006859 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006860 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006861 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006862 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006863 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006864 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006865 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006866 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006867 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006868 }
6869 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006870 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006871 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006872 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006873 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006874 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006875 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006876
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006877 // Print debug info.
6878 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006879 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006880 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006881 if (dli != lastLine && dli.Line != 0)
6882 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6883 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006884 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006885 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006886 outs() << "\n";
6887 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006888 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006889 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006890 outs() << format("\t.byte 0x%02x #bad opcode\n",
6891 *(Bytes.data() + Index) & 0xff);
6892 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006893 } else if (Arch == Triple::aarch64 ||
6894 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006895 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6896 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6897 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6898 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6899 outs() << format("\t.long\t0x%08x\n", opcode);
6900 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006901 } else if (Arch == Triple::arm) {
6902 assert(IsThumb && "ARM mode should have been dealt with above");
6903 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6904 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6905 outs() << format("\t.short\t0x%04x\n", opcode);
6906 Size = 2;
6907 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006908 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6909 if (Size == 0)
6910 Size = 1; // skip illegible bytes
6911 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006912 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006913 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00006914 // Now that we are done disassembled the first symbol set the bool that
6915 // were doing this to false.
6916 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006917 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006918 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006919 // Reading the symbol table didn't work, disassemble the whole section.
6920 uint64_t SectAddress = Sections[SectIdx].getAddress();
6921 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006922 uint64_t InstSize;
6923 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006924 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006925
Kevin Enderbybf246f52014-09-24 23:08:22 +00006926 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00006927 SmallVector<char, 64> AnnotationsBytes;
6928 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006929 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00006930 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006931 if (!NoLeadingAddr) {
6932 if (FullLeadingAddr) {
6933 if (MachOOF->is64Bit())
6934 outs() << format("%016" PRIx64, PC);
6935 else
6936 outs() << format("%08" PRIx64, PC);
6937 } else {
6938 outs() << format("%8" PRIx64 ":", PC);
6939 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006940 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006941 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006942 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006943 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006944 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00006945 StringRef AnnotationsStr = Annotations.str();
6946 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006947 outs() << "\n";
6948 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006949 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006950 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006951 outs() << format("\t.byte 0x%02x #bad opcode\n",
6952 *(Bytes.data() + Index) & 0xff);
6953 InstSize = 1; // skip exactly one illegible byte and move on.
6954 } else {
6955 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6956 if (InstSize == 0)
6957 InstSize = 1; // skip illegible bytes
6958 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006959 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006960 }
6961 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006962 // The TripleName's need to be reset if we are called again for a different
6963 // archtecture.
6964 TripleName = "";
6965 ThumbTripleName = "";
6966
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006967 if (SymbolizerInfo.method != nullptr)
6968 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006969 if (SymbolizerInfo.demangled_name != nullptr)
6970 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006971 if (ThumbSymbolizerInfo.method != nullptr)
6972 free(ThumbSymbolizerInfo.method);
6973 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6974 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006975 }
6976}
Tim Northover4bd286a2014-08-01 13:07:19 +00006977
Tim Northover39c70bb2014-08-12 11:52:59 +00006978//===----------------------------------------------------------------------===//
6979// __compact_unwind section dumping
6980//===----------------------------------------------------------------------===//
6981
Tim Northover4bd286a2014-08-01 13:07:19 +00006982namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006983
6984template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006985 using llvm::support::little;
6986 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006987
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006988 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6989 Buf += sizeof(T);
6990 return Val;
6991}
Tim Northover39c70bb2014-08-12 11:52:59 +00006992
Tim Northover4bd286a2014-08-01 13:07:19 +00006993struct CompactUnwindEntry {
6994 uint32_t OffsetInSection;
6995
6996 uint64_t FunctionAddr;
6997 uint32_t Length;
6998 uint32_t CompactEncoding;
6999 uint64_t PersonalityAddr;
7000 uint64_t LSDAAddr;
7001
7002 RelocationRef FunctionReloc;
7003 RelocationRef PersonalityReloc;
7004 RelocationRef LSDAReloc;
7005
7006 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007007 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007008 if (Is64)
7009 read<uint64_t>(Contents.data() + Offset);
7010 else
7011 read<uint32_t>(Contents.data() + Offset);
7012 }
7013
7014private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007015 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007016 FunctionAddr = readNext<UIntPtr>(Buf);
7017 Length = readNext<uint32_t>(Buf);
7018 CompactEncoding = readNext<uint32_t>(Buf);
7019 PersonalityAddr = readNext<UIntPtr>(Buf);
7020 LSDAAddr = readNext<UIntPtr>(Buf);
7021 }
7022};
7023}
7024
7025/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7026/// and data being relocated, determine the best base Name and Addend to use for
7027/// display purposes.
7028///
7029/// 1. An Extern relocation will directly reference a symbol (and the data is
7030/// then already an addend), so use that.
7031/// 2. Otherwise the data is an offset in the object file's layout; try to find
7032// a symbol before it in the same section, and use the offset from there.
7033/// 3. Finally, if all that fails, fall back to an offset from the start of the
7034/// referenced section.
7035static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7036 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007037 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007038 StringRef &Name, uint64_t &Addend) {
7039 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007040 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007041 if (!NameOrErr)
7042 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007043 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007044 Addend = Addr;
7045 return;
7046 }
7047
7048 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007049 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007050
Rafael Espindola80291272014-10-08 15:28:58 +00007051 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007052
7053 auto Sym = Symbols.upper_bound(Addr);
7054 if (Sym == Symbols.begin()) {
7055 // The first symbol in the object is after this reference, the best we can
7056 // do is section-relative notation.
7057 RelocSection.getName(Name);
7058 Addend = Addr - SectionAddr;
7059 return;
7060 }
7061
7062 // Go back one so that SymbolAddress <= Addr.
7063 --Sym;
7064
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007065 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007066 if (!SectOrErr)
7067 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007068 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007069 if (RelocSection == *SymSection) {
7070 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007071 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007072 if (!NameOrErr)
7073 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007074 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007075 Addend = Addr - Sym->first;
7076 return;
7077 }
7078
7079 // There is a symbol before this reference, but it's in a different
7080 // section. Probably not helpful to mention it, so use the section name.
7081 RelocSection.getName(Name);
7082 Addend = Addr - SectionAddr;
7083}
7084
7085static void printUnwindRelocDest(const MachOObjectFile *Obj,
7086 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007087 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007088 StringRef Name;
7089 uint64_t Addend;
7090
Rafael Espindola854038e2015-06-26 14:51:16 +00007091 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007092 return;
7093
Tim Northover4bd286a2014-08-01 13:07:19 +00007094 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7095
7096 outs() << Name;
7097 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007098 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007099}
7100
7101static void
7102printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7103 std::map<uint64_t, SymbolRef> &Symbols,
7104 const SectionRef &CompactUnwind) {
7105
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007106 if (!Obj->isLittleEndian()) {
7107 outs() << "Skipping big-endian __compact_unwind section\n";
7108 return;
7109 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007110
7111 bool Is64 = Obj->is64Bit();
7112 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7113 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7114
7115 StringRef Contents;
7116 CompactUnwind.getContents(Contents);
7117
7118 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7119
7120 // First populate the initial raw offsets, encodings and so on from the entry.
7121 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7122 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7123 CompactUnwinds.push_back(Entry);
7124 }
7125
7126 // Next we need to look at the relocations to find out what objects are
7127 // actually being referred to.
7128 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007129 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007130
7131 uint32_t EntryIdx = RelocAddress / EntrySize;
7132 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7133 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7134
7135 if (OffsetInEntry == 0)
7136 Entry.FunctionReloc = Reloc;
7137 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7138 Entry.PersonalityReloc = Reloc;
7139 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7140 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007141 else {
7142 outs() << "Invalid relocation in __compact_unwind section\n";
7143 return;
7144 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007145 }
7146
7147 // Finally, we're ready to print the data we've gathered.
7148 outs() << "Contents of __compact_unwind section:\n";
7149 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007150 outs() << " Entry at offset "
7151 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007152
7153 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007154 outs() << " start: " << format("0x%" PRIx64,
7155 Entry.FunctionAddr) << ' ';
7156 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007157 outs() << '\n';
7158
7159 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007160 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7161 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007162 // 3. The 32-bit compact encoding.
7163 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007164 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007165
7166 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007167 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007168 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007169 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007170 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7171 Entry.PersonalityAddr);
7172 outs() << '\n';
7173 }
7174
7175 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007176 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007177 outs() << " LSDA: " << format("0x%" PRIx64,
7178 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007179 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7180 outs() << '\n';
7181 }
7182 }
7183}
7184
Tim Northover39c70bb2014-08-12 11:52:59 +00007185//===----------------------------------------------------------------------===//
7186// __unwind_info section dumping
7187//===----------------------------------------------------------------------===//
7188
7189static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7190 const char *Pos = PageStart;
7191 uint32_t Kind = readNext<uint32_t>(Pos);
7192 (void)Kind;
7193 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7194
7195 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7196 uint16_t NumEntries = readNext<uint16_t>(Pos);
7197
7198 Pos = PageStart + EntriesStart;
7199 for (unsigned i = 0; i < NumEntries; ++i) {
7200 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7201 uint32_t Encoding = readNext<uint32_t>(Pos);
7202
7203 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007204 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7205 << ", "
7206 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007207 }
7208}
7209
7210static void printCompressedSecondLevelUnwindPage(
7211 const char *PageStart, uint32_t FunctionBase,
7212 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7213 const char *Pos = PageStart;
7214 uint32_t Kind = readNext<uint32_t>(Pos);
7215 (void)Kind;
7216 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7217
7218 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7219 uint16_t NumEntries = readNext<uint16_t>(Pos);
7220
7221 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7222 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007223 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7224 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007225
7226 Pos = PageStart + EntriesStart;
7227 for (unsigned i = 0; i < NumEntries; ++i) {
7228 uint32_t Entry = readNext<uint32_t>(Pos);
7229 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7230 uint32_t EncodingIdx = Entry >> 24;
7231
7232 uint32_t Encoding;
7233 if (EncodingIdx < CommonEncodings.size())
7234 Encoding = CommonEncodings[EncodingIdx];
7235 else
7236 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7237
7238 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007239 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7240 << ", "
7241 << "encoding[" << EncodingIdx
7242 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007243 }
7244}
7245
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007246static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7247 std::map<uint64_t, SymbolRef> &Symbols,
7248 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007249
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007250 if (!Obj->isLittleEndian()) {
7251 outs() << "Skipping big-endian __unwind_info section\n";
7252 return;
7253 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007254
7255 outs() << "Contents of __unwind_info section:\n";
7256
7257 StringRef Contents;
7258 UnwindInfo.getContents(Contents);
7259 const char *Pos = Contents.data();
7260
7261 //===----------------------------------
7262 // Section header
7263 //===----------------------------------
7264
7265 uint32_t Version = readNext<uint32_t>(Pos);
7266 outs() << " Version: "
7267 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007268 if (Version != 1) {
7269 outs() << " Skipping section with unknown version\n";
7270 return;
7271 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007272
7273 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7274 outs() << " Common encodings array section offset: "
7275 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7276 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7277 outs() << " Number of common encodings in array: "
7278 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7279
7280 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7281 outs() << " Personality function array section offset: "
7282 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7283 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7284 outs() << " Number of personality functions in array: "
7285 << format("0x%" PRIx32, NumPersonalities) << '\n';
7286
7287 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7288 outs() << " Index array section offset: "
7289 << format("0x%" PRIx32, IndicesStart) << '\n';
7290 uint32_t NumIndices = readNext<uint32_t>(Pos);
7291 outs() << " Number of indices in array: "
7292 << format("0x%" PRIx32, NumIndices) << '\n';
7293
7294 //===----------------------------------
7295 // A shared list of common encodings
7296 //===----------------------------------
7297
7298 // These occupy indices in the range [0, N] whenever an encoding is referenced
7299 // from a compressed 2nd level index table. In practice the linker only
7300 // creates ~128 of these, so that indices are available to embed encodings in
7301 // the 2nd level index.
7302
7303 SmallVector<uint32_t, 64> CommonEncodings;
7304 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7305 Pos = Contents.data() + CommonEncodingsStart;
7306 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7307 uint32_t Encoding = readNext<uint32_t>(Pos);
7308 CommonEncodings.push_back(Encoding);
7309
7310 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7311 << '\n';
7312 }
7313
Tim Northover39c70bb2014-08-12 11:52:59 +00007314 //===----------------------------------
7315 // Personality functions used in this executable
7316 //===----------------------------------
7317
7318 // There should be only a handful of these (one per source language,
7319 // roughly). Particularly since they only get 2 bits in the compact encoding.
7320
7321 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7322 Pos = Contents.data() + PersonalitiesStart;
7323 for (unsigned i = 0; i < NumPersonalities; ++i) {
7324 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7325 outs() << " personality[" << i + 1
7326 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7327 }
7328
7329 //===----------------------------------
7330 // The level 1 index entries
7331 //===----------------------------------
7332
7333 // These specify an approximate place to start searching for the more detailed
7334 // information, sorted by PC.
7335
7336 struct IndexEntry {
7337 uint32_t FunctionOffset;
7338 uint32_t SecondLevelPageStart;
7339 uint32_t LSDAStart;
7340 };
7341
7342 SmallVector<IndexEntry, 4> IndexEntries;
7343
7344 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7345 Pos = Contents.data() + IndicesStart;
7346 for (unsigned i = 0; i < NumIndices; ++i) {
7347 IndexEntry Entry;
7348
7349 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7350 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7351 Entry.LSDAStart = readNext<uint32_t>(Pos);
7352 IndexEntries.push_back(Entry);
7353
7354 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007355 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7356 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007357 << "2nd level page offset="
7358 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007359 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007360 }
7361
Tim Northover39c70bb2014-08-12 11:52:59 +00007362 //===----------------------------------
7363 // Next come the LSDA tables
7364 //===----------------------------------
7365
7366 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7367 // the first top-level index's LSDAOffset to the last (sentinel).
7368
7369 outs() << " LSDA descriptors:\n";
7370 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7371 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7372 (2 * sizeof(uint32_t));
7373 for (int i = 0; i < NumLSDAs; ++i) {
7374 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7375 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7376 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007377 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7378 << ", "
7379 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007380 }
7381
7382 //===----------------------------------
7383 // Finally, the 2nd level indices
7384 //===----------------------------------
7385
7386 // Generally these are 4K in size, and have 2 possible forms:
7387 // + Regular stores up to 511 entries with disparate encodings
7388 // + Compressed stores up to 1021 entries if few enough compact encoding
7389 // values are used.
7390 outs() << " Second level indices:\n";
7391 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7392 // The final sentinel top-level index has no associated 2nd level page
7393 if (IndexEntries[i].SecondLevelPageStart == 0)
7394 break;
7395
7396 outs() << " Second level index[" << i << "]: "
7397 << "offset in section="
7398 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7399 << ", "
7400 << "base function offset="
7401 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7402
7403 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007404 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007405 if (Kind == 2)
7406 printRegularSecondLevelUnwindPage(Pos);
7407 else if (Kind == 3)
7408 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7409 CommonEncodings);
7410 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007411 outs() << " Skipping 2nd level page with unknown kind " << Kind
7412 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007413 }
7414}
7415
Tim Northover4bd286a2014-08-01 13:07:19 +00007416void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7417 std::map<uint64_t, SymbolRef> Symbols;
7418 for (const SymbolRef &SymRef : Obj->symbols()) {
7419 // Discard any undefined or absolute symbols. They're not going to take part
7420 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007421 auto SectOrErr = SymRef.getSection();
7422 if (!SectOrErr) {
7423 // TODO: Actually report errors helpfully.
7424 consumeError(SectOrErr.takeError());
7425 continue;
7426 }
7427 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007428 if (Section == Obj->section_end())
7429 continue;
7430
Rafael Espindoladea00162015-07-03 17:44:18 +00007431 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007432 Symbols.insert(std::make_pair(Addr, SymRef));
7433 }
7434
7435 for (const SectionRef &Section : Obj->sections()) {
7436 StringRef SectName;
7437 Section.getName(SectName);
7438 if (SectName == "__compact_unwind")
7439 printMachOCompactUnwindSection(Obj, Symbols, Section);
7440 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007441 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007442 }
7443}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007444
7445static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7446 uint32_t cpusubtype, uint32_t filetype,
7447 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7448 bool verbose) {
7449 outs() << "Mach header\n";
7450 outs() << " magic cputype cpusubtype caps filetype ncmds "
7451 "sizeofcmds flags\n";
7452 if (verbose) {
7453 if (magic == MachO::MH_MAGIC)
7454 outs() << " MH_MAGIC";
7455 else if (magic == MachO::MH_MAGIC_64)
7456 outs() << "MH_MAGIC_64";
7457 else
7458 outs() << format(" 0x%08" PRIx32, magic);
7459 switch (cputype) {
7460 case MachO::CPU_TYPE_I386:
7461 outs() << " I386";
7462 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7463 case MachO::CPU_SUBTYPE_I386_ALL:
7464 outs() << " ALL";
7465 break;
7466 default:
7467 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7468 break;
7469 }
7470 break;
7471 case MachO::CPU_TYPE_X86_64:
7472 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007473 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7474 case MachO::CPU_SUBTYPE_X86_64_ALL:
7475 outs() << " ALL";
7476 break;
7477 case MachO::CPU_SUBTYPE_X86_64_H:
7478 outs() << " Haswell";
7479 break;
7480 default:
7481 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7482 break;
7483 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007484 break;
7485 case MachO::CPU_TYPE_ARM:
7486 outs() << " ARM";
7487 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7488 case MachO::CPU_SUBTYPE_ARM_ALL:
7489 outs() << " ALL";
7490 break;
7491 case MachO::CPU_SUBTYPE_ARM_V4T:
7492 outs() << " V4T";
7493 break;
7494 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7495 outs() << " V5TEJ";
7496 break;
7497 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7498 outs() << " XSCALE";
7499 break;
7500 case MachO::CPU_SUBTYPE_ARM_V6:
7501 outs() << " V6";
7502 break;
7503 case MachO::CPU_SUBTYPE_ARM_V6M:
7504 outs() << " V6M";
7505 break;
7506 case MachO::CPU_SUBTYPE_ARM_V7:
7507 outs() << " V7";
7508 break;
7509 case MachO::CPU_SUBTYPE_ARM_V7EM:
7510 outs() << " V7EM";
7511 break;
7512 case MachO::CPU_SUBTYPE_ARM_V7K:
7513 outs() << " V7K";
7514 break;
7515 case MachO::CPU_SUBTYPE_ARM_V7M:
7516 outs() << " V7M";
7517 break;
7518 case MachO::CPU_SUBTYPE_ARM_V7S:
7519 outs() << " V7S";
7520 break;
7521 default:
7522 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7523 break;
7524 }
7525 break;
7526 case MachO::CPU_TYPE_ARM64:
7527 outs() << " ARM64";
7528 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7529 case MachO::CPU_SUBTYPE_ARM64_ALL:
7530 outs() << " ALL";
7531 break;
7532 default:
7533 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7534 break;
7535 }
7536 break;
7537 case MachO::CPU_TYPE_POWERPC:
7538 outs() << " PPC";
7539 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7540 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7541 outs() << " ALL";
7542 break;
7543 default:
7544 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7545 break;
7546 }
7547 break;
7548 case MachO::CPU_TYPE_POWERPC64:
7549 outs() << " PPC64";
7550 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7551 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7552 outs() << " ALL";
7553 break;
7554 default:
7555 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7556 break;
7557 }
7558 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007559 default:
7560 outs() << format(" %7d", cputype);
7561 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7562 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007563 }
7564 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007565 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007566 } else {
7567 outs() << format(" 0x%02" PRIx32,
7568 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7569 }
7570 switch (filetype) {
7571 case MachO::MH_OBJECT:
7572 outs() << " OBJECT";
7573 break;
7574 case MachO::MH_EXECUTE:
7575 outs() << " EXECUTE";
7576 break;
7577 case MachO::MH_FVMLIB:
7578 outs() << " FVMLIB";
7579 break;
7580 case MachO::MH_CORE:
7581 outs() << " CORE";
7582 break;
7583 case MachO::MH_PRELOAD:
7584 outs() << " PRELOAD";
7585 break;
7586 case MachO::MH_DYLIB:
7587 outs() << " DYLIB";
7588 break;
7589 case MachO::MH_DYLIB_STUB:
7590 outs() << " DYLIB_STUB";
7591 break;
7592 case MachO::MH_DYLINKER:
7593 outs() << " DYLINKER";
7594 break;
7595 case MachO::MH_BUNDLE:
7596 outs() << " BUNDLE";
7597 break;
7598 case MachO::MH_DSYM:
7599 outs() << " DSYM";
7600 break;
7601 case MachO::MH_KEXT_BUNDLE:
7602 outs() << " KEXTBUNDLE";
7603 break;
7604 default:
7605 outs() << format(" %10u", filetype);
7606 break;
7607 }
7608 outs() << format(" %5u", ncmds);
7609 outs() << format(" %10u", sizeofcmds);
7610 uint32_t f = flags;
7611 if (f & MachO::MH_NOUNDEFS) {
7612 outs() << " NOUNDEFS";
7613 f &= ~MachO::MH_NOUNDEFS;
7614 }
7615 if (f & MachO::MH_INCRLINK) {
7616 outs() << " INCRLINK";
7617 f &= ~MachO::MH_INCRLINK;
7618 }
7619 if (f & MachO::MH_DYLDLINK) {
7620 outs() << " DYLDLINK";
7621 f &= ~MachO::MH_DYLDLINK;
7622 }
7623 if (f & MachO::MH_BINDATLOAD) {
7624 outs() << " BINDATLOAD";
7625 f &= ~MachO::MH_BINDATLOAD;
7626 }
7627 if (f & MachO::MH_PREBOUND) {
7628 outs() << " PREBOUND";
7629 f &= ~MachO::MH_PREBOUND;
7630 }
7631 if (f & MachO::MH_SPLIT_SEGS) {
7632 outs() << " SPLIT_SEGS";
7633 f &= ~MachO::MH_SPLIT_SEGS;
7634 }
7635 if (f & MachO::MH_LAZY_INIT) {
7636 outs() << " LAZY_INIT";
7637 f &= ~MachO::MH_LAZY_INIT;
7638 }
7639 if (f & MachO::MH_TWOLEVEL) {
7640 outs() << " TWOLEVEL";
7641 f &= ~MachO::MH_TWOLEVEL;
7642 }
7643 if (f & MachO::MH_FORCE_FLAT) {
7644 outs() << " FORCE_FLAT";
7645 f &= ~MachO::MH_FORCE_FLAT;
7646 }
7647 if (f & MachO::MH_NOMULTIDEFS) {
7648 outs() << " NOMULTIDEFS";
7649 f &= ~MachO::MH_NOMULTIDEFS;
7650 }
7651 if (f & MachO::MH_NOFIXPREBINDING) {
7652 outs() << " NOFIXPREBINDING";
7653 f &= ~MachO::MH_NOFIXPREBINDING;
7654 }
7655 if (f & MachO::MH_PREBINDABLE) {
7656 outs() << " PREBINDABLE";
7657 f &= ~MachO::MH_PREBINDABLE;
7658 }
7659 if (f & MachO::MH_ALLMODSBOUND) {
7660 outs() << " ALLMODSBOUND";
7661 f &= ~MachO::MH_ALLMODSBOUND;
7662 }
7663 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7664 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7665 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7666 }
7667 if (f & MachO::MH_CANONICAL) {
7668 outs() << " CANONICAL";
7669 f &= ~MachO::MH_CANONICAL;
7670 }
7671 if (f & MachO::MH_WEAK_DEFINES) {
7672 outs() << " WEAK_DEFINES";
7673 f &= ~MachO::MH_WEAK_DEFINES;
7674 }
7675 if (f & MachO::MH_BINDS_TO_WEAK) {
7676 outs() << " BINDS_TO_WEAK";
7677 f &= ~MachO::MH_BINDS_TO_WEAK;
7678 }
7679 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7680 outs() << " ALLOW_STACK_EXECUTION";
7681 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7682 }
7683 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7684 outs() << " DEAD_STRIPPABLE_DYLIB";
7685 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7686 }
7687 if (f & MachO::MH_PIE) {
7688 outs() << " PIE";
7689 f &= ~MachO::MH_PIE;
7690 }
7691 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7692 outs() << " NO_REEXPORTED_DYLIBS";
7693 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7694 }
7695 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7696 outs() << " MH_HAS_TLV_DESCRIPTORS";
7697 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7698 }
7699 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7700 outs() << " MH_NO_HEAP_EXECUTION";
7701 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7702 }
7703 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7704 outs() << " APP_EXTENSION_SAFE";
7705 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7706 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00007707 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
7708 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
7709 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
7710 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007711 if (f != 0 || flags == 0)
7712 outs() << format(" 0x%08" PRIx32, f);
7713 } else {
7714 outs() << format(" 0x%08" PRIx32, magic);
7715 outs() << format(" %7d", cputype);
7716 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7717 outs() << format(" 0x%02" PRIx32,
7718 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7719 outs() << format(" %10u", filetype);
7720 outs() << format(" %5u", ncmds);
7721 outs() << format(" %10u", sizeofcmds);
7722 outs() << format(" 0x%08" PRIx32, flags);
7723 }
7724 outs() << "\n";
7725}
7726
Kevin Enderby956366c2014-08-29 22:30:52 +00007727static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7728 StringRef SegName, uint64_t vmaddr,
7729 uint64_t vmsize, uint64_t fileoff,
7730 uint64_t filesize, uint32_t maxprot,
7731 uint32_t initprot, uint32_t nsects,
7732 uint32_t flags, uint32_t object_size,
7733 bool verbose) {
7734 uint64_t expected_cmdsize;
7735 if (cmd == MachO::LC_SEGMENT) {
7736 outs() << " cmd LC_SEGMENT\n";
7737 expected_cmdsize = nsects;
7738 expected_cmdsize *= sizeof(struct MachO::section);
7739 expected_cmdsize += sizeof(struct MachO::segment_command);
7740 } else {
7741 outs() << " cmd LC_SEGMENT_64\n";
7742 expected_cmdsize = nsects;
7743 expected_cmdsize *= sizeof(struct MachO::section_64);
7744 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7745 }
7746 outs() << " cmdsize " << cmdsize;
7747 if (cmdsize != expected_cmdsize)
7748 outs() << " Inconsistent size\n";
7749 else
7750 outs() << "\n";
7751 outs() << " segname " << SegName << "\n";
7752 if (cmd == MachO::LC_SEGMENT_64) {
7753 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7754 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7755 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007756 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7757 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007758 }
7759 outs() << " fileoff " << fileoff;
7760 if (fileoff > object_size)
7761 outs() << " (past end of file)\n";
7762 else
7763 outs() << "\n";
7764 outs() << " filesize " << filesize;
7765 if (fileoff + filesize > object_size)
7766 outs() << " (past end of file)\n";
7767 else
7768 outs() << "\n";
7769 if (verbose) {
7770 if ((maxprot &
7771 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7772 MachO::VM_PROT_EXECUTE)) != 0)
7773 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7774 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007775 outs() << " maxprot ";
7776 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7777 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7778 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007779 }
7780 if ((initprot &
7781 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7782 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00007783 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007784 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00007785 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00007786 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7787 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7788 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007789 }
7790 } else {
7791 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7792 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7793 }
7794 outs() << " nsects " << nsects << "\n";
7795 if (verbose) {
7796 outs() << " flags";
7797 if (flags == 0)
7798 outs() << " (none)\n";
7799 else {
7800 if (flags & MachO::SG_HIGHVM) {
7801 outs() << " HIGHVM";
7802 flags &= ~MachO::SG_HIGHVM;
7803 }
7804 if (flags & MachO::SG_FVMLIB) {
7805 outs() << " FVMLIB";
7806 flags &= ~MachO::SG_FVMLIB;
7807 }
7808 if (flags & MachO::SG_NORELOC) {
7809 outs() << " NORELOC";
7810 flags &= ~MachO::SG_NORELOC;
7811 }
7812 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7813 outs() << " PROTECTED_VERSION_1";
7814 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7815 }
7816 if (flags)
7817 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7818 else
7819 outs() << "\n";
7820 }
7821 } else {
7822 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7823 }
7824}
7825
7826static void PrintSection(const char *sectname, const char *segname,
7827 uint64_t addr, uint64_t size, uint32_t offset,
7828 uint32_t align, uint32_t reloff, uint32_t nreloc,
7829 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7830 uint32_t cmd, const char *sg_segname,
7831 uint32_t filetype, uint32_t object_size,
7832 bool verbose) {
7833 outs() << "Section\n";
7834 outs() << " sectname " << format("%.16s\n", sectname);
7835 outs() << " segname " << format("%.16s", segname);
7836 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7837 outs() << " (does not match segment)\n";
7838 else
7839 outs() << "\n";
7840 if (cmd == MachO::LC_SEGMENT_64) {
7841 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7842 outs() << " size " << format("0x%016" PRIx64, size);
7843 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007844 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7845 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007846 }
7847 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7848 outs() << " (past end of file)\n";
7849 else
7850 outs() << "\n";
7851 outs() << " offset " << offset;
7852 if (offset > object_size)
7853 outs() << " (past end of file)\n";
7854 else
7855 outs() << "\n";
7856 uint32_t align_shifted = 1 << align;
7857 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7858 outs() << " reloff " << reloff;
7859 if (reloff > object_size)
7860 outs() << " (past end of file)\n";
7861 else
7862 outs() << "\n";
7863 outs() << " nreloc " << nreloc;
7864 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7865 outs() << " (past end of file)\n";
7866 else
7867 outs() << "\n";
7868 uint32_t section_type = flags & MachO::SECTION_TYPE;
7869 if (verbose) {
7870 outs() << " type";
7871 if (section_type == MachO::S_REGULAR)
7872 outs() << " S_REGULAR\n";
7873 else if (section_type == MachO::S_ZEROFILL)
7874 outs() << " S_ZEROFILL\n";
7875 else if (section_type == MachO::S_CSTRING_LITERALS)
7876 outs() << " S_CSTRING_LITERALS\n";
7877 else if (section_type == MachO::S_4BYTE_LITERALS)
7878 outs() << " S_4BYTE_LITERALS\n";
7879 else if (section_type == MachO::S_8BYTE_LITERALS)
7880 outs() << " S_8BYTE_LITERALS\n";
7881 else if (section_type == MachO::S_16BYTE_LITERALS)
7882 outs() << " S_16BYTE_LITERALS\n";
7883 else if (section_type == MachO::S_LITERAL_POINTERS)
7884 outs() << " S_LITERAL_POINTERS\n";
7885 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7886 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7887 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7888 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7889 else if (section_type == MachO::S_SYMBOL_STUBS)
7890 outs() << " S_SYMBOL_STUBS\n";
7891 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7892 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7893 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7894 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7895 else if (section_type == MachO::S_COALESCED)
7896 outs() << " S_COALESCED\n";
7897 else if (section_type == MachO::S_INTERPOSING)
7898 outs() << " S_INTERPOSING\n";
7899 else if (section_type == MachO::S_DTRACE_DOF)
7900 outs() << " S_DTRACE_DOF\n";
7901 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7902 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7903 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7904 outs() << " S_THREAD_LOCAL_REGULAR\n";
7905 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7906 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7907 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7908 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7909 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7910 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7911 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7912 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7913 else
7914 outs() << format("0x%08" PRIx32, section_type) << "\n";
7915 outs() << "attributes";
7916 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7917 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7918 outs() << " PURE_INSTRUCTIONS";
7919 if (section_attributes & MachO::S_ATTR_NO_TOC)
7920 outs() << " NO_TOC";
7921 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7922 outs() << " STRIP_STATIC_SYMS";
7923 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7924 outs() << " NO_DEAD_STRIP";
7925 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7926 outs() << " LIVE_SUPPORT";
7927 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7928 outs() << " SELF_MODIFYING_CODE";
7929 if (section_attributes & MachO::S_ATTR_DEBUG)
7930 outs() << " DEBUG";
7931 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7932 outs() << " SOME_INSTRUCTIONS";
7933 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7934 outs() << " EXT_RELOC";
7935 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7936 outs() << " LOC_RELOC";
7937 if (section_attributes == 0)
7938 outs() << " (none)";
7939 outs() << "\n";
7940 } else
7941 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7942 outs() << " reserved1 " << reserved1;
7943 if (section_type == MachO::S_SYMBOL_STUBS ||
7944 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7945 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7946 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7947 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7948 outs() << " (index into indirect symbol table)\n";
7949 else
7950 outs() << "\n";
7951 outs() << " reserved2 " << reserved2;
7952 if (section_type == MachO::S_SYMBOL_STUBS)
7953 outs() << " (size of stubs)\n";
7954 else
7955 outs() << "\n";
7956}
7957
David Majnemer73cc6ff2014-11-13 19:48:56 +00007958static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007959 uint32_t object_size) {
7960 outs() << " cmd LC_SYMTAB\n";
7961 outs() << " cmdsize " << st.cmdsize;
7962 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7963 outs() << " Incorrect size\n";
7964 else
7965 outs() << "\n";
7966 outs() << " symoff " << st.symoff;
7967 if (st.symoff > object_size)
7968 outs() << " (past end of file)\n";
7969 else
7970 outs() << "\n";
7971 outs() << " nsyms " << st.nsyms;
7972 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007973 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007974 big_size = st.nsyms;
7975 big_size *= sizeof(struct MachO::nlist_64);
7976 big_size += st.symoff;
7977 if (big_size > object_size)
7978 outs() << " (past end of file)\n";
7979 else
7980 outs() << "\n";
7981 } else {
7982 big_size = st.nsyms;
7983 big_size *= sizeof(struct MachO::nlist);
7984 big_size += st.symoff;
7985 if (big_size > object_size)
7986 outs() << " (past end of file)\n";
7987 else
7988 outs() << "\n";
7989 }
7990 outs() << " stroff " << st.stroff;
7991 if (st.stroff > object_size)
7992 outs() << " (past end of file)\n";
7993 else
7994 outs() << "\n";
7995 outs() << " strsize " << st.strsize;
7996 big_size = st.stroff;
7997 big_size += st.strsize;
7998 if (big_size > object_size)
7999 outs() << " (past end of file)\n";
8000 else
8001 outs() << "\n";
8002}
8003
8004static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8005 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008006 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008007 outs() << " cmd LC_DYSYMTAB\n";
8008 outs() << " cmdsize " << dyst.cmdsize;
8009 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8010 outs() << " Incorrect size\n";
8011 else
8012 outs() << "\n";
8013 outs() << " ilocalsym " << dyst.ilocalsym;
8014 if (dyst.ilocalsym > nsyms)
8015 outs() << " (greater than the number of symbols)\n";
8016 else
8017 outs() << "\n";
8018 outs() << " nlocalsym " << dyst.nlocalsym;
8019 uint64_t big_size;
8020 big_size = dyst.ilocalsym;
8021 big_size += dyst.nlocalsym;
8022 if (big_size > nsyms)
8023 outs() << " (past the end of the symbol table)\n";
8024 else
8025 outs() << "\n";
8026 outs() << " iextdefsym " << dyst.iextdefsym;
8027 if (dyst.iextdefsym > nsyms)
8028 outs() << " (greater than the number of symbols)\n";
8029 else
8030 outs() << "\n";
8031 outs() << " nextdefsym " << dyst.nextdefsym;
8032 big_size = dyst.iextdefsym;
8033 big_size += dyst.nextdefsym;
8034 if (big_size > nsyms)
8035 outs() << " (past the end of the symbol table)\n";
8036 else
8037 outs() << "\n";
8038 outs() << " iundefsym " << dyst.iundefsym;
8039 if (dyst.iundefsym > nsyms)
8040 outs() << " (greater than the number of symbols)\n";
8041 else
8042 outs() << "\n";
8043 outs() << " nundefsym " << dyst.nundefsym;
8044 big_size = dyst.iundefsym;
8045 big_size += dyst.nundefsym;
8046 if (big_size > nsyms)
8047 outs() << " (past the end of the symbol table)\n";
8048 else
8049 outs() << "\n";
8050 outs() << " tocoff " << dyst.tocoff;
8051 if (dyst.tocoff > object_size)
8052 outs() << " (past end of file)\n";
8053 else
8054 outs() << "\n";
8055 outs() << " ntoc " << dyst.ntoc;
8056 big_size = dyst.ntoc;
8057 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8058 big_size += dyst.tocoff;
8059 if (big_size > object_size)
8060 outs() << " (past end of file)\n";
8061 else
8062 outs() << "\n";
8063 outs() << " modtaboff " << dyst.modtaboff;
8064 if (dyst.modtaboff > object_size)
8065 outs() << " (past end of file)\n";
8066 else
8067 outs() << "\n";
8068 outs() << " nmodtab " << dyst.nmodtab;
8069 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008070 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008071 modtabend = dyst.nmodtab;
8072 modtabend *= sizeof(struct MachO::dylib_module_64);
8073 modtabend += dyst.modtaboff;
8074 } else {
8075 modtabend = dyst.nmodtab;
8076 modtabend *= sizeof(struct MachO::dylib_module);
8077 modtabend += dyst.modtaboff;
8078 }
8079 if (modtabend > object_size)
8080 outs() << " (past end of file)\n";
8081 else
8082 outs() << "\n";
8083 outs() << " extrefsymoff " << dyst.extrefsymoff;
8084 if (dyst.extrefsymoff > object_size)
8085 outs() << " (past end of file)\n";
8086 else
8087 outs() << "\n";
8088 outs() << " nextrefsyms " << dyst.nextrefsyms;
8089 big_size = dyst.nextrefsyms;
8090 big_size *= sizeof(struct MachO::dylib_reference);
8091 big_size += dyst.extrefsymoff;
8092 if (big_size > object_size)
8093 outs() << " (past end of file)\n";
8094 else
8095 outs() << "\n";
8096 outs() << " indirectsymoff " << dyst.indirectsymoff;
8097 if (dyst.indirectsymoff > object_size)
8098 outs() << " (past end of file)\n";
8099 else
8100 outs() << "\n";
8101 outs() << " nindirectsyms " << dyst.nindirectsyms;
8102 big_size = dyst.nindirectsyms;
8103 big_size *= sizeof(uint32_t);
8104 big_size += dyst.indirectsymoff;
8105 if (big_size > object_size)
8106 outs() << " (past end of file)\n";
8107 else
8108 outs() << "\n";
8109 outs() << " extreloff " << dyst.extreloff;
8110 if (dyst.extreloff > object_size)
8111 outs() << " (past end of file)\n";
8112 else
8113 outs() << "\n";
8114 outs() << " nextrel " << dyst.nextrel;
8115 big_size = dyst.nextrel;
8116 big_size *= sizeof(struct MachO::relocation_info);
8117 big_size += dyst.extreloff;
8118 if (big_size > object_size)
8119 outs() << " (past end of file)\n";
8120 else
8121 outs() << "\n";
8122 outs() << " locreloff " << dyst.locreloff;
8123 if (dyst.locreloff > object_size)
8124 outs() << " (past end of file)\n";
8125 else
8126 outs() << "\n";
8127 outs() << " nlocrel " << dyst.nlocrel;
8128 big_size = dyst.nlocrel;
8129 big_size *= sizeof(struct MachO::relocation_info);
8130 big_size += dyst.locreloff;
8131 if (big_size > object_size)
8132 outs() << " (past end of file)\n";
8133 else
8134 outs() << "\n";
8135}
8136
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008137static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8138 uint32_t object_size) {
8139 if (dc.cmd == MachO::LC_DYLD_INFO)
8140 outs() << " cmd LC_DYLD_INFO\n";
8141 else
8142 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8143 outs() << " cmdsize " << dc.cmdsize;
8144 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8145 outs() << " Incorrect size\n";
8146 else
8147 outs() << "\n";
8148 outs() << " rebase_off " << dc.rebase_off;
8149 if (dc.rebase_off > object_size)
8150 outs() << " (past end of file)\n";
8151 else
8152 outs() << "\n";
8153 outs() << " rebase_size " << dc.rebase_size;
8154 uint64_t big_size;
8155 big_size = dc.rebase_off;
8156 big_size += dc.rebase_size;
8157 if (big_size > object_size)
8158 outs() << " (past end of file)\n";
8159 else
8160 outs() << "\n";
8161 outs() << " bind_off " << dc.bind_off;
8162 if (dc.bind_off > object_size)
8163 outs() << " (past end of file)\n";
8164 else
8165 outs() << "\n";
8166 outs() << " bind_size " << dc.bind_size;
8167 big_size = dc.bind_off;
8168 big_size += dc.bind_size;
8169 if (big_size > object_size)
8170 outs() << " (past end of file)\n";
8171 else
8172 outs() << "\n";
8173 outs() << " weak_bind_off " << dc.weak_bind_off;
8174 if (dc.weak_bind_off > object_size)
8175 outs() << " (past end of file)\n";
8176 else
8177 outs() << "\n";
8178 outs() << " weak_bind_size " << dc.weak_bind_size;
8179 big_size = dc.weak_bind_off;
8180 big_size += dc.weak_bind_size;
8181 if (big_size > object_size)
8182 outs() << " (past end of file)\n";
8183 else
8184 outs() << "\n";
8185 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8186 if (dc.lazy_bind_off > object_size)
8187 outs() << " (past end of file)\n";
8188 else
8189 outs() << "\n";
8190 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8191 big_size = dc.lazy_bind_off;
8192 big_size += dc.lazy_bind_size;
8193 if (big_size > object_size)
8194 outs() << " (past end of file)\n";
8195 else
8196 outs() << "\n";
8197 outs() << " export_off " << dc.export_off;
8198 if (dc.export_off > object_size)
8199 outs() << " (past end of file)\n";
8200 else
8201 outs() << "\n";
8202 outs() << " export_size " << dc.export_size;
8203 big_size = dc.export_off;
8204 big_size += dc.export_size;
8205 if (big_size > object_size)
8206 outs() << " (past end of file)\n";
8207 else
8208 outs() << "\n";
8209}
8210
8211static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8212 const char *Ptr) {
8213 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8214 outs() << " cmd LC_ID_DYLINKER\n";
8215 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8216 outs() << " cmd LC_LOAD_DYLINKER\n";
8217 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8218 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8219 else
8220 outs() << " cmd ?(" << dyld.cmd << ")\n";
8221 outs() << " cmdsize " << dyld.cmdsize;
8222 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8223 outs() << " Incorrect size\n";
8224 else
8225 outs() << "\n";
8226 if (dyld.name >= dyld.cmdsize)
8227 outs() << " name ?(bad offset " << dyld.name << ")\n";
8228 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008229 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008230 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8231 }
8232}
8233
8234static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8235 outs() << " cmd LC_UUID\n";
8236 outs() << " cmdsize " << uuid.cmdsize;
8237 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8238 outs() << " Incorrect size\n";
8239 else
8240 outs() << "\n";
8241 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008242 for (int i = 0; i < 16; ++i) {
8243 outs() << format("%02" PRIX32, uuid.uuid[i]);
8244 if (i == 3 || i == 5 || i == 7 || i == 9)
8245 outs() << "-";
8246 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008247 outs() << "\n";
8248}
8249
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008250static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008251 outs() << " cmd LC_RPATH\n";
8252 outs() << " cmdsize " << rpath.cmdsize;
8253 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8254 outs() << " Incorrect size\n";
8255 else
8256 outs() << "\n";
8257 if (rpath.path >= rpath.cmdsize)
8258 outs() << " path ?(bad offset " << rpath.path << ")\n";
8259 else {
8260 const char *P = (const char *)(Ptr) + rpath.path;
8261 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8262 }
8263}
8264
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008265static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008266 StringRef LoadCmdName;
8267 switch (vd.cmd) {
8268 case MachO::LC_VERSION_MIN_MACOSX:
8269 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8270 break;
8271 case MachO::LC_VERSION_MIN_IPHONEOS:
8272 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8273 break;
8274 case MachO::LC_VERSION_MIN_TVOS:
8275 LoadCmdName = "LC_VERSION_MIN_TVOS";
8276 break;
8277 case MachO::LC_VERSION_MIN_WATCHOS:
8278 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8279 break;
8280 default:
8281 llvm_unreachable("Unknown version min load command");
8282 }
8283
8284 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008285 outs() << " cmdsize " << vd.cmdsize;
8286 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8287 outs() << " Incorrect size\n";
8288 else
8289 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008290 outs() << " version "
8291 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8292 << MachOObjectFile::getVersionMinMinor(vd, false);
8293 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8294 if (Update != 0)
8295 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008296 outs() << "\n";
8297 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008298 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008299 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008300 outs() << " sdk "
8301 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8302 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008303 }
Davide Italiano56baef32015-08-26 12:26:11 +00008304 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8305 if (Update != 0)
8306 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008307 outs() << "\n";
8308}
8309
Kevin Enderbya4579c42017-01-19 17:36:31 +00008310static void PrintNoteLoadCommand(MachO::note_command Nt) {
8311 outs() << " cmd LC_NOTE\n";
8312 outs() << " cmdsize " << Nt.cmdsize;
8313 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8314 outs() << " Incorrect size\n";
8315 else
8316 outs() << "\n";
8317 const char *d = Nt.data_owner;
8318 outs() << "data_owner " << format("%.16s\n", d);
8319 outs() << " offset " << Nt.offset << "\n";
8320 outs() << " size " << Nt.size << "\n";
8321}
8322
Steven Wu5b54a422017-01-23 20:07:55 +00008323static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8324 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8325 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8326 << "\n";
8327}
8328
8329static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8330 MachO::build_version_command bd) {
8331 outs() << " cmd LC_BUILD_VERSION\n";
8332 outs() << " cmdsize " << bd.cmdsize;
8333 if (bd.cmdsize !=
8334 sizeof(struct MachO::build_version_command) +
8335 bd.ntools * sizeof(struct MachO::build_tool_version))
8336 outs() << " Incorrect size\n";
8337 else
8338 outs() << "\n";
8339 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8340 << "\n";
8341 if (bd.sdk)
8342 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8343 << "\n";
8344 else
8345 outs() << " sdk n/a\n";
8346 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8347 << "\n";
8348 outs() << " ntools " << bd.ntools << "\n";
8349 for (unsigned i = 0; i < bd.ntools; ++i) {
8350 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8351 PrintBuildToolVersion(bv);
8352 }
8353}
8354
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008355static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8356 outs() << " cmd LC_SOURCE_VERSION\n";
8357 outs() << " cmdsize " << sd.cmdsize;
8358 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8359 outs() << " Incorrect size\n";
8360 else
8361 outs() << "\n";
8362 uint64_t a = (sd.version >> 40) & 0xffffff;
8363 uint64_t b = (sd.version >> 30) & 0x3ff;
8364 uint64_t c = (sd.version >> 20) & 0x3ff;
8365 uint64_t d = (sd.version >> 10) & 0x3ff;
8366 uint64_t e = sd.version & 0x3ff;
8367 outs() << " version " << a << "." << b;
8368 if (e != 0)
8369 outs() << "." << c << "." << d << "." << e;
8370 else if (d != 0)
8371 outs() << "." << c << "." << d;
8372 else if (c != 0)
8373 outs() << "." << c;
8374 outs() << "\n";
8375}
8376
8377static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8378 outs() << " cmd LC_MAIN\n";
8379 outs() << " cmdsize " << ep.cmdsize;
8380 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8381 outs() << " Incorrect size\n";
8382 else
8383 outs() << "\n";
8384 outs() << " entryoff " << ep.entryoff << "\n";
8385 outs() << " stacksize " << ep.stacksize << "\n";
8386}
8387
Kevin Enderby0804f4672014-12-16 23:25:52 +00008388static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8389 uint32_t object_size) {
8390 outs() << " cmd LC_ENCRYPTION_INFO\n";
8391 outs() << " cmdsize " << ec.cmdsize;
8392 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8393 outs() << " Incorrect size\n";
8394 else
8395 outs() << "\n";
8396 outs() << " cryptoff " << ec.cryptoff;
8397 if (ec.cryptoff > object_size)
8398 outs() << " (past end of file)\n";
8399 else
8400 outs() << "\n";
8401 outs() << " cryptsize " << ec.cryptsize;
8402 if (ec.cryptsize > object_size)
8403 outs() << " (past end of file)\n";
8404 else
8405 outs() << "\n";
8406 outs() << " cryptid " << ec.cryptid << "\n";
8407}
8408
Kevin Enderby57538292014-12-17 01:01:30 +00008409static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008410 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008411 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8412 outs() << " cmdsize " << ec.cmdsize;
8413 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8414 outs() << " Incorrect size\n";
8415 else
8416 outs() << "\n";
8417 outs() << " cryptoff " << ec.cryptoff;
8418 if (ec.cryptoff > object_size)
8419 outs() << " (past end of file)\n";
8420 else
8421 outs() << "\n";
8422 outs() << " cryptsize " << ec.cryptsize;
8423 if (ec.cryptsize > object_size)
8424 outs() << " (past end of file)\n";
8425 else
8426 outs() << "\n";
8427 outs() << " cryptid " << ec.cryptid << "\n";
8428 outs() << " pad " << ec.pad << "\n";
8429}
8430
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008431static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8432 const char *Ptr) {
8433 outs() << " cmd LC_LINKER_OPTION\n";
8434 outs() << " cmdsize " << lo.cmdsize;
8435 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8436 outs() << " Incorrect size\n";
8437 else
8438 outs() << "\n";
8439 outs() << " count " << lo.count << "\n";
8440 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8441 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8442 uint32_t i = 0;
8443 while (left > 0) {
8444 while (*string == '\0' && left > 0) {
8445 string++;
8446 left--;
8447 }
8448 if (left > 0) {
8449 i++;
8450 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008451 uint32_t NullPos = StringRef(string, left).find('\0');
8452 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008453 string += len;
8454 left -= len;
8455 }
8456 }
8457 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008458 outs() << " count " << lo.count << " does not match number of strings "
8459 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008460}
8461
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008462static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8463 const char *Ptr) {
8464 outs() << " cmd LC_SUB_FRAMEWORK\n";
8465 outs() << " cmdsize " << sub.cmdsize;
8466 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8467 outs() << " Incorrect size\n";
8468 else
8469 outs() << "\n";
8470 if (sub.umbrella < sub.cmdsize) {
8471 const char *P = Ptr + sub.umbrella;
8472 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8473 } else {
8474 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8475 }
8476}
8477
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008478static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8479 const char *Ptr) {
8480 outs() << " cmd LC_SUB_UMBRELLA\n";
8481 outs() << " cmdsize " << sub.cmdsize;
8482 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8483 outs() << " Incorrect size\n";
8484 else
8485 outs() << "\n";
8486 if (sub.sub_umbrella < sub.cmdsize) {
8487 const char *P = Ptr + sub.sub_umbrella;
8488 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8489 } else {
8490 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8491 }
8492}
8493
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008494static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008495 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008496 outs() << " cmd LC_SUB_LIBRARY\n";
8497 outs() << " cmdsize " << sub.cmdsize;
8498 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8499 outs() << " Incorrect size\n";
8500 else
8501 outs() << "\n";
8502 if (sub.sub_library < sub.cmdsize) {
8503 const char *P = Ptr + sub.sub_library;
8504 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8505 } else {
8506 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8507 }
8508}
8509
Kevin Enderby186eac32014-12-19 21:06:24 +00008510static void PrintSubClientCommand(MachO::sub_client_command sub,
8511 const char *Ptr) {
8512 outs() << " cmd LC_SUB_CLIENT\n";
8513 outs() << " cmdsize " << sub.cmdsize;
8514 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8515 outs() << " Incorrect size\n";
8516 else
8517 outs() << "\n";
8518 if (sub.client < sub.cmdsize) {
8519 const char *P = Ptr + sub.client;
8520 outs() << " client " << P << " (offset " << sub.client << ")\n";
8521 } else {
8522 outs() << " client ?(bad offset " << sub.client << ")\n";
8523 }
8524}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008525
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008526static void PrintRoutinesCommand(MachO::routines_command r) {
8527 outs() << " cmd LC_ROUTINES\n";
8528 outs() << " cmdsize " << r.cmdsize;
8529 if (r.cmdsize != sizeof(struct MachO::routines_command))
8530 outs() << " Incorrect size\n";
8531 else
8532 outs() << "\n";
8533 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8534 outs() << " init_module " << r.init_module << "\n";
8535 outs() << " reserved1 " << r.reserved1 << "\n";
8536 outs() << " reserved2 " << r.reserved2 << "\n";
8537 outs() << " reserved3 " << r.reserved3 << "\n";
8538 outs() << " reserved4 " << r.reserved4 << "\n";
8539 outs() << " reserved5 " << r.reserved5 << "\n";
8540 outs() << " reserved6 " << r.reserved6 << "\n";
8541}
8542
8543static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8544 outs() << " cmd LC_ROUTINES_64\n";
8545 outs() << " cmdsize " << r.cmdsize;
8546 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8547 outs() << " Incorrect size\n";
8548 else
8549 outs() << "\n";
8550 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8551 outs() << " init_module " << r.init_module << "\n";
8552 outs() << " reserved1 " << r.reserved1 << "\n";
8553 outs() << " reserved2 " << r.reserved2 << "\n";
8554 outs() << " reserved3 " << r.reserved3 << "\n";
8555 outs() << " reserved4 " << r.reserved4 << "\n";
8556 outs() << " reserved5 " << r.reserved5 << "\n";
8557 outs() << " reserved6 " << r.reserved6 << "\n";
8558}
8559
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008560static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8561 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8562 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8563 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8564 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8565 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8566 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8567 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8568 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8569 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8570 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8571 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8572 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8573 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8574 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8575 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8576 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8577}
8578
Kevin Enderby48ef5342014-12-23 22:56:39 +00008579static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8580 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8581 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8582 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8583 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8584 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8585 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8586 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8587 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8588 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8589 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8590 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8591 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8592 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8593 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8594 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8595 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8596 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8597 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8598 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8599 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8600 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8601}
8602
Kevin Enderby227df342014-12-23 23:43:59 +00008603static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008604 uint32_t f;
8605 outs() << "\t mmst_reg ";
8606 for (f = 0; f < 10; f++)
8607 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8608 outs() << "\n";
8609 outs() << "\t mmst_rsrv ";
8610 for (f = 0; f < 6; f++)
8611 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8612 outs() << "\n";
8613}
8614
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008615static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008616 uint32_t f;
8617 outs() << "\t xmm_reg ";
8618 for (f = 0; f < 16; f++)
8619 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8620 outs() << "\n";
8621}
8622
8623static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8624 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8625 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8626 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8627 outs() << " denorm " << fpu.fpu_fcw.denorm;
8628 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8629 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8630 outs() << " undfl " << fpu.fpu_fcw.undfl;
8631 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8632 outs() << "\t\t pc ";
8633 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8634 outs() << "FP_PREC_24B ";
8635 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8636 outs() << "FP_PREC_53B ";
8637 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8638 outs() << "FP_PREC_64B ";
8639 else
8640 outs() << fpu.fpu_fcw.pc << " ";
8641 outs() << "rc ";
8642 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8643 outs() << "FP_RND_NEAR ";
8644 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8645 outs() << "FP_RND_DOWN ";
8646 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8647 outs() << "FP_RND_UP ";
8648 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008649 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008650 outs() << "\n";
8651 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8652 outs() << " denorm " << fpu.fpu_fsw.denorm;
8653 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8654 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8655 outs() << " undfl " << fpu.fpu_fsw.undfl;
8656 outs() << " precis " << fpu.fpu_fsw.precis;
8657 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8658 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8659 outs() << " c0 " << fpu.fpu_fsw.c0;
8660 outs() << " c1 " << fpu.fpu_fsw.c1;
8661 outs() << " c2 " << fpu.fpu_fsw.c2;
8662 outs() << " tos " << fpu.fpu_fsw.tos;
8663 outs() << " c3 " << fpu.fpu_fsw.c3;
8664 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8665 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8666 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8667 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8668 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8669 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8670 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8671 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8672 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8673 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8674 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8675 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8676 outs() << "\n";
8677 outs() << "\t fpu_stmm0:\n";
8678 Print_mmst_reg(fpu.fpu_stmm0);
8679 outs() << "\t fpu_stmm1:\n";
8680 Print_mmst_reg(fpu.fpu_stmm1);
8681 outs() << "\t fpu_stmm2:\n";
8682 Print_mmst_reg(fpu.fpu_stmm2);
8683 outs() << "\t fpu_stmm3:\n";
8684 Print_mmst_reg(fpu.fpu_stmm3);
8685 outs() << "\t fpu_stmm4:\n";
8686 Print_mmst_reg(fpu.fpu_stmm4);
8687 outs() << "\t fpu_stmm5:\n";
8688 Print_mmst_reg(fpu.fpu_stmm5);
8689 outs() << "\t fpu_stmm6:\n";
8690 Print_mmst_reg(fpu.fpu_stmm6);
8691 outs() << "\t fpu_stmm7:\n";
8692 Print_mmst_reg(fpu.fpu_stmm7);
8693 outs() << "\t fpu_xmm0:\n";
8694 Print_xmm_reg(fpu.fpu_xmm0);
8695 outs() << "\t fpu_xmm1:\n";
8696 Print_xmm_reg(fpu.fpu_xmm1);
8697 outs() << "\t fpu_xmm2:\n";
8698 Print_xmm_reg(fpu.fpu_xmm2);
8699 outs() << "\t fpu_xmm3:\n";
8700 Print_xmm_reg(fpu.fpu_xmm3);
8701 outs() << "\t fpu_xmm4:\n";
8702 Print_xmm_reg(fpu.fpu_xmm4);
8703 outs() << "\t fpu_xmm5:\n";
8704 Print_xmm_reg(fpu.fpu_xmm5);
8705 outs() << "\t fpu_xmm6:\n";
8706 Print_xmm_reg(fpu.fpu_xmm6);
8707 outs() << "\t fpu_xmm7:\n";
8708 Print_xmm_reg(fpu.fpu_xmm7);
8709 outs() << "\t fpu_xmm8:\n";
8710 Print_xmm_reg(fpu.fpu_xmm8);
8711 outs() << "\t fpu_xmm9:\n";
8712 Print_xmm_reg(fpu.fpu_xmm9);
8713 outs() << "\t fpu_xmm10:\n";
8714 Print_xmm_reg(fpu.fpu_xmm10);
8715 outs() << "\t fpu_xmm11:\n";
8716 Print_xmm_reg(fpu.fpu_xmm11);
8717 outs() << "\t fpu_xmm12:\n";
8718 Print_xmm_reg(fpu.fpu_xmm12);
8719 outs() << "\t fpu_xmm13:\n";
8720 Print_xmm_reg(fpu.fpu_xmm13);
8721 outs() << "\t fpu_xmm14:\n";
8722 Print_xmm_reg(fpu.fpu_xmm14);
8723 outs() << "\t fpu_xmm15:\n";
8724 Print_xmm_reg(fpu.fpu_xmm15);
8725 outs() << "\t fpu_rsrv4:\n";
8726 for (uint32_t f = 0; f < 6; f++) {
8727 outs() << "\t ";
8728 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008729 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008730 outs() << "\n";
8731 }
8732 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8733 outs() << "\n";
8734}
8735
8736static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8737 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8738 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8739 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8740}
8741
Kevin Enderby41c9c002016-10-21 18:22:35 +00008742static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
8743 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
8744 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
8745 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
8746 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
8747 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
8748 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
8749 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
8750 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
8751 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
8752 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
8753 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
8754 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
8755 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
8756 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
8757 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
8758 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
8759 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
8760}
8761
Kevin Enderby7747cb52016-11-03 20:51:28 +00008762static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
8763 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
8764 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
8765 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
8766 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
8767 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
8768 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
8769 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
8770 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
8771 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
8772 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
8773 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
8774 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
8775 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
8776 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
8777 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
8778 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
8779 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
8780 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
8781 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
8782 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
8783 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
8784 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
8785 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
8786 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
8787 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
8788 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
8789 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
8790 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
8791 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
8792 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
8793 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
8794 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
8795 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
8796 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
8797}
8798
Kevin Enderby48ef5342014-12-23 22:56:39 +00008799static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8800 bool isLittleEndian, uint32_t cputype) {
8801 if (t.cmd == MachO::LC_THREAD)
8802 outs() << " cmd LC_THREAD\n";
8803 else if (t.cmd == MachO::LC_UNIXTHREAD)
8804 outs() << " cmd LC_UNIXTHREAD\n";
8805 else
8806 outs() << " cmd " << t.cmd << " (unknown)\n";
8807 outs() << " cmdsize " << t.cmdsize;
8808 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8809 outs() << " Incorrect size\n";
8810 else
8811 outs() << "\n";
8812
8813 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8814 const char *end = Ptr + t.cmdsize;
8815 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008816 if (cputype == MachO::CPU_TYPE_I386) {
8817 while (begin < end) {
8818 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8819 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8820 begin += sizeof(uint32_t);
8821 } else {
8822 flavor = 0;
8823 begin = end;
8824 }
8825 if (isLittleEndian != sys::IsLittleEndianHost)
8826 sys::swapByteOrder(flavor);
8827 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8828 memcpy((char *)&count, begin, sizeof(uint32_t));
8829 begin += sizeof(uint32_t);
8830 } else {
8831 count = 0;
8832 begin = end;
8833 }
8834 if (isLittleEndian != sys::IsLittleEndianHost)
8835 sys::swapByteOrder(count);
8836 if (flavor == MachO::x86_THREAD_STATE32) {
8837 outs() << " flavor i386_THREAD_STATE\n";
8838 if (count == MachO::x86_THREAD_STATE32_COUNT)
8839 outs() << " count i386_THREAD_STATE_COUNT\n";
8840 else
8841 outs() << " count " << count
8842 << " (not x86_THREAD_STATE32_COUNT)\n";
8843 MachO::x86_thread_state32_t cpu32;
8844 left = end - begin;
8845 if (left >= sizeof(MachO::x86_thread_state32_t)) {
8846 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
8847 begin += sizeof(MachO::x86_thread_state32_t);
8848 } else {
8849 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
8850 memcpy(&cpu32, begin, left);
8851 begin += left;
8852 }
8853 if (isLittleEndian != sys::IsLittleEndianHost)
8854 swapStruct(cpu32);
8855 Print_x86_thread_state32_t(cpu32);
8856 } else if (flavor == MachO::x86_THREAD_STATE) {
8857 outs() << " flavor x86_THREAD_STATE\n";
8858 if (count == MachO::x86_THREAD_STATE_COUNT)
8859 outs() << " count x86_THREAD_STATE_COUNT\n";
8860 else
8861 outs() << " count " << count
8862 << " (not x86_THREAD_STATE_COUNT)\n";
8863 struct MachO::x86_thread_state_t ts;
8864 left = end - begin;
8865 if (left >= sizeof(MachO::x86_thread_state_t)) {
8866 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8867 begin += sizeof(MachO::x86_thread_state_t);
8868 } else {
8869 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8870 memcpy(&ts, begin, left);
8871 begin += left;
8872 }
8873 if (isLittleEndian != sys::IsLittleEndianHost)
8874 swapStruct(ts);
8875 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
8876 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
8877 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
8878 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
8879 else
8880 outs() << "tsh.count " << ts.tsh.count
8881 << " (not x86_THREAD_STATE32_COUNT\n";
8882 Print_x86_thread_state32_t(ts.uts.ts32);
8883 } else {
8884 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8885 << ts.tsh.count << "\n";
8886 }
8887 } else {
8888 outs() << " flavor " << flavor << " (unknown)\n";
8889 outs() << " count " << count << "\n";
8890 outs() << " state (unknown)\n";
8891 begin += count * sizeof(uint32_t);
8892 }
8893 }
8894 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008895 while (begin < end) {
8896 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8897 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8898 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008899 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008900 flavor = 0;
8901 begin = end;
8902 }
8903 if (isLittleEndian != sys::IsLittleEndianHost)
8904 sys::swapByteOrder(flavor);
8905 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8906 memcpy((char *)&count, begin, sizeof(uint32_t));
8907 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008908 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008909 count = 0;
8910 begin = end;
8911 }
8912 if (isLittleEndian != sys::IsLittleEndianHost)
8913 sys::swapByteOrder(count);
8914 if (flavor == MachO::x86_THREAD_STATE64) {
8915 outs() << " flavor x86_THREAD_STATE64\n";
8916 if (count == MachO::x86_THREAD_STATE64_COUNT)
8917 outs() << " count x86_THREAD_STATE64_COUNT\n";
8918 else
8919 outs() << " count " << count
8920 << " (not x86_THREAD_STATE64_COUNT)\n";
8921 MachO::x86_thread_state64_t cpu64;
8922 left = end - begin;
8923 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8924 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8925 begin += sizeof(MachO::x86_thread_state64_t);
8926 } else {
8927 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8928 memcpy(&cpu64, begin, left);
8929 begin += left;
8930 }
8931 if (isLittleEndian != sys::IsLittleEndianHost)
8932 swapStruct(cpu64);
8933 Print_x86_thread_state64_t(cpu64);
8934 } else if (flavor == MachO::x86_THREAD_STATE) {
8935 outs() << " flavor x86_THREAD_STATE\n";
8936 if (count == MachO::x86_THREAD_STATE_COUNT)
8937 outs() << " count x86_THREAD_STATE_COUNT\n";
8938 else
8939 outs() << " count " << count
8940 << " (not x86_THREAD_STATE_COUNT)\n";
8941 struct MachO::x86_thread_state_t ts;
8942 left = end - begin;
8943 if (left >= sizeof(MachO::x86_thread_state_t)) {
8944 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8945 begin += sizeof(MachO::x86_thread_state_t);
8946 } else {
8947 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8948 memcpy(&ts, begin, left);
8949 begin += left;
8950 }
8951 if (isLittleEndian != sys::IsLittleEndianHost)
8952 swapStruct(ts);
8953 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8954 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8955 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8956 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8957 else
8958 outs() << "tsh.count " << ts.tsh.count
8959 << " (not x86_THREAD_STATE64_COUNT\n";
8960 Print_x86_thread_state64_t(ts.uts.ts64);
8961 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008962 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8963 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008964 }
8965 } else if (flavor == MachO::x86_FLOAT_STATE) {
8966 outs() << " flavor x86_FLOAT_STATE\n";
8967 if (count == MachO::x86_FLOAT_STATE_COUNT)
8968 outs() << " count x86_FLOAT_STATE_COUNT\n";
8969 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008970 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008971 struct MachO::x86_float_state_t fs;
8972 left = end - begin;
8973 if (left >= sizeof(MachO::x86_float_state_t)) {
8974 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8975 begin += sizeof(MachO::x86_float_state_t);
8976 } else {
8977 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8978 memcpy(&fs, begin, left);
8979 begin += left;
8980 }
8981 if (isLittleEndian != sys::IsLittleEndianHost)
8982 swapStruct(fs);
8983 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8984 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008985 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008986 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8987 else
8988 outs() << "fsh.count " << fs.fsh.count
8989 << " (not x86_FLOAT_STATE64_COUNT\n";
8990 Print_x86_float_state_t(fs.ufs.fs64);
8991 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008992 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8993 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008994 }
8995 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8996 outs() << " flavor x86_EXCEPTION_STATE\n";
8997 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8998 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8999 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009000 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009001 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9002 struct MachO::x86_exception_state_t es;
9003 left = end - begin;
9004 if (left >= sizeof(MachO::x86_exception_state_t)) {
9005 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9006 begin += sizeof(MachO::x86_exception_state_t);
9007 } else {
9008 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9009 memcpy(&es, begin, left);
9010 begin += left;
9011 }
9012 if (isLittleEndian != sys::IsLittleEndianHost)
9013 swapStruct(es);
9014 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9015 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009016 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009017 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9018 else
9019 outs() << "\t esh.count " << es.esh.count
9020 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9021 Print_x86_exception_state_t(es.ues.es64);
9022 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009023 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9024 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009025 }
9026 } else {
9027 outs() << " flavor " << flavor << " (unknown)\n";
9028 outs() << " count " << count << "\n";
9029 outs() << " state (unknown)\n";
9030 begin += count * sizeof(uint32_t);
9031 }
9032 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009033 } else if (cputype == MachO::CPU_TYPE_ARM) {
9034 while (begin < end) {
9035 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9036 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9037 begin += sizeof(uint32_t);
9038 } else {
9039 flavor = 0;
9040 begin = end;
9041 }
9042 if (isLittleEndian != sys::IsLittleEndianHost)
9043 sys::swapByteOrder(flavor);
9044 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9045 memcpy((char *)&count, begin, sizeof(uint32_t));
9046 begin += sizeof(uint32_t);
9047 } else {
9048 count = 0;
9049 begin = end;
9050 }
9051 if (isLittleEndian != sys::IsLittleEndianHost)
9052 sys::swapByteOrder(count);
9053 if (flavor == MachO::ARM_THREAD_STATE) {
9054 outs() << " flavor ARM_THREAD_STATE\n";
9055 if (count == MachO::ARM_THREAD_STATE_COUNT)
9056 outs() << " count ARM_THREAD_STATE_COUNT\n";
9057 else
9058 outs() << " count " << count
9059 << " (not ARM_THREAD_STATE_COUNT)\n";
9060 MachO::arm_thread_state32_t cpu32;
9061 left = end - begin;
9062 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9063 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9064 begin += sizeof(MachO::arm_thread_state32_t);
9065 } else {
9066 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9067 memcpy(&cpu32, begin, left);
9068 begin += left;
9069 }
9070 if (isLittleEndian != sys::IsLittleEndianHost)
9071 swapStruct(cpu32);
9072 Print_arm_thread_state32_t(cpu32);
9073 } else {
9074 outs() << " flavor " << flavor << " (unknown)\n";
9075 outs() << " count " << count << "\n";
9076 outs() << " state (unknown)\n";
9077 begin += count * sizeof(uint32_t);
9078 }
9079 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009080 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9081 while (begin < end) {
9082 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9083 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9084 begin += sizeof(uint32_t);
9085 } else {
9086 flavor = 0;
9087 begin = end;
9088 }
9089 if (isLittleEndian != sys::IsLittleEndianHost)
9090 sys::swapByteOrder(flavor);
9091 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9092 memcpy((char *)&count, begin, sizeof(uint32_t));
9093 begin += sizeof(uint32_t);
9094 } else {
9095 count = 0;
9096 begin = end;
9097 }
9098 if (isLittleEndian != sys::IsLittleEndianHost)
9099 sys::swapByteOrder(count);
9100 if (flavor == MachO::ARM_THREAD_STATE64) {
9101 outs() << " flavor ARM_THREAD_STATE64\n";
9102 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9103 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9104 else
9105 outs() << " count " << count
9106 << " (not ARM_THREAD_STATE64_COUNT)\n";
9107 MachO::arm_thread_state64_t cpu64;
9108 left = end - begin;
9109 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9110 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9111 begin += sizeof(MachO::arm_thread_state64_t);
9112 } else {
9113 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9114 memcpy(&cpu64, begin, left);
9115 begin += left;
9116 }
9117 if (isLittleEndian != sys::IsLittleEndianHost)
9118 swapStruct(cpu64);
9119 Print_arm_thread_state64_t(cpu64);
9120 } else {
9121 outs() << " flavor " << flavor << " (unknown)\n";
9122 outs() << " count " << count << "\n";
9123 outs() << " state (unknown)\n";
9124 begin += count * sizeof(uint32_t);
9125 }
9126 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009127 } else {
9128 while (begin < end) {
9129 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9130 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9131 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009132 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009133 flavor = 0;
9134 begin = end;
9135 }
9136 if (isLittleEndian != sys::IsLittleEndianHost)
9137 sys::swapByteOrder(flavor);
9138 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9139 memcpy((char *)&count, begin, sizeof(uint32_t));
9140 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009141 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009142 count = 0;
9143 begin = end;
9144 }
9145 if (isLittleEndian != sys::IsLittleEndianHost)
9146 sys::swapByteOrder(count);
9147 outs() << " flavor " << flavor << "\n";
9148 outs() << " count " << count << "\n";
9149 outs() << " state (Unknown cputype/cpusubtype)\n";
9150 begin += count * sizeof(uint32_t);
9151 }
9152 }
9153}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009154
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009155static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9156 if (dl.cmd == MachO::LC_ID_DYLIB)
9157 outs() << " cmd LC_ID_DYLIB\n";
9158 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9159 outs() << " cmd LC_LOAD_DYLIB\n";
9160 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9161 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9162 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9163 outs() << " cmd LC_REEXPORT_DYLIB\n";
9164 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9165 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9166 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9167 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9168 else
9169 outs() << " cmd " << dl.cmd << " (unknown)\n";
9170 outs() << " cmdsize " << dl.cmdsize;
9171 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9172 outs() << " Incorrect size\n";
9173 else
9174 outs() << "\n";
9175 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009176 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009177 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9178 } else {
9179 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9180 }
9181 outs() << " time stamp " << dl.dylib.timestamp << " ";
9182 time_t t = dl.dylib.timestamp;
9183 outs() << ctime(&t);
9184 outs() << " current version ";
9185 if (dl.dylib.current_version == 0xffffffff)
9186 outs() << "n/a\n";
9187 else
9188 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9189 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9190 << (dl.dylib.current_version & 0xff) << "\n";
9191 outs() << "compatibility version ";
9192 if (dl.dylib.compatibility_version == 0xffffffff)
9193 outs() << "n/a\n";
9194 else
9195 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9196 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9197 << (dl.dylib.compatibility_version & 0xff) << "\n";
9198}
9199
9200static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9201 uint32_t object_size) {
9202 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009203 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009204 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9205 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9206 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9207 outs() << " cmd LC_FUNCTION_STARTS\n";
9208 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9209 outs() << " cmd LC_DATA_IN_CODE\n";
9210 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9211 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9212 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9213 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9214 else
9215 outs() << " cmd " << ld.cmd << " (?)\n";
9216 outs() << " cmdsize " << ld.cmdsize;
9217 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9218 outs() << " Incorrect size\n";
9219 else
9220 outs() << "\n";
9221 outs() << " dataoff " << ld.dataoff;
9222 if (ld.dataoff > object_size)
9223 outs() << " (past end of file)\n";
9224 else
9225 outs() << "\n";
9226 outs() << " datasize " << ld.datasize;
9227 uint64_t big_size = ld.dataoff;
9228 big_size += ld.datasize;
9229 if (big_size > object_size)
9230 outs() << " (past end of file)\n";
9231 else
9232 outs() << "\n";
9233}
9234
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009235static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9236 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009237 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009238 unsigned Index = 0;
9239 for (const auto &Command : Obj->load_commands()) {
9240 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009241 if (Command.C.cmd == MachO::LC_SEGMENT) {
9242 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9243 const char *sg_segname = SLC.segname;
9244 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9245 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9246 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9247 verbose);
9248 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009249 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009250 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9251 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9252 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9253 }
9254 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9255 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9256 const char *sg_segname = SLC_64.segname;
9257 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9258 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9259 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9260 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9261 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9262 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9263 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9264 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9265 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9266 sg_segname, filetype, Buf.size(), verbose);
9267 }
9268 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9269 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009270 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009271 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9272 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9273 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009274 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9275 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009276 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9277 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9278 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9279 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9280 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9281 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9282 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9283 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9284 PrintDyldLoadCommand(Dyld, Command.Ptr);
9285 } else if (Command.C.cmd == MachO::LC_UUID) {
9286 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9287 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009288 } else if (Command.C.cmd == MachO::LC_RPATH) {
9289 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9290 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009291 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009292 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9293 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9294 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009295 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9296 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009297 } else if (Command.C.cmd == MachO::LC_NOTE) {
9298 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9299 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009300 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9301 MachO::build_version_command Bv =
9302 Obj->getBuildVersionLoadCommand(Command);
9303 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009304 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9305 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9306 PrintSourceVersionCommand(Sd);
9307 } else if (Command.C.cmd == MachO::LC_MAIN) {
9308 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9309 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009310 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009311 MachO::encryption_info_command Ei =
9312 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009313 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009314 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009315 MachO::encryption_info_command_64 Ei =
9316 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009317 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009318 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009319 MachO::linker_option_command Lo =
9320 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009321 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009322 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9323 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9324 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009325 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9326 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9327 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009328 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9329 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9330 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009331 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9332 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9333 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009334 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9335 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9336 PrintRoutinesCommand(Rc);
9337 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9338 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9339 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009340 } else if (Command.C.cmd == MachO::LC_THREAD ||
9341 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9342 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9343 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009344 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9345 Command.C.cmd == MachO::LC_ID_DYLIB ||
9346 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9347 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9348 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9349 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009350 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9351 PrintDylibCommand(Dl, Command.Ptr);
9352 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9353 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9354 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9355 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9356 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9357 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9358 MachO::linkedit_data_command Ld =
9359 Obj->getLinkeditDataLoadCommand(Command);
9360 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009361 } else {
9362 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9363 << ")\n";
9364 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9365 // TODO: get and print the raw bytes of the load command.
9366 }
9367 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009368 }
9369}
9370
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009371static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009372 if (Obj->is64Bit()) {
9373 MachO::mach_header_64 H_64;
9374 H_64 = Obj->getHeader64();
9375 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9376 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9377 } else {
9378 MachO::mach_header H;
9379 H = Obj->getHeader();
9380 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9381 H.sizeofcmds, H.flags, verbose);
9382 }
9383}
9384
9385void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9386 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009387 PrintMachHeader(file, !NonVerbose);
9388}
9389
9390void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9391 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009392 uint32_t filetype = 0;
9393 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009394 if (file->is64Bit()) {
9395 MachO::mach_header_64 H_64;
9396 H_64 = file->getHeader64();
9397 filetype = H_64.filetype;
9398 cputype = H_64.cputype;
9399 } else {
9400 MachO::mach_header H;
9401 H = file->getHeader();
9402 filetype = H.filetype;
9403 cputype = H.cputype;
9404 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009405 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009406}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009407
9408//===----------------------------------------------------------------------===//
9409// export trie dumping
9410//===----------------------------------------------------------------------===//
9411
9412void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009413 uint64_t BaseSegmentAddress = 0;
9414 for (const auto &Command : Obj->load_commands()) {
9415 if (Command.C.cmd == MachO::LC_SEGMENT) {
9416 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9417 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9418 BaseSegmentAddress = Seg.vmaddr;
9419 break;
9420 }
9421 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9422 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9423 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9424 BaseSegmentAddress = Seg.vmaddr;
9425 break;
9426 }
9427 }
9428 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009429 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +00009430 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009431 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009432 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9433 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9434 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9435 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9436 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9437 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9438 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9439 if (ReExport)
9440 outs() << "[re-export] ";
9441 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009442 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009443 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009444 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009445 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009446 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009447 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009448 if (WeakDef) {
9449 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009450 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009451 }
9452 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009453 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009454 outs() << ", ";
9455 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009456 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009457 }
9458 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009459 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009460 outs() << ", ";
9461 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009462 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009463 }
9464 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009465 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009466 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009467 outs() << format("resolver=0x%08llX", Entry.other());
9468 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009469 }
9470 outs() << "]";
9471 }
9472 if (ReExport) {
9473 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009474 int Ordinal = Entry.other() - 1;
9475 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9476 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009477 outs() << " (from " << DylibName << ")";
9478 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009479 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009480 }
9481 outs() << "\n";
9482 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009483 if (Err)
9484 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +00009485}
Nick Kledzikac431442014-09-12 21:34:15 +00009486
Nick Kledzikac431442014-09-12 21:34:15 +00009487//===----------------------------------------------------------------------===//
9488// rebase table dumping
9489//===----------------------------------------------------------------------===//
9490
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009491void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009492 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009493 Error Err = Error::success();
9494 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9495 StringRef SegmentName = Entry.segmentName();
9496 StringRef SectionName = Entry.sectionName();
9497 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009498
9499 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009500 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9501 SegmentName.str().c_str(), SectionName.str().c_str(),
9502 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009503 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009504 if (Err)
9505 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009506}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009507
9508static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9509 StringRef DylibName;
9510 switch (Ordinal) {
9511 case MachO::BIND_SPECIAL_DYLIB_SELF:
9512 return "this-image";
9513 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9514 return "main-executable";
9515 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9516 return "flat-namespace";
9517 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009518 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009519 std::error_code EC =
9520 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009521 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009522 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009523 return DylibName;
9524 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009525 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009526 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009527}
9528
9529//===----------------------------------------------------------------------===//
9530// bind table dumping
9531//===----------------------------------------------------------------------===//
9532
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009533void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009534 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009535 outs() << "segment section address type "
9536 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009537 Error Err = Error::success();
9538 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009539 StringRef SegmentName = Entry.segmentName();
9540 StringRef SectionName = Entry.sectionName();
9541 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009542
9543 // Table lines look like:
9544 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009545 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009546 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009547 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009548 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009549 << left_justify(SectionName, 18) << " "
9550 << format_hex(Address, 10, true) << " "
9551 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009552 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009553 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009554 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009555 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009556 if (Err)
9557 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009558}
9559
9560//===----------------------------------------------------------------------===//
9561// lazy bind table dumping
9562//===----------------------------------------------------------------------===//
9563
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009564void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009565 outs() << "segment section address "
9566 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009567 Error Err = Error::success();
9568 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009569 StringRef SegmentName = Entry.segmentName();
9570 StringRef SectionName = Entry.sectionName();
9571 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009572
9573 // Table lines look like:
9574 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009575 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009576 << left_justify(SectionName, 18) << " "
9577 << format_hex(Address, 10, true) << " "
9578 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009579 << Entry.symbolName() << "\n";
9580 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009581 if (Err)
9582 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009583}
9584
Nick Kledzik56ebef42014-09-16 01:41:51 +00009585//===----------------------------------------------------------------------===//
9586// weak bind table dumping
9587//===----------------------------------------------------------------------===//
9588
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009589void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009590 outs() << "segment section address "
9591 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009592 Error Err = Error::success();
9593 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009594 // Strong symbols don't have a location to update.
9595 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009596 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009597 << Entry.symbolName() << "\n";
9598 continue;
9599 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009600 StringRef SegmentName = Entry.segmentName();
9601 StringRef SectionName = Entry.sectionName();
9602 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009603
9604 // Table lines look like:
9605 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009606 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009607 << left_justify(SectionName, 18) << " "
9608 << format_hex(Address, 10, true) << " "
9609 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009610 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9611 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009612 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009613 if (Err)
9614 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009615}
9616
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009617// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9618// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9619// information for that address. If the address is found its binding symbol
9620// name is returned. If not nullptr is returned.
9621static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9622 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009623 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009624 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009625 Error Err = Error::success();
9626 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009627 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009628 StringRef name = Entry.symbolName();
9629 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009630 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009631 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009632 if (Err)
9633 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009634 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009635 auto name = info->bindtable->lookup(ReferenceValue);
9636 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009637}