blob: a260d6ff42c5353d4e72ef0541719462003d24ac [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
Mehdi Aminib550cb12016-04-18 09:17:29 +000014#include "llvm/Object/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000016#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000017#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000018#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000019#include "llvm/ADT/Triple.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000023#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000024#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000025#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000026#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000027#include "llvm/MC/MCInst.h"
28#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCInstrDesc.h"
30#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000031#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000032#include "llvm/MC/MCSubtargetInfo.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000033#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000034#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000037#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000041#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000046#include "llvm/Support/ToolOutputFile.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include <algorithm>
49#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000050#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000051
Kevin Enderby9873e2c2016-05-23 21:34:12 +000052#ifdef HAVE_LIBXAR
53extern "C" {
54#include <xar/xar.h>
55}
56#endif
57
Benjamin Kramer43a772e2011-09-19 17:56:04 +000058using namespace llvm;
59using namespace object;
60
61static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062 UseDbg("g",
63 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<std::string> DSYMFile("dsym",
66 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000070
Kevin 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
Kevin Enderby930fdc72014-11-06 19:00:13 +0000205// This is used to search for a data in code table entry for the PC being
206// disassembled. The j parameter has the PC in j.first. A single data in code
207// table entry can cover many bytes for each of its Kind's. So if the offset,
208// aka the i.first value, of the data in code table entry plus its Length
209// covers the PC being searched for this will return true. If not it will
210// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000211static bool compareDiceTableEntries(const DiceTableEntry &i,
212 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000213 uint16_t Length;
214 i.second.getLength(Length);
215
216 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000217}
218
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000219static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000220 unsigned short Kind) {
221 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000222
223 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000224 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000225 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 if (Length >= 4) {
227 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000228 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000229 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000230 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000231 Size = 4;
232 } else if (Length >= 2) {
233 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000234 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000235 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000236 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 Size = 2;
238 } else {
239 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000240 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000241 Value = bytes[0];
242 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000243 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000244 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000245 if (Kind == MachO::DICE_KIND_DATA)
246 outs() << "\t@ KIND_DATA\n";
247 else
248 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000249 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000250 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000251 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000252 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000253 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000254 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
255 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000256 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000257 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000258 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000259 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000260 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000261 outs() << "\t.short " << format("%5u", Value & 0xffff)
262 << "\t@ KIND_JUMP_TABLE16\n";
263 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000264 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000265 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000266 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
267 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000268 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000269 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000270 outs() << "\t.long " << Value;
271 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
272 outs() << "\t@ KIND_JUMP_TABLE32\n";
273 else
274 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
275 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000276 break;
277 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000278 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000279}
280
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000281static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000282 std::vector<SectionRef> &Sections,
283 std::vector<SymbolRef> &Symbols,
284 SmallVectorImpl<uint64_t> &FoundFns,
285 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000286 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000287 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000288 if (!SymName)
289 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000290 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000291 Symbols.push_back(Symbol);
292 }
Owen Andersond9243c42011-10-17 21:37:35 +0000293
Alexey Samsonov48803e52014-03-13 14:37:36 +0000294 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000295 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000296 Section.getName(SectName);
297 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000298 }
299
Kevin Enderby273ae012013-06-06 17:20:50 +0000300 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000301 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000302 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000303 // We found a function starts segment, parse the addresses for later
304 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000305 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000306 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000307
Charles Davis8bdfafd2013-09-01 04:28:48 +0000308 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000309 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
310 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000311 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000312 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000313 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000314 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000315 }
316 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000317 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000318}
319
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000320static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
321 uint32_t n, uint32_t count,
322 uint32_t stride, uint64_t addr) {
323 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
324 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
325 if (n > nindirectsyms)
326 outs() << " (entries start past the end of the indirect symbol "
327 "table) (reserved1 field greater than the table size)";
328 else if (n + count > nindirectsyms)
329 outs() << " (entries extends past the end of the indirect symbol "
330 "table)";
331 outs() << "\n";
332 uint32_t cputype = O->getHeader().cputype;
333 if (cputype & MachO::CPU_ARCH_ABI64)
334 outs() << "address index";
335 else
336 outs() << "address index";
337 if (verbose)
338 outs() << " name\n";
339 else
340 outs() << "\n";
341 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
342 if (cputype & MachO::CPU_ARCH_ABI64)
343 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
344 else
Tim Northover43978372016-04-26 18:29:16 +0000345 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000346 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
347 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
348 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
349 outs() << "LOCAL\n";
350 continue;
351 }
352 if (indirect_symbol ==
353 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
354 outs() << "LOCAL ABSOLUTE\n";
355 continue;
356 }
357 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
358 outs() << "ABSOLUTE\n";
359 continue;
360 }
361 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000362 if (verbose) {
363 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
364 if (indirect_symbol < Symtab.nsyms) {
365 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
366 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000367 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000368 if (!SymName)
369 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000370 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000371 } else {
372 outs() << "?";
373 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000374 }
375 outs() << "\n";
376 }
377}
378
379static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000380 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000381 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
382 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
383 for (unsigned J = 0; J < Seg.nsects; ++J) {
384 MachO::section_64 Sec = O->getSection64(Load, J);
385 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
386 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
387 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
388 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
389 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
390 section_type == MachO::S_SYMBOL_STUBS) {
391 uint32_t stride;
392 if (section_type == MachO::S_SYMBOL_STUBS)
393 stride = Sec.reserved2;
394 else
395 stride = 8;
396 if (stride == 0) {
397 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
398 << Sec.sectname << ") "
399 << "(size of stubs in reserved2 field is zero)\n";
400 continue;
401 }
402 uint32_t count = Sec.size / stride;
403 outs() << "Indirect symbols for (" << Sec.segname << ","
404 << Sec.sectname << ") " << count << " entries";
405 uint32_t n = Sec.reserved1;
406 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
407 }
408 }
409 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
410 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
411 for (unsigned J = 0; J < Seg.nsects; ++J) {
412 MachO::section Sec = O->getSection(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 = 4;
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 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000438 }
439}
440
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000441static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
442 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
443 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
444 outs() << "Data in code table (" << nentries << " entries)\n";
445 outs() << "offset length kind\n";
446 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
447 ++DI) {
448 uint32_t Offset;
449 DI->getOffset(Offset);
450 outs() << format("0x%08" PRIx32, Offset) << " ";
451 uint16_t Length;
452 DI->getLength(Length);
453 outs() << format("%6u", Length) << " ";
454 uint16_t Kind;
455 DI->getKind(Kind);
456 if (verbose) {
457 switch (Kind) {
458 case MachO::DICE_KIND_DATA:
459 outs() << "DATA";
460 break;
461 case MachO::DICE_KIND_JUMP_TABLE8:
462 outs() << "JUMP_TABLE8";
463 break;
464 case MachO::DICE_KIND_JUMP_TABLE16:
465 outs() << "JUMP_TABLE16";
466 break;
467 case MachO::DICE_KIND_JUMP_TABLE32:
468 outs() << "JUMP_TABLE32";
469 break;
470 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
471 outs() << "ABS_JUMP_TABLE32";
472 break;
473 default:
474 outs() << format("0x%04" PRIx32, Kind);
475 break;
476 }
477 } else
478 outs() << format("0x%04" PRIx32, Kind);
479 outs() << "\n";
480 }
481}
482
Kevin Enderby9a509442015-01-27 21:28:24 +0000483static void PrintLinkOptHints(MachOObjectFile *O) {
484 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
485 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
486 uint32_t nloh = LohLC.datasize;
487 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
488 for (uint32_t i = 0; i < nloh;) {
489 unsigned n;
490 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
491 i += n;
492 outs() << " identifier " << identifier << " ";
493 if (i >= nloh)
494 return;
495 switch (identifier) {
496 case 1:
497 outs() << "AdrpAdrp\n";
498 break;
499 case 2:
500 outs() << "AdrpLdr\n";
501 break;
502 case 3:
503 outs() << "AdrpAddLdr\n";
504 break;
505 case 4:
506 outs() << "AdrpLdrGotLdr\n";
507 break;
508 case 5:
509 outs() << "AdrpAddStr\n";
510 break;
511 case 6:
512 outs() << "AdrpLdrGotStr\n";
513 break;
514 case 7:
515 outs() << "AdrpAdd\n";
516 break;
517 case 8:
518 outs() << "AdrpLdrGot\n";
519 break;
520 default:
521 outs() << "Unknown identifier value\n";
522 break;
523 }
524 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
525 i += n;
526 outs() << " narguments " << narguments << "\n";
527 if (i >= nloh)
528 return;
529
530 for (uint32_t j = 0; j < narguments; j++) {
531 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
532 i += n;
533 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
534 if (i >= nloh)
535 return;
536 }
537 }
538}
539
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000540static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000541 unsigned Index = 0;
542 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000543 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
544 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
545 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
546 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
547 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
548 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
549 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
550 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
551 if (dl.dylib.name < dl.cmdsize) {
552 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
553 if (JustId)
554 outs() << p << "\n";
555 else {
556 outs() << "\t" << p;
557 outs() << " (compatibility version "
558 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
559 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
560 << (dl.dylib.compatibility_version & 0xff) << ",";
561 outs() << " current version "
562 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
563 << ((dl.dylib.current_version >> 8) & 0xff) << "."
564 << (dl.dylib.current_version & 0xff) << ")\n";
565 }
566 } else {
567 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
568 if (Load.C.cmd == MachO::LC_ID_DYLIB)
569 outs() << "LC_ID_DYLIB ";
570 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
571 outs() << "LC_LOAD_DYLIB ";
572 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
573 outs() << "LC_LOAD_WEAK_DYLIB ";
574 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
575 outs() << "LC_LAZY_LOAD_DYLIB ";
576 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
577 outs() << "LC_REEXPORT_DYLIB ";
578 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
579 outs() << "LC_LOAD_UPWARD_DYLIB ";
580 else
581 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000582 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000583 }
584 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000585 }
586}
587
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000588typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
589
590static void CreateSymbolAddressMap(MachOObjectFile *O,
591 SymbolAddressMap *AddrMap) {
592 // Create a map of symbol addresses to symbol names.
593 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000594 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000595 if (!STOrErr)
596 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000597 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000598 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
599 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000600 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000601 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000602 if (!SymNameOrErr)
603 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000604 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000605 if (!SymName.startswith(".objc"))
606 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000607 }
608 }
609}
610
611// GuessSymbolName is passed the address of what might be a symbol and a
612// pointer to the SymbolAddressMap. It returns the name of a symbol
613// with that address or nullptr if no symbol is found with that address.
614static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
615 const char *SymbolName = nullptr;
616 // A DenseMap can't lookup up some values.
617 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
618 StringRef name = AddrMap->lookup(value);
619 if (!name.empty())
620 SymbolName = name.data();
621 }
622 return SymbolName;
623}
624
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000625static void DumpCstringChar(const char c) {
626 char p[2];
627 p[0] = c;
628 p[1] = '\0';
629 outs().write_escaped(p);
630}
631
Kevin Enderby10ba0412015-02-04 21:38:42 +0000632static void DumpCstringSection(MachOObjectFile *O, const char *sect,
633 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000634 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000635 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000636 if (print_addresses) {
637 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000638 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000639 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000640 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000641 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000642 for (; i < sect_size && sect[i] != '\0'; i++)
643 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000644 if (i < sect_size && sect[i] == '\0')
645 outs() << "\n";
646 }
647}
648
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000649static void DumpLiteral4(uint32_t l, float f) {
650 outs() << format("0x%08" PRIx32, l);
651 if ((l & 0x7f800000) != 0x7f800000)
652 outs() << format(" (%.16e)\n", f);
653 else {
654 if (l == 0x7f800000)
655 outs() << " (+Infinity)\n";
656 else if (l == 0xff800000)
657 outs() << " (-Infinity)\n";
658 else if ((l & 0x00400000) == 0x00400000)
659 outs() << " (non-signaling Not-a-Number)\n";
660 else
661 outs() << " (signaling Not-a-Number)\n";
662 }
663}
664
665static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
666 uint32_t sect_size, uint64_t sect_addr,
667 bool print_addresses) {
668 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
669 if (print_addresses) {
670 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000671 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000672 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000673 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000674 }
675 float f;
676 memcpy(&f, sect + i, sizeof(float));
677 if (O->isLittleEndian() != sys::IsLittleEndianHost)
678 sys::swapByteOrder(f);
679 uint32_t l;
680 memcpy(&l, sect + i, sizeof(uint32_t));
681 if (O->isLittleEndian() != sys::IsLittleEndianHost)
682 sys::swapByteOrder(l);
683 DumpLiteral4(l, f);
684 }
685}
686
687static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
688 double d) {
689 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
690 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000691 Hi = (O->isLittleEndian()) ? l1 : l0;
692 Lo = (O->isLittleEndian()) ? l0 : l1;
693
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000694 // Hi is the high word, so this is equivalent to if(isfinite(d))
695 if ((Hi & 0x7ff00000) != 0x7ff00000)
696 outs() << format(" (%.16e)\n", d);
697 else {
698 if (Hi == 0x7ff00000 && Lo == 0)
699 outs() << " (+Infinity)\n";
700 else if (Hi == 0xfff00000 && Lo == 0)
701 outs() << " (-Infinity)\n";
702 else if ((Hi & 0x00080000) == 0x00080000)
703 outs() << " (non-signaling Not-a-Number)\n";
704 else
705 outs() << " (signaling Not-a-Number)\n";
706 }
707}
708
709static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
710 uint32_t sect_size, uint64_t sect_addr,
711 bool print_addresses) {
712 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
713 if (print_addresses) {
714 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000715 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000716 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000717 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000718 }
719 double d;
720 memcpy(&d, sect + i, sizeof(double));
721 if (O->isLittleEndian() != sys::IsLittleEndianHost)
722 sys::swapByteOrder(d);
723 uint32_t l0, l1;
724 memcpy(&l0, sect + i, sizeof(uint32_t));
725 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
726 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
727 sys::swapByteOrder(l0);
728 sys::swapByteOrder(l1);
729 }
730 DumpLiteral8(O, l0, l1, d);
731 }
732}
733
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000734static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
735 outs() << format("0x%08" PRIx32, l0) << " ";
736 outs() << format("0x%08" PRIx32, l1) << " ";
737 outs() << format("0x%08" PRIx32, l2) << " ";
738 outs() << format("0x%08" PRIx32, l3) << "\n";
739}
740
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000741static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
742 uint32_t sect_size, uint64_t sect_addr,
743 bool print_addresses) {
744 for (uint32_t i = 0; i < sect_size; i += 16) {
745 if (print_addresses) {
746 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000747 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000748 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000749 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000750 }
751 uint32_t l0, l1, l2, l3;
752 memcpy(&l0, sect + i, sizeof(uint32_t));
753 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
754 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
755 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
756 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
757 sys::swapByteOrder(l0);
758 sys::swapByteOrder(l1);
759 sys::swapByteOrder(l2);
760 sys::swapByteOrder(l3);
761 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000762 DumpLiteral16(l0, l1, l2, l3);
763 }
764}
765
766static void DumpLiteralPointerSection(MachOObjectFile *O,
767 const SectionRef &Section,
768 const char *sect, uint32_t sect_size,
769 uint64_t sect_addr,
770 bool print_addresses) {
771 // Collect the literal sections in this Mach-O file.
772 std::vector<SectionRef> LiteralSections;
773 for (const SectionRef &Section : O->sections()) {
774 DataRefImpl Ref = Section.getRawDataRefImpl();
775 uint32_t section_type;
776 if (O->is64Bit()) {
777 const MachO::section_64 Sec = O->getSection64(Ref);
778 section_type = Sec.flags & MachO::SECTION_TYPE;
779 } else {
780 const MachO::section Sec = O->getSection(Ref);
781 section_type = Sec.flags & MachO::SECTION_TYPE;
782 }
783 if (section_type == MachO::S_CSTRING_LITERALS ||
784 section_type == MachO::S_4BYTE_LITERALS ||
785 section_type == MachO::S_8BYTE_LITERALS ||
786 section_type == MachO::S_16BYTE_LITERALS)
787 LiteralSections.push_back(Section);
788 }
789
790 // Set the size of the literal pointer.
791 uint32_t lp_size = O->is64Bit() ? 8 : 4;
792
Eric Christopher572e03a2015-06-19 01:53:21 +0000793 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000794 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
795 for (const RelocationRef &Reloc : Section.relocations()) {
796 DataRefImpl Rel;
797 MachO::any_relocation_info RE;
798 bool isExtern = false;
799 Rel = Reloc.getRawDataRefImpl();
800 RE = O->getRelocation(Rel);
801 isExtern = O->getPlainRelocationExternal(RE);
802 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000803 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000804 symbol_iterator RelocSym = Reloc.getSymbol();
805 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
806 }
807 }
808 array_pod_sort(Relocs.begin(), Relocs.end());
809
810 // Dump each literal pointer.
811 for (uint32_t i = 0; i < sect_size; i += lp_size) {
812 if (print_addresses) {
813 if (O->is64Bit())
814 outs() << format("%016" PRIx64, sect_addr + i) << " ";
815 else
816 outs() << format("%08" PRIx64, sect_addr + i) << " ";
817 }
818 uint64_t lp;
819 if (O->is64Bit()) {
820 memcpy(&lp, sect + i, sizeof(uint64_t));
821 if (O->isLittleEndian() != sys::IsLittleEndianHost)
822 sys::swapByteOrder(lp);
823 } else {
824 uint32_t li;
825 memcpy(&li, sect + i, sizeof(uint32_t));
826 if (O->isLittleEndian() != sys::IsLittleEndianHost)
827 sys::swapByteOrder(li);
828 lp = li;
829 }
830
831 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +0000832 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
833 return P.first == i;
834 });
David Blaikie33dd45d02015-03-23 18:39:02 +0000835 if (Reloc != Relocs.end()) {
836 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000837 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000838 if (!SymName)
839 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000840 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000841 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000842 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000843
844 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +0000845 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
846 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
847 });
David Blaikie33dd45d02015-03-23 18:39:02 +0000848 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000849 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000850 continue;
851 }
852
853 uint64_t SectAddress = Sect->getAddress();
854 uint64_t SectSize = Sect->getSize();
855
856 StringRef SectName;
857 Sect->getName(SectName);
858 DataRefImpl Ref = Sect->getRawDataRefImpl();
859 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
860 outs() << SegmentName << ":" << SectName << ":";
861
862 uint32_t section_type;
863 if (O->is64Bit()) {
864 const MachO::section_64 Sec = O->getSection64(Ref);
865 section_type = Sec.flags & MachO::SECTION_TYPE;
866 } else {
867 const MachO::section Sec = O->getSection(Ref);
868 section_type = Sec.flags & MachO::SECTION_TYPE;
869 }
870
871 StringRef BytesStr;
872 Sect->getContents(BytesStr);
873 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
874
875 switch (section_type) {
876 case MachO::S_CSTRING_LITERALS:
877 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
878 i++) {
879 DumpCstringChar(Contents[i]);
880 }
881 outs() << "\n";
882 break;
883 case MachO::S_4BYTE_LITERALS:
884 float f;
885 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
886 uint32_t l;
887 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
888 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
889 sys::swapByteOrder(f);
890 sys::swapByteOrder(l);
891 }
892 DumpLiteral4(l, f);
893 break;
894 case MachO::S_8BYTE_LITERALS: {
895 double d;
896 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
897 uint32_t l0, l1;
898 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
899 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
900 sizeof(uint32_t));
901 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
902 sys::swapByteOrder(f);
903 sys::swapByteOrder(l0);
904 sys::swapByteOrder(l1);
905 }
906 DumpLiteral8(O, l0, l1, d);
907 break;
908 }
909 case MachO::S_16BYTE_LITERALS: {
910 uint32_t l0, l1, l2, l3;
911 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
912 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
913 sizeof(uint32_t));
914 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
915 sizeof(uint32_t));
916 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
917 sizeof(uint32_t));
918 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
919 sys::swapByteOrder(l0);
920 sys::swapByteOrder(l1);
921 sys::swapByteOrder(l2);
922 sys::swapByteOrder(l3);
923 }
924 DumpLiteral16(l0, l1, l2, l3);
925 break;
926 }
927 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000928 }
929}
930
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000931static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
932 uint32_t sect_size, uint64_t sect_addr,
933 SymbolAddressMap *AddrMap,
934 bool verbose) {
935 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000936 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000937 for (uint32_t i = 0; i < sect_size; i += stride) {
938 const char *SymbolName = nullptr;
939 if (O->is64Bit()) {
940 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
941 uint64_t pointer_value;
942 memcpy(&pointer_value, sect + i, stride);
943 if (O->isLittleEndian() != sys::IsLittleEndianHost)
944 sys::swapByteOrder(pointer_value);
945 outs() << format("0x%016" PRIx64, pointer_value);
946 if (verbose)
947 SymbolName = GuessSymbolName(pointer_value, AddrMap);
948 } else {
949 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
950 uint32_t pointer_value;
951 memcpy(&pointer_value, sect + i, stride);
952 if (O->isLittleEndian() != sys::IsLittleEndianHost)
953 sys::swapByteOrder(pointer_value);
954 outs() << format("0x%08" PRIx32, pointer_value);
955 if (verbose)
956 SymbolName = GuessSymbolName(pointer_value, AddrMap);
957 }
958 if (SymbolName)
959 outs() << " " << SymbolName;
960 outs() << "\n";
961 }
962}
963
964static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
965 uint32_t size, uint64_t addr) {
966 uint32_t cputype = O->getHeader().cputype;
967 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
968 uint32_t j;
969 for (uint32_t i = 0; i < size; i += j, addr += j) {
970 if (O->is64Bit())
971 outs() << format("%016" PRIx64, addr) << "\t";
972 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000973 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000974 for (j = 0; j < 16 && i + j < size; j++) {
975 uint8_t byte_word = *(sect + i + j);
976 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
977 }
978 outs() << "\n";
979 }
980 } else {
981 uint32_t j;
982 for (uint32_t i = 0; i < size; i += j, addr += j) {
983 if (O->is64Bit())
984 outs() << format("%016" PRIx64, addr) << "\t";
985 else
Kevin Enderbyc4930852016-04-27 22:36:18 +0000986 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000987 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
988 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +0000989 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000990 uint32_t long_word;
991 memcpy(&long_word, sect + i + j, sizeof(int32_t));
992 if (O->isLittleEndian() != sys::IsLittleEndianHost)
993 sys::swapByteOrder(long_word);
994 outs() << format("%08" PRIx32, long_word) << " ";
995 } else {
996 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +0000997 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000998 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
999 }
1000 }
1001 }
1002 outs() << "\n";
1003 }
1004 }
1005}
1006
Kevin Enderby95df54c2015-02-04 01:01:38 +00001007static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1008 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001009static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1010 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001011#ifdef HAVE_LIBXAR
1012static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1013 uint32_t size, bool verbose,
1014 bool PrintXarHeader, bool PrintXarFileHeaders,
1015 std::string XarMemberName);
1016#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001017
1018static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1019 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001020 SymbolAddressMap AddrMap;
1021 if (verbose)
1022 CreateSymbolAddressMap(O, &AddrMap);
1023
Colin LeMahieufcc32762015-07-29 19:08:10 +00001024 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1025 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001026 std::pair<StringRef, StringRef> DumpSegSectName;
1027 DumpSegSectName = DumpSection.split(',');
1028 StringRef DumpSegName, DumpSectName;
1029 if (DumpSegSectName.second.size()) {
1030 DumpSegName = DumpSegSectName.first;
1031 DumpSectName = DumpSegSectName.second;
1032 } else {
1033 DumpSegName = "";
1034 DumpSectName = DumpSegSectName.first;
1035 }
1036 for (const SectionRef &Section : O->sections()) {
1037 StringRef SectName;
1038 Section.getName(SectName);
1039 DataRefImpl Ref = Section.getRawDataRefImpl();
1040 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1041 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1042 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001043
Kevin Enderby95df54c2015-02-04 01:01:38 +00001044 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001045 if (O->is64Bit()) {
1046 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001047 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001048
1049 } else {
1050 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001051 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001052 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001053 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001054
1055 StringRef BytesStr;
1056 Section.getContents(BytesStr);
1057 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1058 uint32_t sect_size = BytesStr.size();
1059 uint64_t sect_addr = Section.getAddress();
1060
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001061 outs() << "Contents of (" << SegName << "," << SectName
1062 << ") section\n";
1063
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001064 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001065 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1066 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1067 DisassembleMachO(Filename, O, SegName, SectName);
1068 continue;
1069 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001070 if (SegName == "__TEXT" && SectName == "__info_plist") {
1071 outs() << sect;
1072 continue;
1073 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001074 if (SegName == "__OBJC" && SectName == "__protocol") {
1075 DumpProtocolSection(O, sect, sect_size, sect_addr);
1076 continue;
1077 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001078#ifdef HAVE_LIBXAR
1079 if (SegName == "__LLVM" && SectName == "__bundle") {
1080 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1081 ArchiveHeaders, "");
1082 continue;
1083 }
1084#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001085 switch (section_type) {
1086 case MachO::S_REGULAR:
1087 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1088 break;
1089 case MachO::S_ZEROFILL:
1090 outs() << "zerofill section and has no contents in the file\n";
1091 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001092 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001093 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001094 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001095 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001096 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001097 break;
1098 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001099 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 break;
1101 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001102 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1103 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001104 case MachO::S_LITERAL_POINTERS:
1105 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001106 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001107 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001108 case MachO::S_MOD_INIT_FUNC_POINTERS:
1109 case MachO::S_MOD_TERM_FUNC_POINTERS:
1110 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1111 verbose);
1112 break;
1113 default:
1114 outs() << "Unknown section type ("
1115 << format("0x%08" PRIx32, section_type) << ")\n";
1116 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1117 break;
1118 }
1119 } else {
1120 if (section_type == MachO::S_ZEROFILL)
1121 outs() << "zerofill section and has no contents in the file\n";
1122 else
1123 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1124 }
1125 }
1126 }
1127 }
1128}
1129
Kevin Enderbycd66be52015-03-11 22:06:32 +00001130static void DumpInfoPlistSectionContents(StringRef Filename,
1131 MachOObjectFile *O) {
1132 for (const SectionRef &Section : O->sections()) {
1133 StringRef SectName;
1134 Section.getName(SectName);
1135 DataRefImpl Ref = Section.getRawDataRefImpl();
1136 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1137 if (SegName == "__TEXT" && SectName == "__info_plist") {
1138 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1139 StringRef BytesStr;
1140 Section.getContents(BytesStr);
1141 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001142 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001143 return;
1144 }
1145 }
1146}
1147
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001148// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1149// and if it is and there is a list of architecture flags is specified then
1150// check to make sure this Mach-O file is one of those architectures or all
1151// architectures were specified. If not then an error is generated and this
1152// routine returns false. Else it returns true.
1153static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001154 auto *MachO = dyn_cast<MachOObjectFile>(O);
1155
1156 if (!MachO || ArchAll || ArchFlags.empty())
1157 return true;
1158
1159 MachO::mach_header H;
1160 MachO::mach_header_64 H_64;
1161 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001162 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001163 if (MachO->is64Bit()) {
1164 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001165 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1166 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001167 } else {
1168 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001169 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1170 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001171 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001172 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001173 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001174 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001175 })) {
1176 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1177 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001178 }
1179 return true;
1180}
1181
Kevin Enderby0fc11822015-04-01 20:57:01 +00001182static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1183
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001184// ProcessMachO() is passed a single opened Mach-O file, which may be an
1185// archive member and or in a slice of a universal file. It prints the
1186// the file name and header info and then processes it according to the
1187// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001188static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001189 StringRef ArchiveMemberName = StringRef(),
1190 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001191 // If we are doing some processing here on the Mach-O file print the header
1192 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001193 // UniversalHeaders or ArchiveHeaders.
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001194 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001195 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001196 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001197 if (!NoLeadingHeaders) {
1198 outs() << Name;
1199 if (!ArchiveMemberName.empty())
1200 outs() << '(' << ArchiveMemberName << ')';
1201 if (!ArchitectureName.empty())
1202 outs() << " (architecture " << ArchitectureName << ")";
1203 outs() << ":\n";
1204 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001205 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001206 // To use the report_error() form with an ArchiveName and FileName set
1207 // these up based on what is passed for Name and ArchiveMemberName.
1208 StringRef ArchiveName;
1209 StringRef FileName;
1210 if (!ArchiveMemberName.empty()) {
1211 ArchiveName = Name;
1212 FileName = ArchiveMemberName;
1213 } else {
1214 ArchiveName = StringRef();
1215 FileName = Name;
1216 }
1217
1218 // If we need the symbol table to do the operation then check it here to
1219 // produce a good error message as to where the Mach-O file comes from in
1220 // the error message.
1221 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1222 UnwindInfo)
1223 if (Error Err = MachOOF->checkSymbolTable())
1224 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001225
1226 if (Disassemble)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001227 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001228 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001229 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001230 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001231 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001232 if (LinkOptHints)
1233 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001234 if (Relocations)
1235 PrintRelocations(MachOOF);
1236 if (SectionHeaders)
1237 PrintSectionHeaders(MachOOF);
1238 if (SectionContents)
1239 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001240 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001241 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001242 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001243 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001244 if (DylibsUsed)
1245 PrintDylibs(MachOOF, false);
1246 if (DylibId)
1247 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001248 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001249 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001250 if (UnwindInfo)
1251 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001252 if (PrivateHeaders) {
1253 printMachOFileHeader(MachOOF);
1254 printMachOLoadCommands(MachOOF);
1255 }
1256 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001257 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001258 if (ObjcMetaData)
1259 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001260 if (ExportsTrie)
1261 printExportsTrie(MachOOF);
1262 if (Rebase)
1263 printRebaseTable(MachOOF);
1264 if (Bind)
1265 printBindTable(MachOOF);
1266 if (LazyBind)
1267 printLazyBindTable(MachOOF);
1268 if (WeakBind)
1269 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001270
1271 if (DwarfDumpType != DIDT_Null) {
1272 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1273 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001274 DIDumpOptions DumpOpts;
1275 DumpOpts.DumpType = DwarfDumpType;
1276 DumpOpts.DumpEH = true;
1277 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001278 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001279}
1280
Kevin Enderby131d1772015-01-09 19:22:37 +00001281// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1282static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1283 outs() << " cputype (" << cputype << ")\n";
1284 outs() << " cpusubtype (" << cpusubtype << ")\n";
1285}
1286
1287// printCPUType() helps print_fat_headers by printing the cputype and
1288// pusubtype (symbolically for the one's it knows about).
1289static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1290 switch (cputype) {
1291 case MachO::CPU_TYPE_I386:
1292 switch (cpusubtype) {
1293 case MachO::CPU_SUBTYPE_I386_ALL:
1294 outs() << " cputype CPU_TYPE_I386\n";
1295 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1296 break;
1297 default:
1298 printUnknownCPUType(cputype, cpusubtype);
1299 break;
1300 }
1301 break;
1302 case MachO::CPU_TYPE_X86_64:
1303 switch (cpusubtype) {
1304 case MachO::CPU_SUBTYPE_X86_64_ALL:
1305 outs() << " cputype CPU_TYPE_X86_64\n";
1306 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1307 break;
1308 case MachO::CPU_SUBTYPE_X86_64_H:
1309 outs() << " cputype CPU_TYPE_X86_64\n";
1310 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1311 break;
1312 default:
1313 printUnknownCPUType(cputype, cpusubtype);
1314 break;
1315 }
1316 break;
1317 case MachO::CPU_TYPE_ARM:
1318 switch (cpusubtype) {
1319 case MachO::CPU_SUBTYPE_ARM_ALL:
1320 outs() << " cputype CPU_TYPE_ARM\n";
1321 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1322 break;
1323 case MachO::CPU_SUBTYPE_ARM_V4T:
1324 outs() << " cputype CPU_TYPE_ARM\n";
1325 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1326 break;
1327 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1328 outs() << " cputype CPU_TYPE_ARM\n";
1329 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1330 break;
1331 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1332 outs() << " cputype CPU_TYPE_ARM\n";
1333 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1334 break;
1335 case MachO::CPU_SUBTYPE_ARM_V6:
1336 outs() << " cputype CPU_TYPE_ARM\n";
1337 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1338 break;
1339 case MachO::CPU_SUBTYPE_ARM_V6M:
1340 outs() << " cputype CPU_TYPE_ARM\n";
1341 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1342 break;
1343 case MachO::CPU_SUBTYPE_ARM_V7:
1344 outs() << " cputype CPU_TYPE_ARM\n";
1345 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1346 break;
1347 case MachO::CPU_SUBTYPE_ARM_V7EM:
1348 outs() << " cputype CPU_TYPE_ARM\n";
1349 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1350 break;
1351 case MachO::CPU_SUBTYPE_ARM_V7K:
1352 outs() << " cputype CPU_TYPE_ARM\n";
1353 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1354 break;
1355 case MachO::CPU_SUBTYPE_ARM_V7M:
1356 outs() << " cputype CPU_TYPE_ARM\n";
1357 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1358 break;
1359 case MachO::CPU_SUBTYPE_ARM_V7S:
1360 outs() << " cputype CPU_TYPE_ARM\n";
1361 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1362 break;
1363 default:
1364 printUnknownCPUType(cputype, cpusubtype);
1365 break;
1366 }
1367 break;
1368 case MachO::CPU_TYPE_ARM64:
1369 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1370 case MachO::CPU_SUBTYPE_ARM64_ALL:
1371 outs() << " cputype CPU_TYPE_ARM64\n";
1372 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1373 break;
1374 default:
1375 printUnknownCPUType(cputype, cpusubtype);
1376 break;
1377 }
1378 break;
1379 default:
1380 printUnknownCPUType(cputype, cpusubtype);
1381 break;
1382 }
1383}
1384
1385static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1386 bool verbose) {
1387 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001388 if (verbose) {
1389 if (UB->getMagic() == MachO::FAT_MAGIC)
1390 outs() << "fat_magic FAT_MAGIC\n";
1391 else // UB->getMagic() == MachO::FAT_MAGIC_64
1392 outs() << "fat_magic FAT_MAGIC_64\n";
1393 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001394 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1395
1396 uint32_t nfat_arch = UB->getNumberOfObjects();
1397 StringRef Buf = UB->getData();
1398 uint64_t size = Buf.size();
1399 uint64_t big_size = sizeof(struct MachO::fat_header) +
1400 nfat_arch * sizeof(struct MachO::fat_arch);
1401 outs() << "nfat_arch " << UB->getNumberOfObjects();
1402 if (nfat_arch == 0)
1403 outs() << " (malformed, contains zero architecture types)\n";
1404 else if (big_size > size)
1405 outs() << " (malformed, architectures past end of file)\n";
1406 else
1407 outs() << "\n";
1408
1409 for (uint32_t i = 0; i < nfat_arch; ++i) {
1410 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1411 uint32_t cputype = OFA.getCPUType();
1412 uint32_t cpusubtype = OFA.getCPUSubType();
1413 outs() << "architecture ";
1414 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1415 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1416 uint32_t other_cputype = other_OFA.getCPUType();
1417 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001418 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001419 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001420 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001421 outs() << "(illegal duplicate architecture) ";
1422 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001423 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001424 }
1425 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001426 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001427 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1428 } else {
1429 outs() << i << "\n";
1430 outs() << " cputype " << cputype << "\n";
1431 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1432 << "\n";
1433 }
1434 if (verbose &&
1435 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1436 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1437 else
1438 outs() << " capabilities "
1439 << format("0x%" PRIx32,
1440 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1441 outs() << " offset " << OFA.getOffset();
1442 if (OFA.getOffset() > size)
1443 outs() << " (past end of file)";
1444 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1445 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1446 outs() << "\n";
1447 outs() << " size " << OFA.getSize();
1448 big_size = OFA.getOffset() + OFA.getSize();
1449 if (big_size > size)
1450 outs() << " (past end of file)";
1451 outs() << "\n";
1452 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1453 << ")\n";
1454 }
1455}
1456
Kevin Enderby6524bd82016-07-19 20:47:07 +00001457static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1458 bool verbose, bool print_offset,
1459 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001460 if (print_offset)
1461 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001462 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1463 if (!ModeOrErr)
1464 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1465 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001466 if (verbose) {
1467 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1468 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1469 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001470 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1471 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1472 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1473 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1474 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1475 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1476 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1477 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1478 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001479 } else {
1480 outs() << format("0%o ", Mode);
1481 }
1482
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001483 Expected<unsigned> UIDOrErr = C.getUID();
1484 if (!UIDOrErr)
1485 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1486 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001487 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001488 Expected<unsigned> GIDOrErr = C.getGID();
1489 if (!GIDOrErr)
1490 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1491 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001492 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001493 Expected<uint64_t> Size = C.getRawSize();
1494 if (!Size)
1495 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001496 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001497
1498 StringRef RawLastModified = C.getRawLastModified();
1499 if (verbose) {
1500 unsigned Seconds;
1501 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001502 outs() << "(date: \"" << RawLastModified
1503 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001504 else {
1505 // Since cime(3) returns a 26 character string of the form:
1506 // "Sun Sep 16 01:03:52 1973\n\0"
1507 // just print 24 characters.
1508 time_t t = Seconds;
1509 outs() << format("%.24s ", ctime(&t));
1510 }
1511 } else {
1512 outs() << RawLastModified << " ";
1513 }
1514
1515 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001516 Expected<StringRef> NameOrErr = C.getName();
1517 if (!NameOrErr) {
1518 consumeError(NameOrErr.takeError());
1519 Expected<StringRef> NameOrErr = C.getRawName();
1520 if (!NameOrErr)
1521 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1522 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001523 outs() << RawName << "\n";
1524 } else {
1525 StringRef Name = NameOrErr.get();
1526 outs() << Name << "\n";
1527 }
1528 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001529 Expected<StringRef> NameOrErr = C.getRawName();
1530 if (!NameOrErr)
1531 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1532 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001533 outs() << RawName << "\n";
1534 }
1535}
1536
Kevin Enderby6524bd82016-07-19 20:47:07 +00001537static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1538 bool print_offset,
1539 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001540 Error Err = Error::success();
1541 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001542 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001543 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1544
Lang Hamesfc209622016-07-14 02:24:01 +00001545 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001546 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001547}
1548
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001549// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1550// -arch flags selecting just those slices as specified by them and also parses
1551// archive files. Then for each individual Mach-O file ProcessMachO() is
1552// called to process the file based on the command line options.
1553void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001554 // Check for -arch all and verifiy the -arch flags are valid.
1555 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1556 if (ArchFlags[i] == "all") {
1557 ArchAll = true;
1558 } else {
1559 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1560 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1561 "'for the -arch option\n";
1562 return;
1563 }
1564 }
1565 }
1566
1567 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001568 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001569 if (!BinaryOrErr) {
1570 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1571 report_error(Filename, std::move(E));
1572 else
1573 outs() << Filename << ": is not an object file\n";
1574 return;
1575 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001576 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001577
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001578 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1579 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001580 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001581 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1582
Mehdi Amini41af4302016-11-11 04:28:40 +00001583 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001584 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001585 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1586 if (!ChildOrErr) {
1587 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1588 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001589 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001590 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001591 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1592 if (!checkMachOAndArchFlags(O, Filename))
1593 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001594 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001595 }
1596 }
Lang Hamesfc209622016-07-14 02:24:01 +00001597 if (Err)
1598 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001599 return;
1600 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001601 if (UniversalHeaders) {
1602 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001603 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001604 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001605 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1606 // If we have a list of architecture flags specified dump only those.
1607 if (!ArchAll && ArchFlags.size() != 0) {
1608 // Look for a slice in the universal binary that matches each ArchFlag.
1609 bool ArchFound;
1610 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1611 ArchFound = false;
1612 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1613 E = UB->end_objects();
1614 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001615 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001616 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001617 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001618 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001619 std::string ArchitectureName = "";
1620 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +00001621 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001622 if (ObjOrErr) {
1623 ObjectFile &O = *ObjOrErr.get();
1624 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001625 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001626 } else if (auto E = isNotObjectErrorInvalidFileType(
1627 ObjOrErr.takeError())) {
1628 report_error(Filename, StringRef(), std::move(E),
1629 ArchitectureName);
1630 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001631 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001632 I->getAsArchive()) {
1633 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001634 outs() << "Archive : " << Filename;
1635 if (!ArchitectureName.empty())
1636 outs() << " (architecture " << ArchitectureName << ")";
1637 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001638 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001639 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1640 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001641 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001642 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001643 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1644 if (!ChildOrErr) {
1645 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001646 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001647 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001648 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001649 if (MachOObjectFile *O =
1650 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001651 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001652 }
Lang Hamesfc209622016-07-14 02:24:01 +00001653 if (Err)
1654 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001655 } else {
1656 consumeError(AOrErr.takeError());
1657 error("Mach-O universal file: " + Filename + " for " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001658 "architecture " + StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001659 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001660 }
1661 }
1662 }
1663 if (!ArchFound) {
1664 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1665 << "architecture: " + ArchFlags[i] + "\n";
1666 return;
1667 }
1668 }
1669 return;
1670 }
1671 // No architecture flags were specified so if this contains a slice that
1672 // matches the host architecture dump only that.
1673 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001674 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1675 E = UB->end_objects();
1676 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001677 if (MachOObjectFile::getHostArch().getArchName() ==
Kevin Enderby59343a92016-12-16 22:54:02 +00001678 I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001679 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001680 std::string ArchiveName;
1681 ArchiveName.clear();
1682 if (ObjOrErr) {
1683 ObjectFile &O = *ObjOrErr.get();
1684 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001685 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001686 } else if (auto E = isNotObjectErrorInvalidFileType(
1687 ObjOrErr.takeError())) {
1688 report_error(Filename, std::move(E));
1689 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001690 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001691 I->getAsArchive()) {
1692 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001693 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001694 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001695 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1696 ArchiveMemberOffsets);
Mehdi Amini41af4302016-11-11 04:28:40 +00001697 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001698 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001699 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1700 if (!ChildOrErr) {
1701 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1702 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001703 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001704 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001705 if (MachOObjectFile *O =
1706 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001707 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001708 }
Lang Hamesfc209622016-07-14 02:24:01 +00001709 if (Err)
1710 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001711 } else {
1712 consumeError(AOrErr.takeError());
1713 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001714 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001715 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001716 }
1717 return;
1718 }
1719 }
1720 }
1721 // Either all architectures have been specified or none have been specified
1722 // and this does not contain the host architecture so dump all the slices.
1723 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1724 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1725 E = UB->end_objects();
1726 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001727 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001728 std::string ArchitectureName = "";
1729 if (moreThanOneArch)
Kevin Enderby59343a92016-12-16 22:54:02 +00001730 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001731 if (ObjOrErr) {
1732 ObjectFile &Obj = *ObjOrErr.get();
1733 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001734 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001735 } else if (auto E = isNotObjectErrorInvalidFileType(
1736 ObjOrErr.takeError())) {
1737 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1738 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001739 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1740 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001741 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001742 outs() << "Archive : " << Filename;
1743 if (!ArchitectureName.empty())
1744 outs() << " (architecture " << ArchitectureName << ")";
1745 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001746 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001747 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1748 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001749 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001750 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001751 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1752 if (!ChildOrErr) {
1753 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001754 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001755 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001756 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001757 if (MachOObjectFile *O =
1758 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1759 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001760 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1761 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001762 }
1763 }
Lang Hamesfc209622016-07-14 02:24:01 +00001764 if (Err)
1765 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001766 } else {
1767 consumeError(AOrErr.takeError());
1768 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001769 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001770 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001771 }
1772 }
1773 return;
1774 }
1775 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1776 if (!checkMachOAndArchFlags(O, Filename))
1777 return;
1778 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001779 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001780 } else
1781 errs() << "llvm-objdump: '" << Filename << "': "
1782 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001783 return;
1784 }
1785 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001786}
1787
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001788// The block of info used by the Symbolizer call backs.
1789struct DisassembleInfo {
1790 bool verbose;
1791 MachOObjectFile *O;
1792 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001793 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001794 std::vector<SectionRef> *Sections;
1795 const char *class_name;
1796 const char *selector_name;
1797 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001798 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001799 uint64_t adrp_addr;
1800 uint32_t adrp_inst;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00001801 std::unique_ptr<SymbolAddressMap> bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001802 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001803};
1804
1805// SymbolizerGetOpInfo() is the operand information call back function.
1806// This is called to get the symbolic information for operand(s) of an
1807// instruction when it is being done. This routine does this from
1808// the relocation information, symbol table, etc. That block of information
1809// is a pointer to the struct DisassembleInfo that was passed when the
1810// disassembler context was created and passed to back to here when
1811// called back by the disassembler for instruction operands that could have
1812// relocation information. The address of the instruction containing operand is
1813// at the Pc parameter. The immediate value the operand has is passed in
1814// op_info->Value and is at Offset past the start of the instruction and has a
1815// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1816// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1817// names and addends of the symbolic expression to add for the operand. The
1818// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1819// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001820static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1821 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001822 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1823 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001824 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001825
1826 // Make sure all fields returned are zero if we don't set them.
1827 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1828 op_info->Value = value;
1829
1830 // If the TagType is not the value 1 which it code knows about or if no
1831 // verbose symbolic information is wanted then just return 0, indicating no
1832 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001833 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001834 return 0;
1835
1836 unsigned int Arch = info->O->getArch();
1837 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001838 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1839 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001840 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1841 // TODO:
1842 // Search the external relocation entries of a fully linked image
1843 // (if any) for an entry that matches this segment offset.
1844 // uint32_t seg_offset = (Pc + Offset);
1845 return 0;
1846 }
1847 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1848 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001849 uint32_t sect_addr = info->S.getAddress();
1850 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1851 bool reloc_found = false;
1852 DataRefImpl Rel;
1853 MachO::any_relocation_info RE;
1854 bool isExtern = false;
1855 SymbolRef Symbol;
1856 bool r_scattered = false;
1857 uint32_t r_value, pair_r_value, r_type;
1858 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001859 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001860 if (RelocOffset == sect_offset) {
1861 Rel = Reloc.getRawDataRefImpl();
1862 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001863 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001864 r_scattered = info->O->isRelocationScattered(RE);
1865 if (r_scattered) {
1866 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001867 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1868 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1869 DataRefImpl RelNext = Rel;
1870 info->O->moveRelocationNext(RelNext);
1871 MachO::any_relocation_info RENext;
1872 RENext = info->O->getRelocation(RelNext);
1873 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001874 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001875 else
1876 return 0;
1877 }
1878 } else {
1879 isExtern = info->O->getPlainRelocationExternal(RE);
1880 if (isExtern) {
1881 symbol_iterator RelocSym = Reloc.getSymbol();
1882 Symbol = *RelocSym;
1883 }
1884 }
1885 reloc_found = true;
1886 break;
1887 }
1888 }
1889 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001890 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001891 if (!SymName)
1892 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001893 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001894 op_info->AddSymbol.Present = 1;
1895 op_info->AddSymbol.Name = name;
1896 // For i386 extern relocation entries the value in the instruction is
1897 // the offset from the symbol, and value is already set in op_info->Value.
1898 return 1;
1899 }
1900 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1901 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001902 const char *add = GuessSymbolName(r_value, info->AddrMap);
1903 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001904 uint32_t offset = value - (r_value - pair_r_value);
1905 op_info->AddSymbol.Present = 1;
1906 if (add != nullptr)
1907 op_info->AddSymbol.Name = add;
1908 else
1909 op_info->AddSymbol.Value = r_value;
1910 op_info->SubtractSymbol.Present = 1;
1911 if (sub != nullptr)
1912 op_info->SubtractSymbol.Name = sub;
1913 else
1914 op_info->SubtractSymbol.Value = pair_r_value;
1915 op_info->Value = offset;
1916 return 1;
1917 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001918 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001919 }
1920 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001921 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1922 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001923 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1924 // TODO:
1925 // Search the external relocation entries of a fully linked image
1926 // (if any) for an entry that matches this segment offset.
1927 // uint64_t seg_offset = (Pc + Offset);
1928 return 0;
1929 }
1930 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1931 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001932 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001933 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1934 bool reloc_found = false;
1935 DataRefImpl Rel;
1936 MachO::any_relocation_info RE;
1937 bool isExtern = false;
1938 SymbolRef Symbol;
1939 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001940 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001941 if (RelocOffset == sect_offset) {
1942 Rel = Reloc.getRawDataRefImpl();
1943 RE = info->O->getRelocation(Rel);
1944 // NOTE: Scattered relocations don't exist on x86_64.
1945 isExtern = info->O->getPlainRelocationExternal(RE);
1946 if (isExtern) {
1947 symbol_iterator RelocSym = Reloc.getSymbol();
1948 Symbol = *RelocSym;
1949 }
1950 reloc_found = true;
1951 break;
1952 }
1953 }
1954 if (reloc_found && isExtern) {
1955 // The Value passed in will be adjusted by the Pc if the instruction
1956 // adds the Pc. But for x86_64 external relocation entries the Value
1957 // is the offset from the external symbol.
1958 if (info->O->getAnyRelocationPCRel(RE))
1959 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001960 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001961 if (!SymName)
1962 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001963 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001964 unsigned Type = info->O->getAnyRelocationType(RE);
1965 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1966 DataRefImpl RelNext = Rel;
1967 info->O->moveRelocationNext(RelNext);
1968 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1969 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1970 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1971 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1972 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1973 op_info->SubtractSymbol.Present = 1;
1974 op_info->SubtractSymbol.Name = name;
1975 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1976 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001977 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001978 if (!SymNameNext)
1979 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001980 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001981 }
1982 }
1983 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1984 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1985 op_info->AddSymbol.Present = 1;
1986 op_info->AddSymbol.Name = name;
1987 return 1;
1988 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001989 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001990 }
1991 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001992 if (Offset != 0 || (Size != 4 && Size != 2))
1993 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001994 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1995 // TODO:
1996 // Search the external relocation entries of a fully linked image
1997 // (if any) for an entry that matches this segment offset.
1998 // uint32_t seg_offset = (Pc + Offset);
1999 return 0;
2000 }
2001 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2002 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002003 uint32_t sect_addr = info->S.getAddress();
2004 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002005 DataRefImpl Rel;
2006 MachO::any_relocation_info RE;
2007 bool isExtern = false;
2008 SymbolRef Symbol;
2009 bool r_scattered = false;
2010 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002011 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002012 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2013 uint64_t RelocOffset = Reloc.getOffset();
2014 return RelocOffset == sect_offset;
2015 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002016
2017 if (Reloc == info->S.relocations().end())
2018 return 0;
2019
2020 Rel = Reloc->getRawDataRefImpl();
2021 RE = info->O->getRelocation(Rel);
2022 r_length = info->O->getAnyRelocationLength(RE);
2023 r_scattered = info->O->isRelocationScattered(RE);
2024 if (r_scattered) {
2025 r_value = info->O->getScatteredRelocationValue(RE);
2026 r_type = info->O->getScatteredRelocationType(RE);
2027 } else {
2028 r_type = info->O->getAnyRelocationType(RE);
2029 isExtern = info->O->getPlainRelocationExternal(RE);
2030 if (isExtern) {
2031 symbol_iterator RelocSym = Reloc->getSymbol();
2032 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002033 }
2034 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002035 if (r_type == MachO::ARM_RELOC_HALF ||
2036 r_type == MachO::ARM_RELOC_SECTDIFF ||
2037 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2038 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2039 DataRefImpl RelNext = Rel;
2040 info->O->moveRelocationNext(RelNext);
2041 MachO::any_relocation_info RENext;
2042 RENext = info->O->getRelocation(RelNext);
2043 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2044 if (info->O->isRelocationScattered(RENext))
2045 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2046 }
2047
2048 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002049 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002050 if (!SymName)
2051 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002052 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002053 op_info->AddSymbol.Present = 1;
2054 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002055 switch (r_type) {
2056 case MachO::ARM_RELOC_HALF:
2057 if ((r_length & 0x1) == 1) {
2058 op_info->Value = value << 16 | other_half;
2059 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2060 } else {
2061 op_info->Value = other_half << 16 | value;
2062 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002063 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002064 break;
2065 default:
2066 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002067 }
2068 return 1;
2069 }
2070 // If we have a branch that is not an external relocation entry then
2071 // return 0 so the code in tryAddingSymbolicOperand() can use the
2072 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002073 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002074 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2075 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002076 return 0;
2077
2078 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002079 if (r_type == MachO::ARM_RELOC_HALF ||
2080 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2081 if ((r_length & 0x1) == 1)
2082 value = value << 16 | other_half;
2083 else
2084 value = other_half << 16 | value;
2085 }
2086 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2087 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2088 offset = value - r_value;
2089 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002090 }
2091
David Blaikie33dd45d02015-03-23 18:39:02 +00002092 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002093 if ((r_length & 0x1) == 1)
2094 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2095 else
2096 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002097 const char *add = GuessSymbolName(r_value, info->AddrMap);
2098 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002099 int32_t offset = value - (r_value - pair_r_value);
2100 op_info->AddSymbol.Present = 1;
2101 if (add != nullptr)
2102 op_info->AddSymbol.Name = add;
2103 else
2104 op_info->AddSymbol.Value = r_value;
2105 op_info->SubtractSymbol.Present = 1;
2106 if (sub != nullptr)
2107 op_info->SubtractSymbol.Name = sub;
2108 else
2109 op_info->SubtractSymbol.Value = pair_r_value;
2110 op_info->Value = offset;
2111 return 1;
2112 }
2113
Kevin Enderby930fdc72014-11-06 19:00:13 +00002114 op_info->AddSymbol.Present = 1;
2115 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002116 if (r_type == MachO::ARM_RELOC_HALF) {
2117 if ((r_length & 0x1) == 1)
2118 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2119 else
2120 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002121 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002122 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002123 if (add != nullptr) {
2124 op_info->AddSymbol.Name = add;
2125 return 1;
2126 }
2127 op_info->AddSymbol.Value = value;
2128 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002129 }
2130 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002131 if (Offset != 0 || Size != 4)
2132 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002133 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2134 // TODO:
2135 // Search the external relocation entries of a fully linked image
2136 // (if any) for an entry that matches this segment offset.
2137 // uint64_t seg_offset = (Pc + Offset);
2138 return 0;
2139 }
2140 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2141 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002142 uint64_t sect_addr = info->S.getAddress();
2143 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002144 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002145 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2146 uint64_t RelocOffset = Reloc.getOffset();
2147 return RelocOffset == sect_offset;
2148 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002149
David Blaikie33dd45d02015-03-23 18:39:02 +00002150 if (Reloc == info->S.relocations().end())
2151 return 0;
2152
2153 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2154 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2155 uint32_t r_type = info->O->getAnyRelocationType(RE);
2156 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2157 DataRefImpl RelNext = Rel;
2158 info->O->moveRelocationNext(RelNext);
2159 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2160 if (value == 0) {
2161 value = info->O->getPlainRelocationSymbolNum(RENext);
2162 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002163 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002164 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002165 // NOTE: Scattered relocations don't exist on arm64.
2166 if (!info->O->getPlainRelocationExternal(RE))
2167 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002168 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002169 if (!SymName)
2170 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002171 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002172 op_info->AddSymbol.Present = 1;
2173 op_info->AddSymbol.Name = name;
2174
2175 switch (r_type) {
2176 case MachO::ARM64_RELOC_PAGE21:
2177 /* @page */
2178 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2179 break;
2180 case MachO::ARM64_RELOC_PAGEOFF12:
2181 /* @pageoff */
2182 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2183 break;
2184 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2185 /* @gotpage */
2186 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2187 break;
2188 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2189 /* @gotpageoff */
2190 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2191 break;
2192 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2193 /* @tvlppage is not implemented in llvm-mc */
2194 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2195 break;
2196 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2197 /* @tvlppageoff is not implemented in llvm-mc */
2198 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2199 break;
2200 default:
2201 case MachO::ARM64_RELOC_BRANCH26:
2202 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2203 break;
2204 }
2205 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002206 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002207 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002208}
2209
Kevin Enderbybf246f52014-09-24 23:08:22 +00002210// GuessCstringPointer is passed the address of what might be a pointer to a
2211// literal string in a cstring section. If that address is in a cstring section
2212// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002213static const char *GuessCstringPointer(uint64_t ReferenceValue,
2214 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002215 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002216 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2217 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2218 for (unsigned J = 0; J < Seg.nsects; ++J) {
2219 MachO::section_64 Sec = info->O->getSection64(Load, J);
2220 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2221 if (section_type == MachO::S_CSTRING_LITERALS &&
2222 ReferenceValue >= Sec.addr &&
2223 ReferenceValue < Sec.addr + Sec.size) {
2224 uint64_t sect_offset = ReferenceValue - Sec.addr;
2225 uint64_t object_offset = Sec.offset + sect_offset;
2226 StringRef MachOContents = info->O->getData();
2227 uint64_t object_size = MachOContents.size();
2228 const char *object_addr = (const char *)MachOContents.data();
2229 if (object_offset < object_size) {
2230 const char *name = object_addr + object_offset;
2231 return name;
2232 } else {
2233 return nullptr;
2234 }
2235 }
2236 }
2237 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2238 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2239 for (unsigned J = 0; J < Seg.nsects; ++J) {
2240 MachO::section Sec = info->O->getSection(Load, J);
2241 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2242 if (section_type == MachO::S_CSTRING_LITERALS &&
2243 ReferenceValue >= Sec.addr &&
2244 ReferenceValue < Sec.addr + Sec.size) {
2245 uint64_t sect_offset = ReferenceValue - Sec.addr;
2246 uint64_t object_offset = Sec.offset + sect_offset;
2247 StringRef MachOContents = info->O->getData();
2248 uint64_t object_size = MachOContents.size();
2249 const char *object_addr = (const char *)MachOContents.data();
2250 if (object_offset < object_size) {
2251 const char *name = object_addr + object_offset;
2252 return name;
2253 } else {
2254 return nullptr;
2255 }
2256 }
2257 }
2258 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002259 }
2260 return nullptr;
2261}
2262
Kevin Enderby85974882014-09-26 22:20:44 +00002263// GuessIndirectSymbol returns the name of the indirect symbol for the
2264// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2265// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2266// symbol name being referenced by the stub or pointer.
2267static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2268 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002269 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2270 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002271 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002272 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2273 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2274 for (unsigned J = 0; J < Seg.nsects; ++J) {
2275 MachO::section_64 Sec = info->O->getSection64(Load, J);
2276 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2277 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2278 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2279 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2280 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2281 section_type == MachO::S_SYMBOL_STUBS) &&
2282 ReferenceValue >= Sec.addr &&
2283 ReferenceValue < Sec.addr + Sec.size) {
2284 uint32_t stride;
2285 if (section_type == MachO::S_SYMBOL_STUBS)
2286 stride = Sec.reserved2;
2287 else
2288 stride = 8;
2289 if (stride == 0)
2290 return nullptr;
2291 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2292 if (index < Dysymtab.nindirectsyms) {
2293 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002294 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002295 if (indirect_symbol < Symtab.nsyms) {
2296 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2297 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002298 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002299 if (!SymName)
2300 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002301 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002302 return name;
2303 }
2304 }
2305 }
2306 }
2307 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2308 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2309 for (unsigned J = 0; J < Seg.nsects; ++J) {
2310 MachO::section Sec = info->O->getSection(Load, J);
2311 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2312 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2313 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2314 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2315 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2316 section_type == MachO::S_SYMBOL_STUBS) &&
2317 ReferenceValue >= Sec.addr &&
2318 ReferenceValue < Sec.addr + Sec.size) {
2319 uint32_t stride;
2320 if (section_type == MachO::S_SYMBOL_STUBS)
2321 stride = Sec.reserved2;
2322 else
2323 stride = 4;
2324 if (stride == 0)
2325 return nullptr;
2326 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2327 if (index < Dysymtab.nindirectsyms) {
2328 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002329 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002330 if (indirect_symbol < Symtab.nsyms) {
2331 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2332 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002333 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002334 if (!SymName)
2335 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002336 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002337 return name;
2338 }
2339 }
2340 }
2341 }
2342 }
Kevin Enderby85974882014-09-26 22:20:44 +00002343 }
2344 return nullptr;
2345}
2346
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002347// method_reference() is called passing it the ReferenceName that might be
2348// a reference it to an Objective-C method call. If so then it allocates and
2349// assembles a method call string with the values last seen and saved in
2350// the DisassembleInfo's class_name and selector_name fields. This is saved
2351// into the method field of the info and any previous string is free'ed.
2352// Then the class_name field in the info is set to nullptr. The method call
2353// string is set into ReferenceName and ReferenceType is set to
2354// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2355// then both ReferenceType and ReferenceName are left unchanged.
2356static void method_reference(struct DisassembleInfo *info,
2357 uint64_t *ReferenceType,
2358 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002359 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002360 if (*ReferenceName != nullptr) {
2361 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002362 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002363 if (info->method != nullptr)
2364 free(info->method);
2365 if (info->class_name != nullptr) {
2366 info->method = (char *)malloc(5 + strlen(info->class_name) +
2367 strlen(info->selector_name));
2368 if (info->method != nullptr) {
2369 strcpy(info->method, "+[");
2370 strcat(info->method, info->class_name);
2371 strcat(info->method, " ");
2372 strcat(info->method, info->selector_name);
2373 strcat(info->method, "]");
2374 *ReferenceName = info->method;
2375 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2376 }
2377 } else {
2378 info->method = (char *)malloc(9 + strlen(info->selector_name));
2379 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002380 if (Arch == Triple::x86_64)
2381 strcpy(info->method, "-[%rdi ");
2382 else if (Arch == Triple::aarch64)
2383 strcpy(info->method, "-[x0 ");
2384 else
2385 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002386 strcat(info->method, info->selector_name);
2387 strcat(info->method, "]");
2388 *ReferenceName = info->method;
2389 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2390 }
2391 }
2392 info->class_name = nullptr;
2393 }
2394 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002395 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002396 if (info->method != nullptr)
2397 free(info->method);
2398 info->method = (char *)malloc(17 + strlen(info->selector_name));
2399 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002400 if (Arch == Triple::x86_64)
2401 strcpy(info->method, "-[[%rdi super] ");
2402 else if (Arch == Triple::aarch64)
2403 strcpy(info->method, "-[[x0 super] ");
2404 else
2405 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002406 strcat(info->method, info->selector_name);
2407 strcat(info->method, "]");
2408 *ReferenceName = info->method;
2409 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2410 }
2411 info->class_name = nullptr;
2412 }
2413 }
2414 }
2415}
2416
2417// GuessPointerPointer() is passed the address of what might be a pointer to
2418// a reference to an Objective-C class, selector, message ref or cfstring.
2419// If so the value of the pointer is returned and one of the booleans are set
2420// to true. If not zero is returned and all the booleans are set to false.
2421static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2422 struct DisassembleInfo *info,
2423 bool &classref, bool &selref, bool &msgref,
2424 bool &cfstring) {
2425 classref = false;
2426 selref = false;
2427 msgref = false;
2428 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002429 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002430 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2431 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2432 for (unsigned J = 0; J < Seg.nsects; ++J) {
2433 MachO::section_64 Sec = info->O->getSection64(Load, J);
2434 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2435 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2436 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2437 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2438 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2439 ReferenceValue >= Sec.addr &&
2440 ReferenceValue < Sec.addr + Sec.size) {
2441 uint64_t sect_offset = ReferenceValue - Sec.addr;
2442 uint64_t object_offset = Sec.offset + sect_offset;
2443 StringRef MachOContents = info->O->getData();
2444 uint64_t object_size = MachOContents.size();
2445 const char *object_addr = (const char *)MachOContents.data();
2446 if (object_offset < object_size) {
2447 uint64_t pointer_value;
2448 memcpy(&pointer_value, object_addr + object_offset,
2449 sizeof(uint64_t));
2450 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2451 sys::swapByteOrder(pointer_value);
2452 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2453 selref = true;
2454 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2455 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2456 classref = true;
2457 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2458 ReferenceValue + 8 < Sec.addr + Sec.size) {
2459 msgref = true;
2460 memcpy(&pointer_value, object_addr + object_offset + 8,
2461 sizeof(uint64_t));
2462 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2463 sys::swapByteOrder(pointer_value);
2464 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2465 cfstring = true;
2466 return pointer_value;
2467 } else {
2468 return 0;
2469 }
2470 }
2471 }
2472 }
2473 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002474 }
2475 return 0;
2476}
2477
2478// get_pointer_64 returns a pointer to the bytes in the object file at the
2479// Address from a section in the Mach-O file. And indirectly returns the
2480// offset into the section, number of bytes left in the section past the offset
2481// and which section is was being referenced. If the Address is not in a
2482// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002483static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2484 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002485 DisassembleInfo *info,
2486 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002487 offset = 0;
2488 left = 0;
2489 S = SectionRef();
2490 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2491 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2492 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002493 if (SectSize == 0)
2494 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002495 if (objc_only) {
2496 StringRef SectName;
2497 ((*(info->Sections))[SectIdx]).getName(SectName);
2498 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2499 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2500 if (SegName != "__OBJC" && SectName != "__cstring")
2501 continue;
2502 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002503 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2504 S = (*(info->Sections))[SectIdx];
2505 offset = Address - SectAddress;
2506 left = SectSize - offset;
2507 StringRef SectContents;
2508 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2509 return SectContents.data() + offset;
2510 }
2511 }
2512 return nullptr;
2513}
2514
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002515static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2516 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002517 DisassembleInfo *info,
2518 bool objc_only = false) {
2519 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002520}
2521
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002522// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2523// the symbol indirectly through n_value. Based on the relocation information
2524// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002525// If no relocation information is found and a non-zero ReferenceValue for the
2526// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002527static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2528 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002529 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002530 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002531 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002532 return nullptr;
2533
2534 // See if there is an external relocation entry at the sect_offset.
2535 bool reloc_found = false;
2536 DataRefImpl Rel;
2537 MachO::any_relocation_info RE;
2538 bool isExtern = false;
2539 SymbolRef Symbol;
2540 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002541 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002542 if (RelocOffset == sect_offset) {
2543 Rel = Reloc.getRawDataRefImpl();
2544 RE = info->O->getRelocation(Rel);
2545 if (info->O->isRelocationScattered(RE))
2546 continue;
2547 isExtern = info->O->getPlainRelocationExternal(RE);
2548 if (isExtern) {
2549 symbol_iterator RelocSym = Reloc.getSymbol();
2550 Symbol = *RelocSym;
2551 }
2552 reloc_found = true;
2553 break;
2554 }
2555 }
2556 // If there is an external relocation entry for a symbol in this section
2557 // at this section_offset then use that symbol's value for the n_value
2558 // and return its name.
2559 const char *SymbolName = nullptr;
2560 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002561 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002562 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002563 if (!NameOrError)
2564 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002565 StringRef Name = *NameOrError;
2566 if (!Name.empty()) {
2567 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002568 return SymbolName;
2569 }
2570 }
2571
2572 // TODO: For fully linked images, look through the external relocation
2573 // entries off the dynamic symtab command. For these the r_offset is from the
2574 // start of the first writeable segment in the Mach-O file. So the offset
2575 // to this section from that segment is passed to this routine by the caller,
2576 // as the database_offset. Which is the difference of the section's starting
2577 // address and the first writable segment.
2578 //
2579 // NOTE: need add passing the database_offset to this routine.
2580
Kevin Enderby0fc11822015-04-01 20:57:01 +00002581 // We did not find an external relocation entry so look up the ReferenceValue
2582 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002583 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002584
2585 return SymbolName;
2586}
2587
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002588static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2589 DisassembleInfo *info,
2590 uint32_t ReferenceValue) {
2591 uint64_t n_value64;
2592 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2593}
2594
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002595// These are structs in the Objective-C meta data and read to produce the
2596// comments for disassembly. While these are part of the ABI they are no
2597// public defintions. So the are here not in include/llvm/Support/MachO.h .
2598
2599// The cfstring object in a 64-bit Mach-O file.
2600struct cfstring64_t {
2601 uint64_t isa; // class64_t * (64-bit pointer)
2602 uint64_t flags; // flag bits
2603 uint64_t characters; // char * (64-bit pointer)
2604 uint64_t length; // number of non-NULL characters in above
2605};
2606
2607// The class object in a 64-bit Mach-O file.
2608struct class64_t {
2609 uint64_t isa; // class64_t * (64-bit pointer)
2610 uint64_t superclass; // class64_t * (64-bit pointer)
2611 uint64_t cache; // Cache (64-bit pointer)
2612 uint64_t vtable; // IMP * (64-bit pointer)
2613 uint64_t data; // class_ro64_t * (64-bit pointer)
2614};
2615
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002616struct class32_t {
2617 uint32_t isa; /* class32_t * (32-bit pointer) */
2618 uint32_t superclass; /* class32_t * (32-bit pointer) */
2619 uint32_t cache; /* Cache (32-bit pointer) */
2620 uint32_t vtable; /* IMP * (32-bit pointer) */
2621 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2622};
2623
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002624struct class_ro64_t {
2625 uint32_t flags;
2626 uint32_t instanceStart;
2627 uint32_t instanceSize;
2628 uint32_t reserved;
2629 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2630 uint64_t name; // const char * (64-bit pointer)
2631 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2632 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2633 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2634 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2635 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2636};
2637
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002638struct class_ro32_t {
2639 uint32_t flags;
2640 uint32_t instanceStart;
2641 uint32_t instanceSize;
2642 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2643 uint32_t name; /* const char * (32-bit pointer) */
2644 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2645 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2646 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2647 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2648 uint32_t baseProperties; /* const struct objc_property_list *
2649 (32-bit pointer) */
2650};
2651
2652/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002653#define RO_META (1 << 0)
2654#define RO_ROOT (1 << 1)
2655#define RO_HAS_CXX_STRUCTORS (1 << 2)
2656
2657struct method_list64_t {
2658 uint32_t entsize;
2659 uint32_t count;
2660 /* struct method64_t first; These structures follow inline */
2661};
2662
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002663struct method_list32_t {
2664 uint32_t entsize;
2665 uint32_t count;
2666 /* struct method32_t first; These structures follow inline */
2667};
2668
Kevin Enderby0fc11822015-04-01 20:57:01 +00002669struct method64_t {
2670 uint64_t name; /* SEL (64-bit pointer) */
2671 uint64_t types; /* const char * (64-bit pointer) */
2672 uint64_t imp; /* IMP (64-bit pointer) */
2673};
2674
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002675struct method32_t {
2676 uint32_t name; /* SEL (32-bit pointer) */
2677 uint32_t types; /* const char * (32-bit pointer) */
2678 uint32_t imp; /* IMP (32-bit pointer) */
2679};
2680
Kevin Enderby0fc11822015-04-01 20:57:01 +00002681struct protocol_list64_t {
2682 uint64_t count; /* uintptr_t (a 64-bit value) */
2683 /* struct protocol64_t * list[0]; These pointers follow inline */
2684};
2685
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002686struct protocol_list32_t {
2687 uint32_t count; /* uintptr_t (a 32-bit value) */
2688 /* struct protocol32_t * list[0]; These pointers follow inline */
2689};
2690
Kevin Enderby0fc11822015-04-01 20:57:01 +00002691struct protocol64_t {
2692 uint64_t isa; /* id * (64-bit pointer) */
2693 uint64_t name; /* const char * (64-bit pointer) */
2694 uint64_t protocols; /* struct protocol_list64_t *
2695 (64-bit pointer) */
2696 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2697 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2698 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2699 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2700 uint64_t instanceProperties; /* struct objc_property_list *
2701 (64-bit pointer) */
2702};
2703
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002704struct protocol32_t {
2705 uint32_t isa; /* id * (32-bit pointer) */
2706 uint32_t name; /* const char * (32-bit pointer) */
2707 uint32_t protocols; /* struct protocol_list_t *
2708 (32-bit pointer) */
2709 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2710 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2711 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2712 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2713 uint32_t instanceProperties; /* struct objc_property_list *
2714 (32-bit pointer) */
2715};
2716
Kevin Enderby0fc11822015-04-01 20:57:01 +00002717struct ivar_list64_t {
2718 uint32_t entsize;
2719 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002720 /* struct ivar64_t first; These structures follow inline */
2721};
2722
2723struct ivar_list32_t {
2724 uint32_t entsize;
2725 uint32_t count;
2726 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002727};
2728
2729struct ivar64_t {
2730 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2731 uint64_t name; /* const char * (64-bit pointer) */
2732 uint64_t type; /* const char * (64-bit pointer) */
2733 uint32_t alignment;
2734 uint32_t size;
2735};
2736
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002737struct ivar32_t {
2738 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2739 uint32_t name; /* const char * (32-bit pointer) */
2740 uint32_t type; /* const char * (32-bit pointer) */
2741 uint32_t alignment;
2742 uint32_t size;
2743};
2744
Kevin Enderby0fc11822015-04-01 20:57:01 +00002745struct objc_property_list64 {
2746 uint32_t entsize;
2747 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002748 /* struct objc_property64 first; These structures follow inline */
2749};
2750
2751struct objc_property_list32 {
2752 uint32_t entsize;
2753 uint32_t count;
2754 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002755};
2756
2757struct objc_property64 {
2758 uint64_t name; /* const char * (64-bit pointer) */
2759 uint64_t attributes; /* const char * (64-bit pointer) */
2760};
2761
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002762struct objc_property32 {
2763 uint32_t name; /* const char * (32-bit pointer) */
2764 uint32_t attributes; /* const char * (32-bit pointer) */
2765};
2766
Kevin Enderby0fc11822015-04-01 20:57:01 +00002767struct category64_t {
2768 uint64_t name; /* const char * (64-bit pointer) */
2769 uint64_t cls; /* struct class_t * (64-bit pointer) */
2770 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2771 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2772 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2773 uint64_t instanceProperties; /* struct objc_property_list *
2774 (64-bit pointer) */
2775};
2776
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002777struct category32_t {
2778 uint32_t name; /* const char * (32-bit pointer) */
2779 uint32_t cls; /* struct class_t * (32-bit pointer) */
2780 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2781 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2782 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2783 uint32_t instanceProperties; /* struct objc_property_list *
2784 (32-bit pointer) */
2785};
2786
Kevin Enderby0fc11822015-04-01 20:57:01 +00002787struct objc_image_info64 {
2788 uint32_t version;
2789 uint32_t flags;
2790};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002791struct objc_image_info32 {
2792 uint32_t version;
2793 uint32_t flags;
2794};
Kevin Enderby846c0002015-04-16 17:19:59 +00002795struct imageInfo_t {
2796 uint32_t version;
2797 uint32_t flags;
2798};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002799/* masks for objc_image_info.flags */
2800#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2801#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2802
2803struct message_ref64 {
2804 uint64_t imp; /* IMP (64-bit pointer) */
2805 uint64_t sel; /* SEL (64-bit pointer) */
2806};
2807
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002808struct message_ref32 {
2809 uint32_t imp; /* IMP (32-bit pointer) */
2810 uint32_t sel; /* SEL (32-bit pointer) */
2811};
2812
Kevin Enderby846c0002015-04-16 17:19:59 +00002813// Objective-C 1 (32-bit only) meta data structs.
2814
2815struct objc_module_t {
2816 uint32_t version;
2817 uint32_t size;
2818 uint32_t name; /* char * (32-bit pointer) */
2819 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2820};
2821
2822struct objc_symtab_t {
2823 uint32_t sel_ref_cnt;
2824 uint32_t refs; /* SEL * (32-bit pointer) */
2825 uint16_t cls_def_cnt;
2826 uint16_t cat_def_cnt;
2827 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2828};
2829
2830struct objc_class_t {
2831 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2832 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2833 uint32_t name; /* const char * (32-bit pointer) */
2834 int32_t version;
2835 int32_t info;
2836 int32_t instance_size;
2837 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2838 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2839 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2840 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2841};
2842
2843#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2844// class is not a metaclass
2845#define CLS_CLASS 0x1
2846// class is a metaclass
2847#define CLS_META 0x2
2848
2849struct objc_category_t {
2850 uint32_t category_name; /* char * (32-bit pointer) */
2851 uint32_t class_name; /* char * (32-bit pointer) */
2852 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2853 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2854 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2855};
2856
2857struct objc_ivar_t {
2858 uint32_t ivar_name; /* char * (32-bit pointer) */
2859 uint32_t ivar_type; /* char * (32-bit pointer) */
2860 int32_t ivar_offset;
2861};
2862
2863struct objc_ivar_list_t {
2864 int32_t ivar_count;
2865 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2866};
2867
2868struct objc_method_list_t {
2869 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2870 int32_t method_count;
2871 // struct objc_method_t method_list[1]; /* variable length structure */
2872};
2873
2874struct objc_method_t {
2875 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2876 uint32_t method_types; /* char * (32-bit pointer) */
2877 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2878 (32-bit pointer) */
2879};
2880
2881struct objc_protocol_list_t {
2882 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2883 int32_t count;
2884 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2885 // (32-bit pointer) */
2886};
2887
2888struct objc_protocol_t {
2889 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2890 uint32_t protocol_name; /* char * (32-bit pointer) */
2891 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2892 uint32_t instance_methods; /* struct objc_method_description_list *
2893 (32-bit pointer) */
2894 uint32_t class_methods; /* struct objc_method_description_list *
2895 (32-bit pointer) */
2896};
2897
2898struct objc_method_description_list_t {
2899 int32_t count;
2900 // struct objc_method_description_t list[1];
2901};
2902
2903struct objc_method_description_t {
2904 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2905 uint32_t types; /* char * (32-bit pointer) */
2906};
2907
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002908inline void swapStruct(struct cfstring64_t &cfs) {
2909 sys::swapByteOrder(cfs.isa);
2910 sys::swapByteOrder(cfs.flags);
2911 sys::swapByteOrder(cfs.characters);
2912 sys::swapByteOrder(cfs.length);
2913}
2914
2915inline void swapStruct(struct class64_t &c) {
2916 sys::swapByteOrder(c.isa);
2917 sys::swapByteOrder(c.superclass);
2918 sys::swapByteOrder(c.cache);
2919 sys::swapByteOrder(c.vtable);
2920 sys::swapByteOrder(c.data);
2921}
2922
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002923inline void swapStruct(struct class32_t &c) {
2924 sys::swapByteOrder(c.isa);
2925 sys::swapByteOrder(c.superclass);
2926 sys::swapByteOrder(c.cache);
2927 sys::swapByteOrder(c.vtable);
2928 sys::swapByteOrder(c.data);
2929}
2930
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002931inline void swapStruct(struct class_ro64_t &cro) {
2932 sys::swapByteOrder(cro.flags);
2933 sys::swapByteOrder(cro.instanceStart);
2934 sys::swapByteOrder(cro.instanceSize);
2935 sys::swapByteOrder(cro.reserved);
2936 sys::swapByteOrder(cro.ivarLayout);
2937 sys::swapByteOrder(cro.name);
2938 sys::swapByteOrder(cro.baseMethods);
2939 sys::swapByteOrder(cro.baseProtocols);
2940 sys::swapByteOrder(cro.ivars);
2941 sys::swapByteOrder(cro.weakIvarLayout);
2942 sys::swapByteOrder(cro.baseProperties);
2943}
2944
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002945inline void swapStruct(struct class_ro32_t &cro) {
2946 sys::swapByteOrder(cro.flags);
2947 sys::swapByteOrder(cro.instanceStart);
2948 sys::swapByteOrder(cro.instanceSize);
2949 sys::swapByteOrder(cro.ivarLayout);
2950 sys::swapByteOrder(cro.name);
2951 sys::swapByteOrder(cro.baseMethods);
2952 sys::swapByteOrder(cro.baseProtocols);
2953 sys::swapByteOrder(cro.ivars);
2954 sys::swapByteOrder(cro.weakIvarLayout);
2955 sys::swapByteOrder(cro.baseProperties);
2956}
2957
Kevin Enderby0fc11822015-04-01 20:57:01 +00002958inline void swapStruct(struct method_list64_t &ml) {
2959 sys::swapByteOrder(ml.entsize);
2960 sys::swapByteOrder(ml.count);
2961}
2962
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002963inline void swapStruct(struct method_list32_t &ml) {
2964 sys::swapByteOrder(ml.entsize);
2965 sys::swapByteOrder(ml.count);
2966}
2967
Kevin Enderby0fc11822015-04-01 20:57:01 +00002968inline void swapStruct(struct method64_t &m) {
2969 sys::swapByteOrder(m.name);
2970 sys::swapByteOrder(m.types);
2971 sys::swapByteOrder(m.imp);
2972}
2973
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002974inline void swapStruct(struct method32_t &m) {
2975 sys::swapByteOrder(m.name);
2976 sys::swapByteOrder(m.types);
2977 sys::swapByteOrder(m.imp);
2978}
2979
Kevin Enderby0fc11822015-04-01 20:57:01 +00002980inline void swapStruct(struct protocol_list64_t &pl) {
2981 sys::swapByteOrder(pl.count);
2982}
2983
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002984inline void swapStruct(struct protocol_list32_t &pl) {
2985 sys::swapByteOrder(pl.count);
2986}
2987
Kevin Enderby0fc11822015-04-01 20:57:01 +00002988inline void swapStruct(struct protocol64_t &p) {
2989 sys::swapByteOrder(p.isa);
2990 sys::swapByteOrder(p.name);
2991 sys::swapByteOrder(p.protocols);
2992 sys::swapByteOrder(p.instanceMethods);
2993 sys::swapByteOrder(p.classMethods);
2994 sys::swapByteOrder(p.optionalInstanceMethods);
2995 sys::swapByteOrder(p.optionalClassMethods);
2996 sys::swapByteOrder(p.instanceProperties);
2997}
2998
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002999inline void swapStruct(struct protocol32_t &p) {
3000 sys::swapByteOrder(p.isa);
3001 sys::swapByteOrder(p.name);
3002 sys::swapByteOrder(p.protocols);
3003 sys::swapByteOrder(p.instanceMethods);
3004 sys::swapByteOrder(p.classMethods);
3005 sys::swapByteOrder(p.optionalInstanceMethods);
3006 sys::swapByteOrder(p.optionalClassMethods);
3007 sys::swapByteOrder(p.instanceProperties);
3008}
3009
Kevin Enderby0fc11822015-04-01 20:57:01 +00003010inline void swapStruct(struct ivar_list64_t &il) {
3011 sys::swapByteOrder(il.entsize);
3012 sys::swapByteOrder(il.count);
3013}
3014
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003015inline void swapStruct(struct ivar_list32_t &il) {
3016 sys::swapByteOrder(il.entsize);
3017 sys::swapByteOrder(il.count);
3018}
3019
Kevin Enderby0fc11822015-04-01 20:57:01 +00003020inline void swapStruct(struct ivar64_t &i) {
3021 sys::swapByteOrder(i.offset);
3022 sys::swapByteOrder(i.name);
3023 sys::swapByteOrder(i.type);
3024 sys::swapByteOrder(i.alignment);
3025 sys::swapByteOrder(i.size);
3026}
3027
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003028inline void swapStruct(struct ivar32_t &i) {
3029 sys::swapByteOrder(i.offset);
3030 sys::swapByteOrder(i.name);
3031 sys::swapByteOrder(i.type);
3032 sys::swapByteOrder(i.alignment);
3033 sys::swapByteOrder(i.size);
3034}
3035
Kevin Enderby0fc11822015-04-01 20:57:01 +00003036inline void swapStruct(struct objc_property_list64 &pl) {
3037 sys::swapByteOrder(pl.entsize);
3038 sys::swapByteOrder(pl.count);
3039}
3040
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003041inline void swapStruct(struct objc_property_list32 &pl) {
3042 sys::swapByteOrder(pl.entsize);
3043 sys::swapByteOrder(pl.count);
3044}
3045
Kevin Enderby0fc11822015-04-01 20:57:01 +00003046inline void swapStruct(struct objc_property64 &op) {
3047 sys::swapByteOrder(op.name);
3048 sys::swapByteOrder(op.attributes);
3049}
3050
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003051inline void swapStruct(struct objc_property32 &op) {
3052 sys::swapByteOrder(op.name);
3053 sys::swapByteOrder(op.attributes);
3054}
3055
Kevin Enderby0fc11822015-04-01 20:57:01 +00003056inline void swapStruct(struct category64_t &c) {
3057 sys::swapByteOrder(c.name);
3058 sys::swapByteOrder(c.cls);
3059 sys::swapByteOrder(c.instanceMethods);
3060 sys::swapByteOrder(c.classMethods);
3061 sys::swapByteOrder(c.protocols);
3062 sys::swapByteOrder(c.instanceProperties);
3063}
3064
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003065inline void swapStruct(struct category32_t &c) {
3066 sys::swapByteOrder(c.name);
3067 sys::swapByteOrder(c.cls);
3068 sys::swapByteOrder(c.instanceMethods);
3069 sys::swapByteOrder(c.classMethods);
3070 sys::swapByteOrder(c.protocols);
3071 sys::swapByteOrder(c.instanceProperties);
3072}
3073
Kevin Enderby0fc11822015-04-01 20:57:01 +00003074inline void swapStruct(struct objc_image_info64 &o) {
3075 sys::swapByteOrder(o.version);
3076 sys::swapByteOrder(o.flags);
3077}
3078
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003079inline void swapStruct(struct objc_image_info32 &o) {
3080 sys::swapByteOrder(o.version);
3081 sys::swapByteOrder(o.flags);
3082}
3083
Kevin Enderby846c0002015-04-16 17:19:59 +00003084inline void swapStruct(struct imageInfo_t &o) {
3085 sys::swapByteOrder(o.version);
3086 sys::swapByteOrder(o.flags);
3087}
3088
Kevin Enderby0fc11822015-04-01 20:57:01 +00003089inline void swapStruct(struct message_ref64 &mr) {
3090 sys::swapByteOrder(mr.imp);
3091 sys::swapByteOrder(mr.sel);
3092}
3093
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003094inline void swapStruct(struct message_ref32 &mr) {
3095 sys::swapByteOrder(mr.imp);
3096 sys::swapByteOrder(mr.sel);
3097}
3098
Kevin Enderby846c0002015-04-16 17:19:59 +00003099inline void swapStruct(struct objc_module_t &module) {
3100 sys::swapByteOrder(module.version);
3101 sys::swapByteOrder(module.size);
3102 sys::swapByteOrder(module.name);
3103 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003104}
Kevin Enderby846c0002015-04-16 17:19:59 +00003105
3106inline void swapStruct(struct objc_symtab_t &symtab) {
3107 sys::swapByteOrder(symtab.sel_ref_cnt);
3108 sys::swapByteOrder(symtab.refs);
3109 sys::swapByteOrder(symtab.cls_def_cnt);
3110 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003111}
Kevin Enderby846c0002015-04-16 17:19:59 +00003112
3113inline void swapStruct(struct objc_class_t &objc_class) {
3114 sys::swapByteOrder(objc_class.isa);
3115 sys::swapByteOrder(objc_class.super_class);
3116 sys::swapByteOrder(objc_class.name);
3117 sys::swapByteOrder(objc_class.version);
3118 sys::swapByteOrder(objc_class.info);
3119 sys::swapByteOrder(objc_class.instance_size);
3120 sys::swapByteOrder(objc_class.ivars);
3121 sys::swapByteOrder(objc_class.methodLists);
3122 sys::swapByteOrder(objc_class.cache);
3123 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003124}
Kevin Enderby846c0002015-04-16 17:19:59 +00003125
3126inline void swapStruct(struct objc_category_t &objc_category) {
3127 sys::swapByteOrder(objc_category.category_name);
3128 sys::swapByteOrder(objc_category.class_name);
3129 sys::swapByteOrder(objc_category.instance_methods);
3130 sys::swapByteOrder(objc_category.class_methods);
3131 sys::swapByteOrder(objc_category.protocols);
3132}
3133
3134inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3135 sys::swapByteOrder(objc_ivar_list.ivar_count);
3136}
3137
3138inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3139 sys::swapByteOrder(objc_ivar.ivar_name);
3140 sys::swapByteOrder(objc_ivar.ivar_type);
3141 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003142}
Kevin Enderby846c0002015-04-16 17:19:59 +00003143
3144inline void swapStruct(struct objc_method_list_t &method_list) {
3145 sys::swapByteOrder(method_list.obsolete);
3146 sys::swapByteOrder(method_list.method_count);
3147}
3148
3149inline void swapStruct(struct objc_method_t &method) {
3150 sys::swapByteOrder(method.method_name);
3151 sys::swapByteOrder(method.method_types);
3152 sys::swapByteOrder(method.method_imp);
3153}
3154
3155inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3156 sys::swapByteOrder(protocol_list.next);
3157 sys::swapByteOrder(protocol_list.count);
3158}
3159
3160inline void swapStruct(struct objc_protocol_t &protocol) {
3161 sys::swapByteOrder(protocol.isa);
3162 sys::swapByteOrder(protocol.protocol_name);
3163 sys::swapByteOrder(protocol.protocol_list);
3164 sys::swapByteOrder(protocol.instance_methods);
3165 sys::swapByteOrder(protocol.class_methods);
3166}
3167
3168inline void swapStruct(struct objc_method_description_list_t &mdl) {
3169 sys::swapByteOrder(mdl.count);
3170}
3171
3172inline void swapStruct(struct objc_method_description_t &md) {
3173 sys::swapByteOrder(md.name);
3174 sys::swapByteOrder(md.types);
3175}
3176
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003177static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3178 struct DisassembleInfo *info);
3179
3180// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3181// to an Objective-C class and returns the class name. It is also passed the
3182// address of the pointer, so when the pointer is zero as it can be in an .o
3183// file, that is used to look for an external relocation entry with a symbol
3184// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003185static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3186 uint64_t ReferenceValue,
3187 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003188 const char *r;
3189 uint32_t offset, left;
3190 SectionRef S;
3191
3192 // The pointer_value can be 0 in an object file and have a relocation
3193 // entry for the class symbol at the ReferenceValue (the address of the
3194 // pointer).
3195 if (pointer_value == 0) {
3196 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3197 if (r == nullptr || left < sizeof(uint64_t))
3198 return nullptr;
3199 uint64_t n_value;
3200 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3201 if (symbol_name == nullptr)
3202 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003203 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003204 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3205 return class_name + 2;
3206 else
3207 return nullptr;
3208 }
3209
3210 // The case were the pointer_value is non-zero and points to a class defined
3211 // in this Mach-O file.
3212 r = get_pointer_64(pointer_value, offset, left, S, info);
3213 if (r == nullptr || left < sizeof(struct class64_t))
3214 return nullptr;
3215 struct class64_t c;
3216 memcpy(&c, r, sizeof(struct class64_t));
3217 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3218 swapStruct(c);
3219 if (c.data == 0)
3220 return nullptr;
3221 r = get_pointer_64(c.data, offset, left, S, info);
3222 if (r == nullptr || left < sizeof(struct class_ro64_t))
3223 return nullptr;
3224 struct class_ro64_t cro;
3225 memcpy(&cro, r, sizeof(struct class_ro64_t));
3226 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3227 swapStruct(cro);
3228 if (cro.name == 0)
3229 return nullptr;
3230 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3231 return name;
3232}
3233
3234// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3235// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003236static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3237 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003238 const char *r, *name;
3239 uint32_t offset, left;
3240 SectionRef S;
3241 struct cfstring64_t cfs;
3242 uint64_t cfs_characters;
3243
3244 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3245 if (r == nullptr || left < sizeof(struct cfstring64_t))
3246 return nullptr;
3247 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3248 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3249 swapStruct(cfs);
3250 if (cfs.characters == 0) {
3251 uint64_t n_value;
3252 const char *symbol_name = get_symbol_64(
3253 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3254 if (symbol_name == nullptr)
3255 return nullptr;
3256 cfs_characters = n_value;
3257 } else
3258 cfs_characters = cfs.characters;
3259 name = get_pointer_64(cfs_characters, offset, left, S, info);
3260
3261 return name;
3262}
3263
3264// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3265// of a pointer to an Objective-C selector reference when the pointer value is
3266// zero as in a .o file and is likely to have a external relocation entry with
3267// who's symbol's n_value is the real pointer to the selector name. If that is
3268// the case the real pointer to the selector name is returned else 0 is
3269// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003270static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3271 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003272 uint32_t offset, left;
3273 SectionRef S;
3274
3275 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3276 if (r == nullptr || left < sizeof(uint64_t))
3277 return 0;
3278 uint64_t n_value;
3279 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3280 if (symbol_name == nullptr)
3281 return 0;
3282 return n_value;
3283}
3284
Kevin Enderby0fc11822015-04-01 20:57:01 +00003285static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3286 const char *sectname) {
3287 for (const SectionRef &Section : O->sections()) {
3288 StringRef SectName;
3289 Section.getName(SectName);
3290 DataRefImpl Ref = Section.getRawDataRefImpl();
3291 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3292 if (SegName == segname && SectName == sectname)
3293 return Section;
3294 }
3295 return SectionRef();
3296}
3297
3298static void
3299walk_pointer_list_64(const char *listname, const SectionRef S,
3300 MachOObjectFile *O, struct DisassembleInfo *info,
3301 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3302 if (S == SectionRef())
3303 return;
3304
3305 StringRef SectName;
3306 S.getName(SectName);
3307 DataRefImpl Ref = S.getRawDataRefImpl();
3308 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3309 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3310
3311 StringRef BytesStr;
3312 S.getContents(BytesStr);
3313 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3314
3315 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3316 uint32_t left = S.getSize() - i;
3317 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3318 uint64_t p = 0;
3319 memcpy(&p, Contents + i, size);
3320 if (i + sizeof(uint64_t) > S.getSize())
3321 outs() << listname << " list pointer extends past end of (" << SegName
3322 << "," << SectName << ") section\n";
3323 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3324
3325 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3326 sys::swapByteOrder(p);
3327
3328 uint64_t n_value = 0;
3329 const char *name = get_symbol_64(i, S, info, n_value, p);
3330 if (name == nullptr)
3331 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3332
3333 if (n_value != 0) {
3334 outs() << format("0x%" PRIx64, n_value);
3335 if (p != 0)
3336 outs() << " + " << format("0x%" PRIx64, p);
3337 } else
3338 outs() << format("0x%" PRIx64, p);
3339 if (name != nullptr)
3340 outs() << " " << name;
3341 outs() << "\n";
3342
3343 p += n_value;
3344 if (func)
3345 func(p, info);
3346 }
3347}
3348
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003349static void
3350walk_pointer_list_32(const char *listname, const SectionRef S,
3351 MachOObjectFile *O, struct DisassembleInfo *info,
3352 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3353 if (S == SectionRef())
3354 return;
3355
3356 StringRef SectName;
3357 S.getName(SectName);
3358 DataRefImpl Ref = S.getRawDataRefImpl();
3359 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3360 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3361
3362 StringRef BytesStr;
3363 S.getContents(BytesStr);
3364 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3365
3366 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3367 uint32_t left = S.getSize() - i;
3368 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3369 uint32_t p = 0;
3370 memcpy(&p, Contents + i, size);
3371 if (i + sizeof(uint32_t) > S.getSize())
3372 outs() << listname << " list pointer extends past end of (" << SegName
3373 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003374 uint32_t Address = S.getAddress() + i;
3375 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003376
3377 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3378 sys::swapByteOrder(p);
3379 outs() << format("0x%" PRIx32, p);
3380
3381 const char *name = get_symbol_32(i, S, info, p);
3382 if (name != nullptr)
3383 outs() << " " << name;
3384 outs() << "\n";
3385
3386 if (func)
3387 func(p, info);
3388 }
3389}
3390
3391static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003392 if (layout_map == nullptr)
3393 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003394 outs() << " layout map: ";
3395 do {
3396 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3397 left--;
3398 layout_map++;
3399 } while (*layout_map != '\0' && left != 0);
3400 outs() << "\n";
3401}
3402
Kevin Enderby0fc11822015-04-01 20:57:01 +00003403static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3404 uint32_t offset, left;
3405 SectionRef S;
3406 const char *layout_map;
3407
3408 if (p == 0)
3409 return;
3410 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003411 print_layout_map(layout_map, left);
3412}
3413
3414static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3415 uint32_t offset, left;
3416 SectionRef S;
3417 const char *layout_map;
3418
3419 if (p == 0)
3420 return;
3421 layout_map = get_pointer_32(p, offset, left, S, info);
3422 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003423}
3424
3425static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3426 const char *indent) {
3427 struct method_list64_t ml;
3428 struct method64_t m;
3429 const char *r;
3430 uint32_t offset, xoffset, left, i;
3431 SectionRef S, xS;
3432 const char *name, *sym_name;
3433 uint64_t n_value;
3434
3435 r = get_pointer_64(p, offset, left, S, info);
3436 if (r == nullptr)
3437 return;
3438 memset(&ml, '\0', sizeof(struct method_list64_t));
3439 if (left < sizeof(struct method_list64_t)) {
3440 memcpy(&ml, r, left);
3441 outs() << " (method_list_t entends past the end of the section)\n";
3442 } else
3443 memcpy(&ml, r, sizeof(struct method_list64_t));
3444 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3445 swapStruct(ml);
3446 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3447 outs() << indent << "\t\t count " << ml.count << "\n";
3448
3449 p += sizeof(struct method_list64_t);
3450 offset += sizeof(struct method_list64_t);
3451 for (i = 0; i < ml.count; i++) {
3452 r = get_pointer_64(p, offset, left, S, info);
3453 if (r == nullptr)
3454 return;
3455 memset(&m, '\0', sizeof(struct method64_t));
3456 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003457 memcpy(&m, r, left);
3458 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003459 } else
3460 memcpy(&m, r, sizeof(struct method64_t));
3461 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3462 swapStruct(m);
3463
3464 outs() << indent << "\t\t name ";
3465 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3466 info, n_value, m.name);
3467 if (n_value != 0) {
3468 if (info->verbose && sym_name != nullptr)
3469 outs() << sym_name;
3470 else
3471 outs() << format("0x%" PRIx64, n_value);
3472 if (m.name != 0)
3473 outs() << " + " << format("0x%" PRIx64, m.name);
3474 } else
3475 outs() << format("0x%" PRIx64, m.name);
3476 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3477 if (name != nullptr)
3478 outs() << format(" %.*s", left, name);
3479 outs() << "\n";
3480
3481 outs() << indent << "\t\t types ";
3482 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3483 info, n_value, m.types);
3484 if (n_value != 0) {
3485 if (info->verbose && sym_name != nullptr)
3486 outs() << sym_name;
3487 else
3488 outs() << format("0x%" PRIx64, n_value);
3489 if (m.types != 0)
3490 outs() << " + " << format("0x%" PRIx64, m.types);
3491 } else
3492 outs() << format("0x%" PRIx64, m.types);
3493 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3494 if (name != nullptr)
3495 outs() << format(" %.*s", left, name);
3496 outs() << "\n";
3497
3498 outs() << indent << "\t\t imp ";
3499 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3500 n_value, m.imp);
3501 if (info->verbose && name == nullptr) {
3502 if (n_value != 0) {
3503 outs() << format("0x%" PRIx64, n_value) << " ";
3504 if (m.imp != 0)
3505 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3506 } else
3507 outs() << format("0x%" PRIx64, m.imp) << " ";
3508 }
3509 if (name != nullptr)
3510 outs() << name;
3511 outs() << "\n";
3512
3513 p += sizeof(struct method64_t);
3514 offset += sizeof(struct method64_t);
3515 }
3516}
3517
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003518static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3519 const char *indent) {
3520 struct method_list32_t ml;
3521 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003522 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003523 uint32_t offset, xoffset, left, i;
3524 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003525
3526 r = get_pointer_32(p, offset, left, S, info);
3527 if (r == nullptr)
3528 return;
3529 memset(&ml, '\0', sizeof(struct method_list32_t));
3530 if (left < sizeof(struct method_list32_t)) {
3531 memcpy(&ml, r, left);
3532 outs() << " (method_list_t entends past the end of the section)\n";
3533 } else
3534 memcpy(&ml, r, sizeof(struct method_list32_t));
3535 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3536 swapStruct(ml);
3537 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3538 outs() << indent << "\t\t count " << ml.count << "\n";
3539
3540 p += sizeof(struct method_list32_t);
3541 offset += sizeof(struct method_list32_t);
3542 for (i = 0; i < ml.count; i++) {
3543 r = get_pointer_32(p, offset, left, S, info);
3544 if (r == nullptr)
3545 return;
3546 memset(&m, '\0', sizeof(struct method32_t));
3547 if (left < sizeof(struct method32_t)) {
3548 memcpy(&ml, r, left);
3549 outs() << indent << " (method_t entends past the end of the section)\n";
3550 } else
3551 memcpy(&m, r, sizeof(struct method32_t));
3552 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3553 swapStruct(m);
3554
3555 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3556 name = get_pointer_32(m.name, xoffset, left, xS, info);
3557 if (name != nullptr)
3558 outs() << format(" %.*s", left, name);
3559 outs() << "\n";
3560
3561 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3562 name = get_pointer_32(m.types, xoffset, left, xS, info);
3563 if (name != nullptr)
3564 outs() << format(" %.*s", left, name);
3565 outs() << "\n";
3566
3567 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3568 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3569 m.imp);
3570 if (name != nullptr)
3571 outs() << " " << name;
3572 outs() << "\n";
3573
3574 p += sizeof(struct method32_t);
3575 offset += sizeof(struct method32_t);
3576 }
3577}
3578
Kevin Enderby846c0002015-04-16 17:19:59 +00003579static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3580 uint32_t offset, left, xleft;
3581 SectionRef S;
3582 struct objc_method_list_t method_list;
3583 struct objc_method_t method;
3584 const char *r, *methods, *name, *SymbolName;
3585 int32_t i;
3586
3587 r = get_pointer_32(p, offset, left, S, info, true);
3588 if (r == nullptr)
3589 return true;
3590
3591 outs() << "\n";
3592 if (left > sizeof(struct objc_method_list_t)) {
3593 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3594 } else {
3595 outs() << "\t\t objc_method_list extends past end of the section\n";
3596 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3597 memcpy(&method_list, r, left);
3598 }
3599 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3600 swapStruct(method_list);
3601
3602 outs() << "\t\t obsolete "
3603 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3604 outs() << "\t\t method_count " << method_list.method_count << "\n";
3605
3606 methods = r + sizeof(struct objc_method_list_t);
3607 for (i = 0; i < method_list.method_count; i++) {
3608 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3609 outs() << "\t\t remaining method's extend past the of the section\n";
3610 break;
3611 }
3612 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3613 sizeof(struct objc_method_t));
3614 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3615 swapStruct(method);
3616
3617 outs() << "\t\t method_name "
3618 << format("0x%08" PRIx32, method.method_name);
3619 if (info->verbose) {
3620 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3621 if (name != nullptr)
3622 outs() << format(" %.*s", xleft, name);
3623 else
3624 outs() << " (not in an __OBJC section)";
3625 }
3626 outs() << "\n";
3627
3628 outs() << "\t\t method_types "
3629 << format("0x%08" PRIx32, method.method_types);
3630 if (info->verbose) {
3631 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3632 if (name != nullptr)
3633 outs() << format(" %.*s", xleft, name);
3634 else
3635 outs() << " (not in an __OBJC section)";
3636 }
3637 outs() << "\n";
3638
3639 outs() << "\t\t method_imp "
3640 << format("0x%08" PRIx32, method.method_imp) << " ";
3641 if (info->verbose) {
3642 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3643 if (SymbolName != nullptr)
3644 outs() << SymbolName;
3645 }
3646 outs() << "\n";
3647 }
3648 return false;
3649}
3650
Kevin Enderby0fc11822015-04-01 20:57:01 +00003651static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3652 struct protocol_list64_t pl;
3653 uint64_t q, n_value;
3654 struct protocol64_t pc;
3655 const char *r;
3656 uint32_t offset, xoffset, left, i;
3657 SectionRef S, xS;
3658 const char *name, *sym_name;
3659
3660 r = get_pointer_64(p, offset, left, S, info);
3661 if (r == nullptr)
3662 return;
3663 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3664 if (left < sizeof(struct protocol_list64_t)) {
3665 memcpy(&pl, r, left);
3666 outs() << " (protocol_list_t entends past the end of the section)\n";
3667 } else
3668 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3669 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3670 swapStruct(pl);
3671 outs() << " count " << pl.count << "\n";
3672
3673 p += sizeof(struct protocol_list64_t);
3674 offset += sizeof(struct protocol_list64_t);
3675 for (i = 0; i < pl.count; i++) {
3676 r = get_pointer_64(p, offset, left, S, info);
3677 if (r == nullptr)
3678 return;
3679 q = 0;
3680 if (left < sizeof(uint64_t)) {
3681 memcpy(&q, r, left);
3682 outs() << " (protocol_t * entends past the end of the section)\n";
3683 } else
3684 memcpy(&q, r, sizeof(uint64_t));
3685 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3686 sys::swapByteOrder(q);
3687
3688 outs() << "\t\t list[" << i << "] ";
3689 sym_name = get_symbol_64(offset, S, info, n_value, q);
3690 if (n_value != 0) {
3691 if (info->verbose && sym_name != nullptr)
3692 outs() << sym_name;
3693 else
3694 outs() << format("0x%" PRIx64, n_value);
3695 if (q != 0)
3696 outs() << " + " << format("0x%" PRIx64, q);
3697 } else
3698 outs() << format("0x%" PRIx64, q);
3699 outs() << " (struct protocol_t *)\n";
3700
3701 r = get_pointer_64(q + n_value, offset, left, S, info);
3702 if (r == nullptr)
3703 return;
3704 memset(&pc, '\0', sizeof(struct protocol64_t));
3705 if (left < sizeof(struct protocol64_t)) {
3706 memcpy(&pc, r, left);
3707 outs() << " (protocol_t entends past the end of the section)\n";
3708 } else
3709 memcpy(&pc, r, sizeof(struct protocol64_t));
3710 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3711 swapStruct(pc);
3712
3713 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3714
3715 outs() << "\t\t\t name ";
3716 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3717 info, n_value, pc.name);
3718 if (n_value != 0) {
3719 if (info->verbose && sym_name != nullptr)
3720 outs() << sym_name;
3721 else
3722 outs() << format("0x%" PRIx64, n_value);
3723 if (pc.name != 0)
3724 outs() << " + " << format("0x%" PRIx64, pc.name);
3725 } else
3726 outs() << format("0x%" PRIx64, pc.name);
3727 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3728 if (name != nullptr)
3729 outs() << format(" %.*s", left, name);
3730 outs() << "\n";
3731
3732 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3733
3734 outs() << "\t\t instanceMethods ";
3735 sym_name =
3736 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3737 S, info, n_value, pc.instanceMethods);
3738 if (n_value != 0) {
3739 if (info->verbose && sym_name != nullptr)
3740 outs() << sym_name;
3741 else
3742 outs() << format("0x%" PRIx64, n_value);
3743 if (pc.instanceMethods != 0)
3744 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3745 } else
3746 outs() << format("0x%" PRIx64, pc.instanceMethods);
3747 outs() << " (struct method_list_t *)\n";
3748 if (pc.instanceMethods + n_value != 0)
3749 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3750
3751 outs() << "\t\t classMethods ";
3752 sym_name =
3753 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3754 info, n_value, pc.classMethods);
3755 if (n_value != 0) {
3756 if (info->verbose && sym_name != nullptr)
3757 outs() << sym_name;
3758 else
3759 outs() << format("0x%" PRIx64, n_value);
3760 if (pc.classMethods != 0)
3761 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3762 } else
3763 outs() << format("0x%" PRIx64, pc.classMethods);
3764 outs() << " (struct method_list_t *)\n";
3765 if (pc.classMethods + n_value != 0)
3766 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3767
3768 outs() << "\t optionalInstanceMethods "
3769 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3770 outs() << "\t optionalClassMethods "
3771 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3772 outs() << "\t instanceProperties "
3773 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3774
3775 p += sizeof(uint64_t);
3776 offset += sizeof(uint64_t);
3777 }
3778}
3779
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003780static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3781 struct protocol_list32_t pl;
3782 uint32_t q;
3783 struct protocol32_t pc;
3784 const char *r;
3785 uint32_t offset, xoffset, left, i;
3786 SectionRef S, xS;
3787 const char *name;
3788
3789 r = get_pointer_32(p, offset, left, S, info);
3790 if (r == nullptr)
3791 return;
3792 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3793 if (left < sizeof(struct protocol_list32_t)) {
3794 memcpy(&pl, r, left);
3795 outs() << " (protocol_list_t entends past the end of the section)\n";
3796 } else
3797 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3798 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3799 swapStruct(pl);
3800 outs() << " count " << pl.count << "\n";
3801
3802 p += sizeof(struct protocol_list32_t);
3803 offset += sizeof(struct protocol_list32_t);
3804 for (i = 0; i < pl.count; i++) {
3805 r = get_pointer_32(p, offset, left, S, info);
3806 if (r == nullptr)
3807 return;
3808 q = 0;
3809 if (left < sizeof(uint32_t)) {
3810 memcpy(&q, r, left);
3811 outs() << " (protocol_t * entends past the end of the section)\n";
3812 } else
3813 memcpy(&q, r, sizeof(uint32_t));
3814 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3815 sys::swapByteOrder(q);
3816 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3817 << " (struct protocol_t *)\n";
3818 r = get_pointer_32(q, offset, left, S, info);
3819 if (r == nullptr)
3820 return;
3821 memset(&pc, '\0', sizeof(struct protocol32_t));
3822 if (left < sizeof(struct protocol32_t)) {
3823 memcpy(&pc, r, left);
3824 outs() << " (protocol_t entends past the end of the section)\n";
3825 } else
3826 memcpy(&pc, r, sizeof(struct protocol32_t));
3827 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3828 swapStruct(pc);
3829 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3830 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3831 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3832 if (name != nullptr)
3833 outs() << format(" %.*s", left, name);
3834 outs() << "\n";
3835 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3836 outs() << "\t\t instanceMethods "
3837 << format("0x%" PRIx32, pc.instanceMethods)
3838 << " (struct method_list_t *)\n";
3839 if (pc.instanceMethods != 0)
3840 print_method_list32_t(pc.instanceMethods, info, "\t");
3841 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3842 << " (struct method_list_t *)\n";
3843 if (pc.classMethods != 0)
3844 print_method_list32_t(pc.classMethods, info, "\t");
3845 outs() << "\t optionalInstanceMethods "
3846 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3847 outs() << "\t optionalClassMethods "
3848 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3849 outs() << "\t instanceProperties "
3850 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3851 p += sizeof(uint32_t);
3852 offset += sizeof(uint32_t);
3853 }
3854}
3855
Kevin Enderby846c0002015-04-16 17:19:59 +00003856static void print_indent(uint32_t indent) {
3857 for (uint32_t i = 0; i < indent;) {
3858 if (indent - i >= 8) {
3859 outs() << "\t";
3860 i += 8;
3861 } else {
3862 for (uint32_t j = i; j < indent; j++)
3863 outs() << " ";
3864 return;
3865 }
3866 }
3867}
3868
3869static bool print_method_description_list(uint32_t p, uint32_t indent,
3870 struct DisassembleInfo *info) {
3871 uint32_t offset, left, xleft;
3872 SectionRef S;
3873 struct objc_method_description_list_t mdl;
3874 struct objc_method_description_t md;
3875 const char *r, *list, *name;
3876 int32_t i;
3877
3878 r = get_pointer_32(p, offset, left, S, info, true);
3879 if (r == nullptr)
3880 return true;
3881
3882 outs() << "\n";
3883 if (left > sizeof(struct objc_method_description_list_t)) {
3884 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3885 } else {
3886 print_indent(indent);
3887 outs() << " objc_method_description_list extends past end of the section\n";
3888 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3889 memcpy(&mdl, r, left);
3890 }
3891 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3892 swapStruct(mdl);
3893
3894 print_indent(indent);
3895 outs() << " count " << mdl.count << "\n";
3896
3897 list = r + sizeof(struct objc_method_description_list_t);
3898 for (i = 0; i < mdl.count; i++) {
3899 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3900 print_indent(indent);
3901 outs() << " remaining list entries extend past the of the section\n";
3902 break;
3903 }
3904 print_indent(indent);
3905 outs() << " list[" << i << "]\n";
3906 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3907 sizeof(struct objc_method_description_t));
3908 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3909 swapStruct(md);
3910
3911 print_indent(indent);
3912 outs() << " name " << format("0x%08" PRIx32, md.name);
3913 if (info->verbose) {
3914 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3915 if (name != nullptr)
3916 outs() << format(" %.*s", xleft, name);
3917 else
3918 outs() << " (not in an __OBJC section)";
3919 }
3920 outs() << "\n";
3921
3922 print_indent(indent);
3923 outs() << " types " << format("0x%08" PRIx32, md.types);
3924 if (info->verbose) {
3925 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3926 if (name != nullptr)
3927 outs() << format(" %.*s", xleft, name);
3928 else
3929 outs() << " (not in an __OBJC section)";
3930 }
3931 outs() << "\n";
3932 }
3933 return false;
3934}
3935
3936static bool print_protocol_list(uint32_t p, uint32_t indent,
3937 struct DisassembleInfo *info);
3938
3939static bool print_protocol(uint32_t p, uint32_t indent,
3940 struct DisassembleInfo *info) {
3941 uint32_t offset, left;
3942 SectionRef S;
3943 struct objc_protocol_t protocol;
3944 const char *r, *name;
3945
3946 r = get_pointer_32(p, offset, left, S, info, true);
3947 if (r == nullptr)
3948 return true;
3949
3950 outs() << "\n";
3951 if (left >= sizeof(struct objc_protocol_t)) {
3952 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3953 } else {
3954 print_indent(indent);
3955 outs() << " Protocol extends past end of the section\n";
3956 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3957 memcpy(&protocol, r, left);
3958 }
3959 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3960 swapStruct(protocol);
3961
3962 print_indent(indent);
3963 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3964 << "\n";
3965
3966 print_indent(indent);
3967 outs() << " protocol_name "
3968 << format("0x%08" PRIx32, protocol.protocol_name);
3969 if (info->verbose) {
3970 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3971 if (name != nullptr)
3972 outs() << format(" %.*s", left, name);
3973 else
3974 outs() << " (not in an __OBJC section)";
3975 }
3976 outs() << "\n";
3977
3978 print_indent(indent);
3979 outs() << " protocol_list "
3980 << format("0x%08" PRIx32, protocol.protocol_list);
3981 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3982 outs() << " (not in an __OBJC section)\n";
3983
3984 print_indent(indent);
3985 outs() << " instance_methods "
3986 << format("0x%08" PRIx32, protocol.instance_methods);
3987 if (print_method_description_list(protocol.instance_methods, indent, info))
3988 outs() << " (not in an __OBJC section)\n";
3989
3990 print_indent(indent);
3991 outs() << " class_methods "
3992 << format("0x%08" PRIx32, protocol.class_methods);
3993 if (print_method_description_list(protocol.class_methods, indent, info))
3994 outs() << " (not in an __OBJC section)\n";
3995
3996 return false;
3997}
3998
3999static bool print_protocol_list(uint32_t p, uint32_t indent,
4000 struct DisassembleInfo *info) {
4001 uint32_t offset, left, l;
4002 SectionRef S;
4003 struct objc_protocol_list_t protocol_list;
4004 const char *r, *list;
4005 int32_t i;
4006
4007 r = get_pointer_32(p, offset, left, S, info, true);
4008 if (r == nullptr)
4009 return true;
4010
4011 outs() << "\n";
4012 if (left > sizeof(struct objc_protocol_list_t)) {
4013 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4014 } else {
4015 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4016 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4017 memcpy(&protocol_list, r, left);
4018 }
4019 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4020 swapStruct(protocol_list);
4021
4022 print_indent(indent);
4023 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4024 << "\n";
4025 print_indent(indent);
4026 outs() << " count " << protocol_list.count << "\n";
4027
4028 list = r + sizeof(struct objc_protocol_list_t);
4029 for (i = 0; i < protocol_list.count; i++) {
4030 if ((i + 1) * sizeof(uint32_t) > left) {
4031 outs() << "\t\t remaining list entries extend past the of the section\n";
4032 break;
4033 }
4034 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4035 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4036 sys::swapByteOrder(l);
4037
4038 print_indent(indent);
4039 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4040 if (print_protocol(l, indent, info))
4041 outs() << "(not in an __OBJC section)\n";
4042 }
4043 return false;
4044}
4045
Kevin Enderby0fc11822015-04-01 20:57:01 +00004046static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4047 struct ivar_list64_t il;
4048 struct ivar64_t i;
4049 const char *r;
4050 uint32_t offset, xoffset, left, j;
4051 SectionRef S, xS;
4052 const char *name, *sym_name, *ivar_offset_p;
4053 uint64_t ivar_offset, n_value;
4054
4055 r = get_pointer_64(p, offset, left, S, info);
4056 if (r == nullptr)
4057 return;
4058 memset(&il, '\0', sizeof(struct ivar_list64_t));
4059 if (left < sizeof(struct ivar_list64_t)) {
4060 memcpy(&il, r, left);
4061 outs() << " (ivar_list_t entends past the end of the section)\n";
4062 } else
4063 memcpy(&il, r, sizeof(struct ivar_list64_t));
4064 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4065 swapStruct(il);
4066 outs() << " entsize " << il.entsize << "\n";
4067 outs() << " count " << il.count << "\n";
4068
4069 p += sizeof(struct ivar_list64_t);
4070 offset += sizeof(struct ivar_list64_t);
4071 for (j = 0; j < il.count; j++) {
4072 r = get_pointer_64(p, offset, left, S, info);
4073 if (r == nullptr)
4074 return;
4075 memset(&i, '\0', sizeof(struct ivar64_t));
4076 if (left < sizeof(struct ivar64_t)) {
4077 memcpy(&i, r, left);
4078 outs() << " (ivar_t entends past the end of the section)\n";
4079 } else
4080 memcpy(&i, r, sizeof(struct ivar64_t));
4081 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4082 swapStruct(i);
4083
4084 outs() << "\t\t\t offset ";
4085 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4086 info, n_value, i.offset);
4087 if (n_value != 0) {
4088 if (info->verbose && sym_name != nullptr)
4089 outs() << sym_name;
4090 else
4091 outs() << format("0x%" PRIx64, n_value);
4092 if (i.offset != 0)
4093 outs() << " + " << format("0x%" PRIx64, i.offset);
4094 } else
4095 outs() << format("0x%" PRIx64, i.offset);
4096 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4097 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4098 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4099 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4100 sys::swapByteOrder(ivar_offset);
4101 outs() << " " << ivar_offset << "\n";
4102 } else
4103 outs() << "\n";
4104
4105 outs() << "\t\t\t name ";
4106 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4107 n_value, i.name);
4108 if (n_value != 0) {
4109 if (info->verbose && sym_name != nullptr)
4110 outs() << sym_name;
4111 else
4112 outs() << format("0x%" PRIx64, n_value);
4113 if (i.name != 0)
4114 outs() << " + " << format("0x%" PRIx64, i.name);
4115 } else
4116 outs() << format("0x%" PRIx64, i.name);
4117 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4118 if (name != nullptr)
4119 outs() << format(" %.*s", left, name);
4120 outs() << "\n";
4121
4122 outs() << "\t\t\t type ";
4123 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4124 n_value, i.name);
4125 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4126 if (n_value != 0) {
4127 if (info->verbose && sym_name != nullptr)
4128 outs() << sym_name;
4129 else
4130 outs() << format("0x%" PRIx64, n_value);
4131 if (i.type != 0)
4132 outs() << " + " << format("0x%" PRIx64, i.type);
4133 } else
4134 outs() << format("0x%" PRIx64, i.type);
4135 if (name != nullptr)
4136 outs() << format(" %.*s", left, name);
4137 outs() << "\n";
4138
4139 outs() << "\t\t\talignment " << i.alignment << "\n";
4140 outs() << "\t\t\t size " << i.size << "\n";
4141
4142 p += sizeof(struct ivar64_t);
4143 offset += sizeof(struct ivar64_t);
4144 }
4145}
4146
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004147static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4148 struct ivar_list32_t il;
4149 struct ivar32_t i;
4150 const char *r;
4151 uint32_t offset, xoffset, left, j;
4152 SectionRef S, xS;
4153 const char *name, *ivar_offset_p;
4154 uint32_t ivar_offset;
4155
4156 r = get_pointer_32(p, offset, left, S, info);
4157 if (r == nullptr)
4158 return;
4159 memset(&il, '\0', sizeof(struct ivar_list32_t));
4160 if (left < sizeof(struct ivar_list32_t)) {
4161 memcpy(&il, r, left);
4162 outs() << " (ivar_list_t entends past the end of the section)\n";
4163 } else
4164 memcpy(&il, r, sizeof(struct ivar_list32_t));
4165 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4166 swapStruct(il);
4167 outs() << " entsize " << il.entsize << "\n";
4168 outs() << " count " << il.count << "\n";
4169
4170 p += sizeof(struct ivar_list32_t);
4171 offset += sizeof(struct ivar_list32_t);
4172 for (j = 0; j < il.count; j++) {
4173 r = get_pointer_32(p, offset, left, S, info);
4174 if (r == nullptr)
4175 return;
4176 memset(&i, '\0', sizeof(struct ivar32_t));
4177 if (left < sizeof(struct ivar32_t)) {
4178 memcpy(&i, r, left);
4179 outs() << " (ivar_t entends past the end of the section)\n";
4180 } else
4181 memcpy(&i, r, sizeof(struct ivar32_t));
4182 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4183 swapStruct(i);
4184
4185 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4186 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4187 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4188 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4189 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4190 sys::swapByteOrder(ivar_offset);
4191 outs() << " " << ivar_offset << "\n";
4192 } else
4193 outs() << "\n";
4194
4195 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4196 name = get_pointer_32(i.name, xoffset, left, xS, info);
4197 if (name != nullptr)
4198 outs() << format(" %.*s", left, name);
4199 outs() << "\n";
4200
4201 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4202 name = get_pointer_32(i.type, xoffset, left, xS, info);
4203 if (name != nullptr)
4204 outs() << format(" %.*s", left, name);
4205 outs() << "\n";
4206
4207 outs() << "\t\t\talignment " << i.alignment << "\n";
4208 outs() << "\t\t\t size " << i.size << "\n";
4209
4210 p += sizeof(struct ivar32_t);
4211 offset += sizeof(struct ivar32_t);
4212 }
4213}
4214
Kevin Enderby0fc11822015-04-01 20:57:01 +00004215static void print_objc_property_list64(uint64_t p,
4216 struct DisassembleInfo *info) {
4217 struct objc_property_list64 opl;
4218 struct objc_property64 op;
4219 const char *r;
4220 uint32_t offset, xoffset, left, j;
4221 SectionRef S, xS;
4222 const char *name, *sym_name;
4223 uint64_t n_value;
4224
4225 r = get_pointer_64(p, offset, left, S, info);
4226 if (r == nullptr)
4227 return;
4228 memset(&opl, '\0', sizeof(struct objc_property_list64));
4229 if (left < sizeof(struct objc_property_list64)) {
4230 memcpy(&opl, r, left);
4231 outs() << " (objc_property_list entends past the end of the section)\n";
4232 } else
4233 memcpy(&opl, r, sizeof(struct objc_property_list64));
4234 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4235 swapStruct(opl);
4236 outs() << " entsize " << opl.entsize << "\n";
4237 outs() << " count " << opl.count << "\n";
4238
4239 p += sizeof(struct objc_property_list64);
4240 offset += sizeof(struct objc_property_list64);
4241 for (j = 0; j < opl.count; j++) {
4242 r = get_pointer_64(p, offset, left, S, info);
4243 if (r == nullptr)
4244 return;
4245 memset(&op, '\0', sizeof(struct objc_property64));
4246 if (left < sizeof(struct objc_property64)) {
4247 memcpy(&op, r, left);
4248 outs() << " (objc_property entends past the end of the section)\n";
4249 } else
4250 memcpy(&op, r, sizeof(struct objc_property64));
4251 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4252 swapStruct(op);
4253
4254 outs() << "\t\t\t name ";
4255 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4256 info, n_value, op.name);
4257 if (n_value != 0) {
4258 if (info->verbose && sym_name != nullptr)
4259 outs() << sym_name;
4260 else
4261 outs() << format("0x%" PRIx64, n_value);
4262 if (op.name != 0)
4263 outs() << " + " << format("0x%" PRIx64, op.name);
4264 } else
4265 outs() << format("0x%" PRIx64, op.name);
4266 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4267 if (name != nullptr)
4268 outs() << format(" %.*s", left, name);
4269 outs() << "\n";
4270
4271 outs() << "\t\t\tattributes ";
4272 sym_name =
4273 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4274 info, n_value, op.attributes);
4275 if (n_value != 0) {
4276 if (info->verbose && sym_name != nullptr)
4277 outs() << sym_name;
4278 else
4279 outs() << format("0x%" PRIx64, n_value);
4280 if (op.attributes != 0)
4281 outs() << " + " << format("0x%" PRIx64, op.attributes);
4282 } else
4283 outs() << format("0x%" PRIx64, op.attributes);
4284 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4285 if (name != nullptr)
4286 outs() << format(" %.*s", left, name);
4287 outs() << "\n";
4288
4289 p += sizeof(struct objc_property64);
4290 offset += sizeof(struct objc_property64);
4291 }
4292}
4293
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004294static void print_objc_property_list32(uint32_t p,
4295 struct DisassembleInfo *info) {
4296 struct objc_property_list32 opl;
4297 struct objc_property32 op;
4298 const char *r;
4299 uint32_t offset, xoffset, left, j;
4300 SectionRef S, xS;
4301 const char *name;
4302
4303 r = get_pointer_32(p, offset, left, S, info);
4304 if (r == nullptr)
4305 return;
4306 memset(&opl, '\0', sizeof(struct objc_property_list32));
4307 if (left < sizeof(struct objc_property_list32)) {
4308 memcpy(&opl, r, left);
4309 outs() << " (objc_property_list entends past the end of the section)\n";
4310 } else
4311 memcpy(&opl, r, sizeof(struct objc_property_list32));
4312 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4313 swapStruct(opl);
4314 outs() << " entsize " << opl.entsize << "\n";
4315 outs() << " count " << opl.count << "\n";
4316
4317 p += sizeof(struct objc_property_list32);
4318 offset += sizeof(struct objc_property_list32);
4319 for (j = 0; j < opl.count; j++) {
4320 r = get_pointer_32(p, offset, left, S, info);
4321 if (r == nullptr)
4322 return;
4323 memset(&op, '\0', sizeof(struct objc_property32));
4324 if (left < sizeof(struct objc_property32)) {
4325 memcpy(&op, r, left);
4326 outs() << " (objc_property entends past the end of the section)\n";
4327 } else
4328 memcpy(&op, r, sizeof(struct objc_property32));
4329 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4330 swapStruct(op);
4331
4332 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4333 name = get_pointer_32(op.name, xoffset, left, xS, info);
4334 if (name != nullptr)
4335 outs() << format(" %.*s", left, name);
4336 outs() << "\n";
4337
4338 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4339 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4340 if (name != nullptr)
4341 outs() << format(" %.*s", left, name);
4342 outs() << "\n";
4343
4344 p += sizeof(struct objc_property32);
4345 offset += sizeof(struct objc_property32);
4346 }
4347}
4348
Richard Smith81ff44d2015-10-09 22:09:56 +00004349static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004350 bool &is_meta_class) {
4351 struct class_ro64_t cro;
4352 const char *r;
4353 uint32_t offset, xoffset, left;
4354 SectionRef S, xS;
4355 const char *name, *sym_name;
4356 uint64_t n_value;
4357
4358 r = get_pointer_64(p, offset, left, S, info);
4359 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004360 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004361 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004362 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4363 swapStruct(cro);
4364 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4365 if (cro.flags & RO_META)
4366 outs() << " RO_META";
4367 if (cro.flags & RO_ROOT)
4368 outs() << " RO_ROOT";
4369 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4370 outs() << " RO_HAS_CXX_STRUCTORS";
4371 outs() << "\n";
4372 outs() << " instanceStart " << cro.instanceStart << "\n";
4373 outs() << " instanceSize " << cro.instanceSize << "\n";
4374 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4375 << "\n";
4376 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4377 << "\n";
4378 print_layout_map64(cro.ivarLayout, info);
4379
4380 outs() << " name ";
4381 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4382 info, n_value, cro.name);
4383 if (n_value != 0) {
4384 if (info->verbose && sym_name != nullptr)
4385 outs() << sym_name;
4386 else
4387 outs() << format("0x%" PRIx64, n_value);
4388 if (cro.name != 0)
4389 outs() << " + " << format("0x%" PRIx64, cro.name);
4390 } else
4391 outs() << format("0x%" PRIx64, cro.name);
4392 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4393 if (name != nullptr)
4394 outs() << format(" %.*s", left, name);
4395 outs() << "\n";
4396
4397 outs() << " baseMethods ";
4398 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4399 S, info, n_value, cro.baseMethods);
4400 if (n_value != 0) {
4401 if (info->verbose && sym_name != nullptr)
4402 outs() << sym_name;
4403 else
4404 outs() << format("0x%" PRIx64, n_value);
4405 if (cro.baseMethods != 0)
4406 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4407 } else
4408 outs() << format("0x%" PRIx64, cro.baseMethods);
4409 outs() << " (struct method_list_t *)\n";
4410 if (cro.baseMethods + n_value != 0)
4411 print_method_list64_t(cro.baseMethods + n_value, info, "");
4412
4413 outs() << " baseProtocols ";
4414 sym_name =
4415 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4416 info, n_value, cro.baseProtocols);
4417 if (n_value != 0) {
4418 if (info->verbose && sym_name != nullptr)
4419 outs() << sym_name;
4420 else
4421 outs() << format("0x%" PRIx64, n_value);
4422 if (cro.baseProtocols != 0)
4423 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4424 } else
4425 outs() << format("0x%" PRIx64, cro.baseProtocols);
4426 outs() << "\n";
4427 if (cro.baseProtocols + n_value != 0)
4428 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4429
4430 outs() << " ivars ";
4431 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004432 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004433 if (n_value != 0) {
4434 if (info->verbose && sym_name != nullptr)
4435 outs() << sym_name;
4436 else
4437 outs() << format("0x%" PRIx64, n_value);
4438 if (cro.ivars != 0)
4439 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4440 } else
4441 outs() << format("0x%" PRIx64, cro.ivars);
4442 outs() << "\n";
4443 if (cro.ivars + n_value != 0)
4444 print_ivar_list64_t(cro.ivars + n_value, info);
4445
4446 outs() << " weakIvarLayout ";
4447 sym_name =
4448 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4449 info, n_value, cro.weakIvarLayout);
4450 if (n_value != 0) {
4451 if (info->verbose && sym_name != nullptr)
4452 outs() << sym_name;
4453 else
4454 outs() << format("0x%" PRIx64, n_value);
4455 if (cro.weakIvarLayout != 0)
4456 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4457 } else
4458 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4459 outs() << "\n";
4460 print_layout_map64(cro.weakIvarLayout + n_value, info);
4461
4462 outs() << " baseProperties ";
4463 sym_name =
4464 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4465 info, n_value, cro.baseProperties);
4466 if (n_value != 0) {
4467 if (info->verbose && sym_name != nullptr)
4468 outs() << sym_name;
4469 else
4470 outs() << format("0x%" PRIx64, n_value);
4471 if (cro.baseProperties != 0)
4472 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4473 } else
4474 outs() << format("0x%" PRIx64, cro.baseProperties);
4475 outs() << "\n";
4476 if (cro.baseProperties + n_value != 0)
4477 print_objc_property_list64(cro.baseProperties + n_value, info);
4478
Rafael Espindolab9091322015-10-24 23:19:10 +00004479 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004480 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004481}
4482
Richard Smith81ff44d2015-10-09 22:09:56 +00004483static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004484 bool &is_meta_class) {
4485 struct class_ro32_t cro;
4486 const char *r;
4487 uint32_t offset, xoffset, left;
4488 SectionRef S, xS;
4489 const char *name;
4490
4491 r = get_pointer_32(p, offset, left, S, info);
4492 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004493 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004494 memset(&cro, '\0', sizeof(struct class_ro32_t));
4495 if (left < sizeof(struct class_ro32_t)) {
4496 memcpy(&cro, r, left);
4497 outs() << " (class_ro_t entends past the end of the section)\n";
4498 } else
4499 memcpy(&cro, r, sizeof(struct class_ro32_t));
4500 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4501 swapStruct(cro);
4502 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4503 if (cro.flags & RO_META)
4504 outs() << " RO_META";
4505 if (cro.flags & RO_ROOT)
4506 outs() << " RO_ROOT";
4507 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4508 outs() << " RO_HAS_CXX_STRUCTORS";
4509 outs() << "\n";
4510 outs() << " instanceStart " << cro.instanceStart << "\n";
4511 outs() << " instanceSize " << cro.instanceSize << "\n";
4512 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4513 << "\n";
4514 print_layout_map32(cro.ivarLayout, info);
4515
4516 outs() << " name " << format("0x%" PRIx32, cro.name);
4517 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4518 if (name != nullptr)
4519 outs() << format(" %.*s", left, name);
4520 outs() << "\n";
4521
4522 outs() << " baseMethods "
4523 << format("0x%" PRIx32, cro.baseMethods)
4524 << " (struct method_list_t *)\n";
4525 if (cro.baseMethods != 0)
4526 print_method_list32_t(cro.baseMethods, info, "");
4527
4528 outs() << " baseProtocols "
4529 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4530 if (cro.baseProtocols != 0)
4531 print_protocol_list32_t(cro.baseProtocols, info);
4532 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4533 << "\n";
4534 if (cro.ivars != 0)
4535 print_ivar_list32_t(cro.ivars, info);
4536 outs() << " weakIvarLayout "
4537 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4538 print_layout_map32(cro.weakIvarLayout, info);
4539 outs() << " baseProperties "
4540 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4541 if (cro.baseProperties != 0)
4542 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004543 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004544 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004545}
4546
Kevin Enderby0fc11822015-04-01 20:57:01 +00004547static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4548 struct class64_t c;
4549 const char *r;
4550 uint32_t offset, left;
4551 SectionRef S;
4552 const char *name;
4553 uint64_t isa_n_value, n_value;
4554
4555 r = get_pointer_64(p, offset, left, S, info);
4556 if (r == nullptr || left < sizeof(struct class64_t))
4557 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004558 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004559 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4560 swapStruct(c);
4561
4562 outs() << " isa " << format("0x%" PRIx64, c.isa);
4563 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4564 isa_n_value, c.isa);
4565 if (name != nullptr)
4566 outs() << " " << name;
4567 outs() << "\n";
4568
4569 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4570 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4571 n_value, c.superclass);
4572 if (name != nullptr)
4573 outs() << " " << name;
4574 outs() << "\n";
4575
4576 outs() << " cache " << format("0x%" PRIx64, c.cache);
4577 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4578 n_value, c.cache);
4579 if (name != nullptr)
4580 outs() << " " << name;
4581 outs() << "\n";
4582
4583 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4584 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4585 n_value, c.vtable);
4586 if (name != nullptr)
4587 outs() << " " << name;
4588 outs() << "\n";
4589
4590 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4591 n_value, c.data);
4592 outs() << " data ";
4593 if (n_value != 0) {
4594 if (info->verbose && name != nullptr)
4595 outs() << name;
4596 else
4597 outs() << format("0x%" PRIx64, n_value);
4598 if (c.data != 0)
4599 outs() << " + " << format("0x%" PRIx64, c.data);
4600 } else
4601 outs() << format("0x%" PRIx64, c.data);
4602 outs() << " (struct class_ro_t *)";
4603
4604 // This is a Swift class if some of the low bits of the pointer are set.
4605 if ((c.data + n_value) & 0x7)
4606 outs() << " Swift class";
4607 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004608 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004609 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4610 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004611
Kevin Enderbyaac75382015-10-08 16:56:35 +00004612 if (!is_meta_class &&
4613 c.isa + isa_n_value != p &&
4614 c.isa + isa_n_value != 0 &&
4615 info->depth < 100) {
4616 info->depth++;
4617 outs() << "Meta Class\n";
4618 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004619 }
4620}
4621
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004622static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4623 struct class32_t c;
4624 const char *r;
4625 uint32_t offset, left;
4626 SectionRef S;
4627 const char *name;
4628
4629 r = get_pointer_32(p, offset, left, S, info);
4630 if (r == nullptr)
4631 return;
4632 memset(&c, '\0', sizeof(struct class32_t));
4633 if (left < sizeof(struct class32_t)) {
4634 memcpy(&c, r, left);
4635 outs() << " (class_t entends past the end of the section)\n";
4636 } else
4637 memcpy(&c, r, sizeof(struct class32_t));
4638 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4639 swapStruct(c);
4640
4641 outs() << " isa " << format("0x%" PRIx32, c.isa);
4642 name =
4643 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4644 if (name != nullptr)
4645 outs() << " " << name;
4646 outs() << "\n";
4647
4648 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4649 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4650 c.superclass);
4651 if (name != nullptr)
4652 outs() << " " << name;
4653 outs() << "\n";
4654
4655 outs() << " cache " << format("0x%" PRIx32, c.cache);
4656 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4657 c.cache);
4658 if (name != nullptr)
4659 outs() << " " << name;
4660 outs() << "\n";
4661
4662 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4663 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4664 c.vtable);
4665 if (name != nullptr)
4666 outs() << " " << name;
4667 outs() << "\n";
4668
4669 name =
4670 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4671 outs() << " data " << format("0x%" PRIx32, c.data)
4672 << " (struct class_ro_t *)";
4673
4674 // This is a Swift class if some of the low bits of the pointer are set.
4675 if (c.data & 0x3)
4676 outs() << " Swift class";
4677 outs() << "\n";
4678 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004679 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4680 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004681
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004682 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004683 outs() << "Meta Class\n";
4684 print_class32_t(c.isa, info);
4685 }
4686}
4687
Kevin Enderby846c0002015-04-16 17:19:59 +00004688static void print_objc_class_t(struct objc_class_t *objc_class,
4689 struct DisassembleInfo *info) {
4690 uint32_t offset, left, xleft;
4691 const char *name, *p, *ivar_list;
4692 SectionRef S;
4693 int32_t i;
4694 struct objc_ivar_list_t objc_ivar_list;
4695 struct objc_ivar_t ivar;
4696
4697 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4698 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4699 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4700 if (name != nullptr)
4701 outs() << format(" %.*s", left, name);
4702 else
4703 outs() << " (not in an __OBJC section)";
4704 }
4705 outs() << "\n";
4706
4707 outs() << "\t super_class "
4708 << format("0x%08" PRIx32, objc_class->super_class);
4709 if (info->verbose) {
4710 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4711 if (name != nullptr)
4712 outs() << format(" %.*s", left, name);
4713 else
4714 outs() << " (not in an __OBJC section)";
4715 }
4716 outs() << "\n";
4717
4718 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4719 if (info->verbose) {
4720 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4721 if (name != nullptr)
4722 outs() << format(" %.*s", left, name);
4723 else
4724 outs() << " (not in an __OBJC section)";
4725 }
4726 outs() << "\n";
4727
4728 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4729 << "\n";
4730
4731 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4732 if (info->verbose) {
4733 if (CLS_GETINFO(objc_class, CLS_CLASS))
4734 outs() << " CLS_CLASS";
4735 else if (CLS_GETINFO(objc_class, CLS_META))
4736 outs() << " CLS_META";
4737 }
4738 outs() << "\n";
4739
4740 outs() << "\t instance_size "
4741 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4742
4743 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4744 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4745 if (p != nullptr) {
4746 if (left > sizeof(struct objc_ivar_list_t)) {
4747 outs() << "\n";
4748 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4749 } else {
4750 outs() << " (entends past the end of the section)\n";
4751 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4752 memcpy(&objc_ivar_list, p, left);
4753 }
4754 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4755 swapStruct(objc_ivar_list);
4756 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4757 ivar_list = p + sizeof(struct objc_ivar_list_t);
4758 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4759 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4760 outs() << "\t\t remaining ivar's extend past the of the section\n";
4761 break;
4762 }
4763 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4764 sizeof(struct objc_ivar_t));
4765 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4766 swapStruct(ivar);
4767
4768 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4769 if (info->verbose) {
4770 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4771 if (name != nullptr)
4772 outs() << format(" %.*s", xleft, name);
4773 else
4774 outs() << " (not in an __OBJC section)";
4775 }
4776 outs() << "\n";
4777
4778 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4779 if (info->verbose) {
4780 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4781 if (name != nullptr)
4782 outs() << format(" %.*s", xleft, name);
4783 else
4784 outs() << " (not in an __OBJC section)";
4785 }
4786 outs() << "\n";
4787
4788 outs() << "\t\t ivar_offset "
4789 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4790 }
4791 } else {
4792 outs() << " (not in an __OBJC section)\n";
4793 }
4794
4795 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4796 if (print_method_list(objc_class->methodLists, info))
4797 outs() << " (not in an __OBJC section)\n";
4798
4799 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4800 << "\n";
4801
4802 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4803 if (print_protocol_list(objc_class->protocols, 16, info))
4804 outs() << " (not in an __OBJC section)\n";
4805}
4806
4807static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4808 struct DisassembleInfo *info) {
4809 uint32_t offset, left;
4810 const char *name;
4811 SectionRef S;
4812
4813 outs() << "\t category name "
4814 << format("0x%08" PRIx32, objc_category->category_name);
4815 if (info->verbose) {
4816 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4817 true);
4818 if (name != nullptr)
4819 outs() << format(" %.*s", left, name);
4820 else
4821 outs() << " (not in an __OBJC section)";
4822 }
4823 outs() << "\n";
4824
4825 outs() << "\t\t class name "
4826 << format("0x%08" PRIx32, objc_category->class_name);
4827 if (info->verbose) {
4828 name =
4829 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4830 if (name != nullptr)
4831 outs() << format(" %.*s", left, name);
4832 else
4833 outs() << " (not in an __OBJC section)";
4834 }
4835 outs() << "\n";
4836
4837 outs() << "\t instance methods "
4838 << format("0x%08" PRIx32, objc_category->instance_methods);
4839 if (print_method_list(objc_category->instance_methods, info))
4840 outs() << " (not in an __OBJC section)\n";
4841
4842 outs() << "\t class methods "
4843 << format("0x%08" PRIx32, objc_category->class_methods);
4844 if (print_method_list(objc_category->class_methods, info))
4845 outs() << " (not in an __OBJC section)\n";
4846}
4847
Kevin Enderby0fc11822015-04-01 20:57:01 +00004848static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4849 struct category64_t c;
4850 const char *r;
4851 uint32_t offset, xoffset, left;
4852 SectionRef S, xS;
4853 const char *name, *sym_name;
4854 uint64_t n_value;
4855
4856 r = get_pointer_64(p, offset, left, S, info);
4857 if (r == nullptr)
4858 return;
4859 memset(&c, '\0', sizeof(struct category64_t));
4860 if (left < sizeof(struct category64_t)) {
4861 memcpy(&c, r, left);
4862 outs() << " (category_t entends past the end of the section)\n";
4863 } else
4864 memcpy(&c, r, sizeof(struct category64_t));
4865 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4866 swapStruct(c);
4867
4868 outs() << " name ";
4869 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4870 info, n_value, c.name);
4871 if (n_value != 0) {
4872 if (info->verbose && sym_name != nullptr)
4873 outs() << sym_name;
4874 else
4875 outs() << format("0x%" PRIx64, n_value);
4876 if (c.name != 0)
4877 outs() << " + " << format("0x%" PRIx64, c.name);
4878 } else
4879 outs() << format("0x%" PRIx64, c.name);
4880 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4881 if (name != nullptr)
4882 outs() << format(" %.*s", left, name);
4883 outs() << "\n";
4884
4885 outs() << " cls ";
4886 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4887 n_value, c.cls);
4888 if (n_value != 0) {
4889 if (info->verbose && sym_name != nullptr)
4890 outs() << sym_name;
4891 else
4892 outs() << format("0x%" PRIx64, n_value);
4893 if (c.cls != 0)
4894 outs() << " + " << format("0x%" PRIx64, c.cls);
4895 } else
4896 outs() << format("0x%" PRIx64, c.cls);
4897 outs() << "\n";
4898 if (c.cls + n_value != 0)
4899 print_class64_t(c.cls + n_value, info);
4900
4901 outs() << " instanceMethods ";
4902 sym_name =
4903 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4904 info, n_value, c.instanceMethods);
4905 if (n_value != 0) {
4906 if (info->verbose && sym_name != nullptr)
4907 outs() << sym_name;
4908 else
4909 outs() << format("0x%" PRIx64, n_value);
4910 if (c.instanceMethods != 0)
4911 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4912 } else
4913 outs() << format("0x%" PRIx64, c.instanceMethods);
4914 outs() << "\n";
4915 if (c.instanceMethods + n_value != 0)
4916 print_method_list64_t(c.instanceMethods + n_value, info, "");
4917
4918 outs() << " classMethods ";
4919 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4920 S, info, n_value, c.classMethods);
4921 if (n_value != 0) {
4922 if (info->verbose && sym_name != nullptr)
4923 outs() << sym_name;
4924 else
4925 outs() << format("0x%" PRIx64, n_value);
4926 if (c.classMethods != 0)
4927 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4928 } else
4929 outs() << format("0x%" PRIx64, c.classMethods);
4930 outs() << "\n";
4931 if (c.classMethods + n_value != 0)
4932 print_method_list64_t(c.classMethods + n_value, info, "");
4933
4934 outs() << " protocols ";
4935 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4936 info, n_value, c.protocols);
4937 if (n_value != 0) {
4938 if (info->verbose && sym_name != nullptr)
4939 outs() << sym_name;
4940 else
4941 outs() << format("0x%" PRIx64, n_value);
4942 if (c.protocols != 0)
4943 outs() << " + " << format("0x%" PRIx64, c.protocols);
4944 } else
4945 outs() << format("0x%" PRIx64, c.protocols);
4946 outs() << "\n";
4947 if (c.protocols + n_value != 0)
4948 print_protocol_list64_t(c.protocols + n_value, info);
4949
4950 outs() << "instanceProperties ";
4951 sym_name =
4952 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4953 S, info, n_value, c.instanceProperties);
4954 if (n_value != 0) {
4955 if (info->verbose && sym_name != nullptr)
4956 outs() << sym_name;
4957 else
4958 outs() << format("0x%" PRIx64, n_value);
4959 if (c.instanceProperties != 0)
4960 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4961 } else
4962 outs() << format("0x%" PRIx64, c.instanceProperties);
4963 outs() << "\n";
4964 if (c.instanceProperties + n_value != 0)
4965 print_objc_property_list64(c.instanceProperties + n_value, info);
4966}
4967
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004968static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4969 struct category32_t c;
4970 const char *r;
4971 uint32_t offset, left;
4972 SectionRef S, xS;
4973 const char *name;
4974
4975 r = get_pointer_32(p, offset, left, S, info);
4976 if (r == nullptr)
4977 return;
4978 memset(&c, '\0', sizeof(struct category32_t));
4979 if (left < sizeof(struct category32_t)) {
4980 memcpy(&c, r, left);
4981 outs() << " (category_t entends past the end of the section)\n";
4982 } else
4983 memcpy(&c, r, sizeof(struct category32_t));
4984 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4985 swapStruct(c);
4986
4987 outs() << " name " << format("0x%" PRIx32, c.name);
4988 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4989 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004990 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004991 outs() << " " << name;
4992 outs() << "\n";
4993
4994 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4995 if (c.cls != 0)
4996 print_class32_t(c.cls, info);
4997 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4998 << "\n";
4999 if (c.instanceMethods != 0)
5000 print_method_list32_t(c.instanceMethods, info, "");
5001 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5002 << "\n";
5003 if (c.classMethods != 0)
5004 print_method_list32_t(c.classMethods, info, "");
5005 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5006 if (c.protocols != 0)
5007 print_protocol_list32_t(c.protocols, info);
5008 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5009 << "\n";
5010 if (c.instanceProperties != 0)
5011 print_objc_property_list32(c.instanceProperties, info);
5012}
5013
Kevin Enderby0fc11822015-04-01 20:57:01 +00005014static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5015 uint32_t i, left, offset, xoffset;
5016 uint64_t p, n_value;
5017 struct message_ref64 mr;
5018 const char *name, *sym_name;
5019 const char *r;
5020 SectionRef xS;
5021
5022 if (S == SectionRef())
5023 return;
5024
5025 StringRef SectName;
5026 S.getName(SectName);
5027 DataRefImpl Ref = S.getRawDataRefImpl();
5028 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5029 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5030 offset = 0;
5031 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5032 p = S.getAddress() + i;
5033 r = get_pointer_64(p, offset, left, S, info);
5034 if (r == nullptr)
5035 return;
5036 memset(&mr, '\0', sizeof(struct message_ref64));
5037 if (left < sizeof(struct message_ref64)) {
5038 memcpy(&mr, r, left);
5039 outs() << " (message_ref entends past the end of the section)\n";
5040 } else
5041 memcpy(&mr, r, sizeof(struct message_ref64));
5042 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5043 swapStruct(mr);
5044
5045 outs() << " imp ";
5046 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5047 n_value, mr.imp);
5048 if (n_value != 0) {
5049 outs() << format("0x%" PRIx64, n_value) << " ";
5050 if (mr.imp != 0)
5051 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5052 } else
5053 outs() << format("0x%" PRIx64, mr.imp) << " ";
5054 if (name != nullptr)
5055 outs() << " " << name;
5056 outs() << "\n";
5057
5058 outs() << " sel ";
5059 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5060 info, n_value, mr.sel);
5061 if (n_value != 0) {
5062 if (info->verbose && sym_name != nullptr)
5063 outs() << sym_name;
5064 else
5065 outs() << format("0x%" PRIx64, n_value);
5066 if (mr.sel != 0)
5067 outs() << " + " << format("0x%" PRIx64, mr.sel);
5068 } else
5069 outs() << format("0x%" PRIx64, mr.sel);
5070 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5071 if (name != nullptr)
5072 outs() << format(" %.*s", left, name);
5073 outs() << "\n";
5074
5075 offset += sizeof(struct message_ref64);
5076 }
5077}
5078
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005079static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5080 uint32_t i, left, offset, xoffset, p;
5081 struct message_ref32 mr;
5082 const char *name, *r;
5083 SectionRef xS;
5084
5085 if (S == SectionRef())
5086 return;
5087
5088 StringRef SectName;
5089 S.getName(SectName);
5090 DataRefImpl Ref = S.getRawDataRefImpl();
5091 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5092 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5093 offset = 0;
5094 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5095 p = S.getAddress() + i;
5096 r = get_pointer_32(p, offset, left, S, info);
5097 if (r == nullptr)
5098 return;
5099 memset(&mr, '\0', sizeof(struct message_ref32));
5100 if (left < sizeof(struct message_ref32)) {
5101 memcpy(&mr, r, left);
5102 outs() << " (message_ref entends past the end of the section)\n";
5103 } else
5104 memcpy(&mr, r, sizeof(struct message_ref32));
5105 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5106 swapStruct(mr);
5107
5108 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5109 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5110 mr.imp);
5111 if (name != nullptr)
5112 outs() << " " << name;
5113 outs() << "\n";
5114
5115 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5116 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5117 if (name != nullptr)
5118 outs() << " " << name;
5119 outs() << "\n";
5120
5121 offset += sizeof(struct message_ref32);
5122 }
5123}
5124
Kevin Enderby0fc11822015-04-01 20:57:01 +00005125static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5126 uint32_t left, offset, swift_version;
5127 uint64_t p;
5128 struct objc_image_info64 o;
5129 const char *r;
5130
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005131 if (S == SectionRef())
5132 return;
5133
Kevin Enderby0fc11822015-04-01 20:57:01 +00005134 StringRef SectName;
5135 S.getName(SectName);
5136 DataRefImpl Ref = S.getRawDataRefImpl();
5137 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5138 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5139 p = S.getAddress();
5140 r = get_pointer_64(p, offset, left, S, info);
5141 if (r == nullptr)
5142 return;
5143 memset(&o, '\0', sizeof(struct objc_image_info64));
5144 if (left < sizeof(struct objc_image_info64)) {
5145 memcpy(&o, r, left);
5146 outs() << " (objc_image_info entends past the end of the section)\n";
5147 } else
5148 memcpy(&o, r, sizeof(struct objc_image_info64));
5149 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5150 swapStruct(o);
5151 outs() << " version " << o.version << "\n";
5152 outs() << " flags " << format("0x%" PRIx32, o.flags);
5153 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5154 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5155 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5156 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5157 swift_version = (o.flags >> 8) & 0xff;
5158 if (swift_version != 0) {
5159 if (swift_version == 1)
5160 outs() << " Swift 1.0";
5161 else if (swift_version == 2)
5162 outs() << " Swift 1.1";
5163 else
5164 outs() << " unknown future Swift version (" << swift_version << ")";
5165 }
5166 outs() << "\n";
5167}
5168
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005169static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5170 uint32_t left, offset, swift_version, p;
5171 struct objc_image_info32 o;
5172 const char *r;
5173
Kevin Enderby19be2512016-04-21 19:49:29 +00005174 if (S == SectionRef())
5175 return;
5176
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005177 StringRef SectName;
5178 S.getName(SectName);
5179 DataRefImpl Ref = S.getRawDataRefImpl();
5180 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5181 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5182 p = S.getAddress();
5183 r = get_pointer_32(p, offset, left, S, info);
5184 if (r == nullptr)
5185 return;
5186 memset(&o, '\0', sizeof(struct objc_image_info32));
5187 if (left < sizeof(struct objc_image_info32)) {
5188 memcpy(&o, r, left);
5189 outs() << " (objc_image_info entends past the end of the section)\n";
5190 } else
5191 memcpy(&o, r, sizeof(struct objc_image_info32));
5192 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5193 swapStruct(o);
5194 outs() << " version " << o.version << "\n";
5195 outs() << " flags " << format("0x%" PRIx32, o.flags);
5196 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5197 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5198 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5199 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5200 swift_version = (o.flags >> 8) & 0xff;
5201 if (swift_version != 0) {
5202 if (swift_version == 1)
5203 outs() << " Swift 1.0";
5204 else if (swift_version == 2)
5205 outs() << " Swift 1.1";
5206 else
5207 outs() << " unknown future Swift version (" << swift_version << ")";
5208 }
5209 outs() << "\n";
5210}
5211
Kevin Enderby846c0002015-04-16 17:19:59 +00005212static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5213 uint32_t left, offset, p;
5214 struct imageInfo_t o;
5215 const char *r;
5216
5217 StringRef SectName;
5218 S.getName(SectName);
5219 DataRefImpl Ref = S.getRawDataRefImpl();
5220 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5221 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5222 p = S.getAddress();
5223 r = get_pointer_32(p, offset, left, S, info);
5224 if (r == nullptr)
5225 return;
5226 memset(&o, '\0', sizeof(struct imageInfo_t));
5227 if (left < sizeof(struct imageInfo_t)) {
5228 memcpy(&o, r, left);
5229 outs() << " (imageInfo entends past the end of the section)\n";
5230 } else
5231 memcpy(&o, r, sizeof(struct imageInfo_t));
5232 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5233 swapStruct(o);
5234 outs() << " version " << o.version << "\n";
5235 outs() << " flags " << format("0x%" PRIx32, o.flags);
5236 if (o.flags & 0x1)
5237 outs() << " F&C";
5238 if (o.flags & 0x2)
5239 outs() << " GC";
5240 if (o.flags & 0x4)
5241 outs() << " GC-only";
5242 else
5243 outs() << " RR";
5244 outs() << "\n";
5245}
5246
Kevin Enderby0fc11822015-04-01 20:57:01 +00005247static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5248 SymbolAddressMap AddrMap;
5249 if (verbose)
5250 CreateSymbolAddressMap(O, &AddrMap);
5251
5252 std::vector<SectionRef> Sections;
5253 for (const SectionRef &Section : O->sections()) {
5254 StringRef SectName;
5255 Section.getName(SectName);
5256 Sections.push_back(Section);
5257 }
5258
5259 struct DisassembleInfo info;
5260 // Set up the block of info used by the Symbolizer call backs.
5261 info.verbose = verbose;
5262 info.O = O;
5263 info.AddrMap = &AddrMap;
5264 info.Sections = &Sections;
5265 info.class_name = nullptr;
5266 info.selector_name = nullptr;
5267 info.method = nullptr;
5268 info.demangled_name = nullptr;
5269 info.bindtable = nullptr;
5270 info.adrp_addr = 0;
5271 info.adrp_inst = 0;
5272
Kevin Enderbyaac75382015-10-08 16:56:35 +00005273 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005274 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5275 if (CL == SectionRef())
5276 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005277 if (CL == SectionRef())
5278 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5279 if (CL == SectionRef())
5280 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005281 info.S = CL;
5282 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005283
Davide Italiano62507042015-12-11 22:27:59 +00005284 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5285 if (CR == SectionRef())
5286 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005287 if (CR == SectionRef())
5288 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5289 if (CR == SectionRef())
5290 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005291 info.S = CR;
5292 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005293
Davide Italiano62507042015-12-11 22:27:59 +00005294 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5295 if (SR == SectionRef())
5296 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005297 if (SR == SectionRef())
5298 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5299 if (SR == SectionRef())
5300 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005301 info.S = SR;
5302 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005303
Davide Italiano62507042015-12-11 22:27:59 +00005304 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5305 if (CA == SectionRef())
5306 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005307 if (CA == SectionRef())
5308 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5309 if (CA == SectionRef())
5310 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005311 info.S = CA;
5312 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005313
Davide Italiano62507042015-12-11 22:27:59 +00005314 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5315 if (PL == SectionRef())
5316 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005317 if (PL == SectionRef())
5318 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5319 if (PL == SectionRef())
5320 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005321 info.S = PL;
5322 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005323
Davide Italiano62507042015-12-11 22:27:59 +00005324 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5325 if (MR == SectionRef())
5326 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005327 if (MR == SectionRef())
5328 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5329 if (MR == SectionRef())
5330 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005331 info.S = MR;
5332 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005333
Davide Italiano62507042015-12-11 22:27:59 +00005334 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5335 if (II == SectionRef())
5336 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005337 if (II == SectionRef())
5338 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5339 if (II == SectionRef())
5340 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005341 info.S = II;
5342 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005343}
5344
5345static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005346 SymbolAddressMap AddrMap;
5347 if (verbose)
5348 CreateSymbolAddressMap(O, &AddrMap);
5349
5350 std::vector<SectionRef> Sections;
5351 for (const SectionRef &Section : O->sections()) {
5352 StringRef SectName;
5353 Section.getName(SectName);
5354 Sections.push_back(Section);
5355 }
5356
5357 struct DisassembleInfo info;
5358 // Set up the block of info used by the Symbolizer call backs.
5359 info.verbose = verbose;
5360 info.O = O;
5361 info.AddrMap = &AddrMap;
5362 info.Sections = &Sections;
5363 info.class_name = nullptr;
5364 info.selector_name = nullptr;
5365 info.method = nullptr;
5366 info.demangled_name = nullptr;
5367 info.bindtable = nullptr;
5368 info.adrp_addr = 0;
5369 info.adrp_inst = 0;
5370
Kevin Enderby5879a482017-02-09 17:56:26 +00005371 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5372 if (CL == SectionRef())
5373 CL = get_section(O, "__DATA", "__objc_classlist");
5374 if (CL == SectionRef())
5375 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5376 if (CL == SectionRef())
5377 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5378 info.S = CL;
5379 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005380
Kevin Enderby5879a482017-02-09 17:56:26 +00005381 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5382 if (CR == SectionRef())
5383 CR = get_section(O, "__DATA", "__objc_classrefs");
5384 if (CR == SectionRef())
5385 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5386 if (CR == SectionRef())
5387 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5388 info.S = CR;
5389 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005390
Kevin Enderby5879a482017-02-09 17:56:26 +00005391 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5392 if (SR == SectionRef())
5393 SR = get_section(O, "__DATA", "__objc_superrefs");
5394 if (SR == SectionRef())
5395 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5396 if (SR == SectionRef())
5397 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5398 info.S = SR;
5399 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005400
Kevin Enderby5879a482017-02-09 17:56:26 +00005401 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5402 if (CA == SectionRef())
5403 CA = get_section(O, "__DATA", "__objc_catlist");
5404 if (CA == SectionRef())
5405 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5406 if (CA == SectionRef())
5407 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5408 info.S = CA;
5409 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005410
Kevin Enderby5879a482017-02-09 17:56:26 +00005411 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5412 if (PL == SectionRef())
5413 PL = get_section(O, "__DATA", "__objc_protolist");
5414 if (PL == SectionRef())
5415 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5416 if (PL == SectionRef())
5417 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5418 info.S = PL;
5419 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005420
Kevin Enderby5879a482017-02-09 17:56:26 +00005421 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5422 if (MR == SectionRef())
5423 MR = get_section(O, "__DATA", "__objc_msgrefs");
5424 if (MR == SectionRef())
5425 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5426 if (MR == SectionRef())
5427 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5428 info.S = MR;
5429 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005430
Kevin Enderby5879a482017-02-09 17:56:26 +00005431 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5432 if (II == SectionRef())
5433 II = get_section(O, "__DATA", "__objc_imageinfo");
5434 if (II == SectionRef())
5435 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5436 if (II == SectionRef())
5437 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5438 info.S = II;
5439 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005440}
5441
5442static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005443 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5444 const char *r, *name, *defs;
5445 struct objc_module_t module;
5446 SectionRef S, xS;
5447 struct objc_symtab_t symtab;
5448 struct objc_class_t objc_class;
5449 struct objc_category_t objc_category;
5450
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005451 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005452 S = get_section(O, "__OBJC", "__module_info");
5453 if (S == SectionRef())
5454 return false;
5455
5456 SymbolAddressMap AddrMap;
5457 if (verbose)
5458 CreateSymbolAddressMap(O, &AddrMap);
5459
5460 std::vector<SectionRef> Sections;
5461 for (const SectionRef &Section : O->sections()) {
5462 StringRef SectName;
5463 Section.getName(SectName);
5464 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005465 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005466
5467 struct DisassembleInfo info;
5468 // Set up the block of info used by the Symbolizer call backs.
5469 info.verbose = verbose;
5470 info.O = O;
5471 info.AddrMap = &AddrMap;
5472 info.Sections = &Sections;
5473 info.class_name = nullptr;
5474 info.selector_name = nullptr;
5475 info.method = nullptr;
5476 info.demangled_name = nullptr;
5477 info.bindtable = nullptr;
5478 info.adrp_addr = 0;
5479 info.adrp_inst = 0;
5480
5481 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5482 p = S.getAddress() + i;
5483 r = get_pointer_32(p, offset, left, S, &info, true);
5484 if (r == nullptr)
5485 return true;
5486 memset(&module, '\0', sizeof(struct objc_module_t));
5487 if (left < sizeof(struct objc_module_t)) {
5488 memcpy(&module, r, left);
5489 outs() << " (module extends past end of __module_info section)\n";
5490 } else
5491 memcpy(&module, r, sizeof(struct objc_module_t));
5492 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5493 swapStruct(module);
5494
5495 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5496 outs() << " version " << module.version << "\n";
5497 outs() << " size " << module.size << "\n";
5498 outs() << " name ";
5499 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5500 if (name != nullptr)
5501 outs() << format("%.*s", left, name);
5502 else
5503 outs() << format("0x%08" PRIx32, module.name)
5504 << "(not in an __OBJC section)";
5505 outs() << "\n";
5506
5507 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5508 if (module.symtab == 0 || r == nullptr) {
5509 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5510 << " (not in an __OBJC section)\n";
5511 continue;
5512 }
5513 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5514 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5515 defs_left = 0;
5516 defs = nullptr;
5517 if (left < sizeof(struct objc_symtab_t)) {
5518 memcpy(&symtab, r, left);
5519 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5520 } else {
5521 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5522 if (left > sizeof(struct objc_symtab_t)) {
5523 defs_left = left - sizeof(struct objc_symtab_t);
5524 defs = r + sizeof(struct objc_symtab_t);
5525 }
5526 }
5527 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5528 swapStruct(symtab);
5529
5530 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5531 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5532 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5533 if (r == nullptr)
5534 outs() << " (not in an __OBJC section)";
5535 outs() << "\n";
5536 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5537 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5538 if (symtab.cls_def_cnt > 0)
5539 outs() << "\tClass Definitions\n";
5540 for (j = 0; j < symtab.cls_def_cnt; j++) {
5541 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5542 outs() << "\t(remaining class defs entries entends past the end of the "
5543 << "section)\n";
5544 break;
5545 }
5546 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5547 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5548 sys::swapByteOrder(def);
5549
5550 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5551 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5552 if (r != nullptr) {
5553 if (left > sizeof(struct objc_class_t)) {
5554 outs() << "\n";
5555 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5556 } else {
5557 outs() << " (entends past the end of the section)\n";
5558 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5559 memcpy(&objc_class, r, left);
5560 }
5561 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5562 swapStruct(objc_class);
5563 print_objc_class_t(&objc_class, &info);
5564 } else {
5565 outs() << "(not in an __OBJC section)\n";
5566 }
5567
5568 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5569 outs() << "\tMeta Class";
5570 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5571 if (r != nullptr) {
5572 if (left > sizeof(struct objc_class_t)) {
5573 outs() << "\n";
5574 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5575 } else {
5576 outs() << " (entends past the end of the section)\n";
5577 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5578 memcpy(&objc_class, r, left);
5579 }
5580 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5581 swapStruct(objc_class);
5582 print_objc_class_t(&objc_class, &info);
5583 } else {
5584 outs() << "(not in an __OBJC section)\n";
5585 }
5586 }
5587 }
5588 if (symtab.cat_def_cnt > 0)
5589 outs() << "\tCategory Definitions\n";
5590 for (j = 0; j < symtab.cat_def_cnt; j++) {
5591 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5592 outs() << "\t(remaining category defs entries entends past the end of "
5593 << "the section)\n";
5594 break;
5595 }
5596 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5597 sizeof(uint32_t));
5598 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5599 sys::swapByteOrder(def);
5600
5601 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5602 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5603 << format("0x%08" PRIx32, def);
5604 if (r != nullptr) {
5605 if (left > sizeof(struct objc_category_t)) {
5606 outs() << "\n";
5607 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5608 } else {
5609 outs() << " (entends past the end of the section)\n";
5610 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5611 memcpy(&objc_category, r, left);
5612 }
5613 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5614 swapStruct(objc_category);
5615 print_objc_objc_category_t(&objc_category, &info);
5616 } else {
5617 outs() << "(not in an __OBJC section)\n";
5618 }
5619 }
5620 }
5621 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5622 if (II != SectionRef())
5623 print_image_info(II, &info);
5624
5625 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005626}
5627
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005628static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5629 uint32_t size, uint32_t addr) {
5630 SymbolAddressMap AddrMap;
5631 CreateSymbolAddressMap(O, &AddrMap);
5632
5633 std::vector<SectionRef> Sections;
5634 for (const SectionRef &Section : O->sections()) {
5635 StringRef SectName;
5636 Section.getName(SectName);
5637 Sections.push_back(Section);
5638 }
5639
5640 struct DisassembleInfo info;
5641 // Set up the block of info used by the Symbolizer call backs.
5642 info.verbose = true;
5643 info.O = O;
5644 info.AddrMap = &AddrMap;
5645 info.Sections = &Sections;
5646 info.class_name = nullptr;
5647 info.selector_name = nullptr;
5648 info.method = nullptr;
5649 info.demangled_name = nullptr;
5650 info.bindtable = nullptr;
5651 info.adrp_addr = 0;
5652 info.adrp_inst = 0;
5653
5654 const char *p;
5655 struct objc_protocol_t protocol;
5656 uint32_t left, paddr;
5657 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5658 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5659 left = size - (p - sect);
5660 if (left < sizeof(struct objc_protocol_t)) {
5661 outs() << "Protocol extends past end of __protocol section\n";
5662 memcpy(&protocol, p, left);
5663 } else
5664 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5665 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5666 swapStruct(protocol);
5667 paddr = addr + (p - sect);
5668 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5669 if (print_protocol(paddr, 0, &info))
5670 outs() << "(not in an __OBJC section)\n";
5671 }
5672}
5673
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005674#ifdef HAVE_LIBXAR
5675inline void swapStruct(struct xar_header &xar) {
5676 sys::swapByteOrder(xar.magic);
5677 sys::swapByteOrder(xar.size);
5678 sys::swapByteOrder(xar.version);
5679 sys::swapByteOrder(xar.toc_length_compressed);
5680 sys::swapByteOrder(xar.toc_length_uncompressed);
5681 sys::swapByteOrder(xar.cksum_alg);
5682}
5683
5684static void PrintModeVerbose(uint32_t mode) {
5685 switch(mode & S_IFMT){
5686 case S_IFDIR:
5687 outs() << "d";
5688 break;
5689 case S_IFCHR:
5690 outs() << "c";
5691 break;
5692 case S_IFBLK:
5693 outs() << "b";
5694 break;
5695 case S_IFREG:
5696 outs() << "-";
5697 break;
5698 case S_IFLNK:
5699 outs() << "l";
5700 break;
5701 case S_IFSOCK:
5702 outs() << "s";
5703 break;
5704 default:
5705 outs() << "?";
5706 break;
5707 }
5708
5709 /* owner permissions */
5710 if(mode & S_IREAD)
5711 outs() << "r";
5712 else
5713 outs() << "-";
5714 if(mode & S_IWRITE)
5715 outs() << "w";
5716 else
5717 outs() << "-";
5718 if(mode & S_ISUID)
5719 outs() << "s";
5720 else if(mode & S_IEXEC)
5721 outs() << "x";
5722 else
5723 outs() << "-";
5724
5725 /* group permissions */
5726 if(mode & (S_IREAD >> 3))
5727 outs() << "r";
5728 else
5729 outs() << "-";
5730 if(mode & (S_IWRITE >> 3))
5731 outs() << "w";
5732 else
5733 outs() << "-";
5734 if(mode & S_ISGID)
5735 outs() << "s";
5736 else if(mode & (S_IEXEC >> 3))
5737 outs() << "x";
5738 else
5739 outs() << "-";
5740
5741 /* other permissions */
5742 if(mode & (S_IREAD >> 6))
5743 outs() << "r";
5744 else
5745 outs() << "-";
5746 if(mode & (S_IWRITE >> 6))
5747 outs() << "w";
5748 else
5749 outs() << "-";
5750 if(mode & S_ISVTX)
5751 outs() << "t";
5752 else if(mode & (S_IEXEC >> 6))
5753 outs() << "x";
5754 else
5755 outs() << "-";
5756}
5757
5758static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5759 xar_iter_t xi;
5760 xar_file_t xf;
5761 xar_iter_t xp;
5762 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5763 char *endp;
5764 uint32_t mode_value;
5765
5766 xi = xar_iter_new();
5767 if (!xi) {
5768 errs() << "Can't obtain an xar iterator for xar archive "
5769 << XarFilename << "\n";
5770 return;
5771 }
5772
5773 // Go through the xar's files.
5774 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5775 xp = xar_iter_new();
5776 if(!xp){
5777 errs() << "Can't obtain an xar iterator for xar archive "
5778 << XarFilename << "\n";
5779 return;
5780 }
5781 type = nullptr;
5782 mode = nullptr;
5783 user = nullptr;
5784 group = nullptr;
5785 size = nullptr;
5786 mtime = nullptr;
5787 name = nullptr;
5788 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5789 const char *val = nullptr;
5790 xar_prop_get(xf, key, &val);
5791#if 0 // Useful for debugging.
5792 outs() << "key: " << key << " value: " << val << "\n";
5793#endif
5794 if(strcmp(key, "type") == 0)
5795 type = val;
5796 if(strcmp(key, "mode") == 0)
5797 mode = val;
5798 if(strcmp(key, "user") == 0)
5799 user = val;
5800 if(strcmp(key, "group") == 0)
5801 group = val;
5802 if(strcmp(key, "data/size") == 0)
5803 size = val;
5804 if(strcmp(key, "mtime") == 0)
5805 mtime = val;
5806 if(strcmp(key, "name") == 0)
5807 name = val;
5808 }
5809 if(mode != nullptr){
5810 mode_value = strtoul(mode, &endp, 8);
5811 if(*endp != '\0')
5812 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5813 if(strcmp(type, "file") == 0)
5814 mode_value |= S_IFREG;
5815 PrintModeVerbose(mode_value);
5816 outs() << " ";
5817 }
5818 if(user != nullptr)
5819 outs() << format("%10s/", user);
5820 if(group != nullptr)
5821 outs() << format("%-10s ", group);
5822 if(size != nullptr)
5823 outs() << format("%7s ", size);
5824 if(mtime != nullptr){
5825 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5826 outs() << *m;
5827 if(*m == 'T')
5828 m++;
5829 outs() << " ";
5830 for( ; *m != 'Z' && *m != '\0'; m++)
5831 outs() << *m;
5832 outs() << " ";
5833 }
5834 if(name != nullptr)
5835 outs() << name;
5836 outs() << "\n";
5837 }
5838}
5839
5840static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5841 uint32_t size, bool verbose,
5842 bool PrintXarHeader, bool PrintXarFileHeaders,
5843 std::string XarMemberName) {
5844 if(size < sizeof(struct xar_header)) {
5845 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5846 "of struct xar_header)\n";
5847 return;
5848 }
5849 struct xar_header XarHeader;
5850 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5851 if (sys::IsLittleEndianHost)
5852 swapStruct(XarHeader);
5853 if (PrintXarHeader) {
5854 if (!XarMemberName.empty())
5855 outs() << "In xar member " << XarMemberName << ": ";
5856 else
5857 outs() << "For (__LLVM,__bundle) section: ";
5858 outs() << "xar header\n";
5859 if (XarHeader.magic == XAR_HEADER_MAGIC)
5860 outs() << " magic XAR_HEADER_MAGIC\n";
5861 else
5862 outs() << " magic "
5863 << format_hex(XarHeader.magic, 10, true)
5864 << " (not XAR_HEADER_MAGIC)\n";
5865 outs() << " size " << XarHeader.size << "\n";
5866 outs() << " version " << XarHeader.version << "\n";
5867 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5868 << "\n";
5869 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5870 << "\n";
5871 outs() << " cksum_alg ";
5872 switch (XarHeader.cksum_alg) {
5873 case XAR_CKSUM_NONE:
5874 outs() << "XAR_CKSUM_NONE\n";
5875 break;
5876 case XAR_CKSUM_SHA1:
5877 outs() << "XAR_CKSUM_SHA1\n";
5878 break;
5879 case XAR_CKSUM_MD5:
5880 outs() << "XAR_CKSUM_MD5\n";
5881 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005882#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005883 case XAR_CKSUM_SHA256:
5884 outs() << "XAR_CKSUM_SHA256\n";
5885 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005886#endif
5887#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005888 case XAR_CKSUM_SHA512:
5889 outs() << "XAR_CKSUM_SHA512\n";
5890 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005891#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005892 default:
5893 outs() << XarHeader.cksum_alg << "\n";
5894 }
5895 }
5896
5897 SmallString<128> XarFilename;
5898 int FD;
5899 std::error_code XarEC =
5900 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5901 if (XarEC) {
5902 errs() << XarEC.message() << "\n";
5903 return;
5904 }
5905 tool_output_file XarFile(XarFilename, FD);
5906 raw_fd_ostream &XarOut = XarFile.os();
5907 StringRef XarContents(sect, size);
5908 XarOut << XarContents;
5909 XarOut.close();
5910 if (XarOut.has_error())
5911 return;
5912
5913 xar_t xar = xar_open(XarFilename.c_str(), READ);
5914 if (!xar) {
5915 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5916 return;
5917 }
5918
5919 SmallString<128> TocFilename;
5920 std::error_code TocEC =
5921 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5922 if (TocEC) {
5923 errs() << TocEC.message() << "\n";
5924 return;
5925 }
5926 xar_serialize(xar, TocFilename.c_str());
5927
5928 if (PrintXarFileHeaders) {
5929 if (!XarMemberName.empty())
5930 outs() << "In xar member " << XarMemberName << ": ";
5931 else
5932 outs() << "For (__LLVM,__bundle) section: ";
5933 outs() << "xar archive files:\n";
5934 PrintXarFilesSummary(XarFilename.c_str(), xar);
5935 }
5936
5937 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5938 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5939 if (std::error_code EC = FileOrErr.getError()) {
5940 errs() << EC.message() << "\n";
5941 return;
5942 }
5943 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5944
5945 if (!XarMemberName.empty())
5946 outs() << "In xar member " << XarMemberName << ": ";
5947 else
5948 outs() << "For (__LLVM,__bundle) section: ";
5949 outs() << "xar table of contents:\n";
5950 outs() << Buffer->getBuffer() << "\n";
5951
5952 // TODO: Go through the xar's files.
5953 xar_iter_t xi = xar_iter_new();
5954 if(!xi){
5955 errs() << "Can't obtain an xar iterator for xar archive "
5956 << XarFilename.c_str() << "\n";
5957 xar_close(xar);
5958 return;
5959 }
5960 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5961 const char *key;
5962 xar_iter_t xp;
5963 const char *member_name, *member_type, *member_size_string;
5964 size_t member_size;
5965
5966 xp = xar_iter_new();
5967 if(!xp){
5968 errs() << "Can't obtain an xar iterator for xar archive "
5969 << XarFilename.c_str() << "\n";
5970 xar_close(xar);
5971 return;
5972 }
5973 member_name = NULL;
5974 member_type = NULL;
5975 member_size_string = NULL;
5976 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5977 const char *val = nullptr;
5978 xar_prop_get(xf, key, &val);
5979#if 0 // Useful for debugging.
5980 outs() << "key: " << key << " value: " << val << "\n";
5981#endif
5982 if(strcmp(key, "name") == 0)
5983 member_name = val;
5984 if(strcmp(key, "type") == 0)
5985 member_type = val;
5986 if(strcmp(key, "data/size") == 0)
5987 member_size_string = val;
5988 }
5989 /*
5990 * If we find a file with a name, date/size and type properties
5991 * and with the type being "file" see if that is a xar file.
5992 */
5993 if (member_name != NULL && member_type != NULL &&
5994 strcmp(member_type, "file") == 0 &&
5995 member_size_string != NULL){
5996 // Extract the file into a buffer.
5997 char *endptr;
5998 member_size = strtoul(member_size_string, &endptr, 10);
5999 if (*endptr == '\0' && member_size != 0) {
6000 char *buffer = (char *) ::operator new (member_size);
6001 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6002#if 0 // Useful for debugging.
6003 outs() << "xar member: " << member_name << " extracted\n";
6004#endif
6005 // Set the XarMemberName we want to see printed in the header.
6006 std::string OldXarMemberName;
6007 // If XarMemberName is already set this is nested. So
6008 // save the old name and create the nested name.
6009 if (!XarMemberName.empty()) {
6010 OldXarMemberName = XarMemberName;
6011 XarMemberName =
6012 (Twine("[") + XarMemberName + "]" + member_name).str();
6013 } else {
6014 OldXarMemberName = "";
6015 XarMemberName = member_name;
6016 }
6017 // See if this is could be a xar file (nested).
6018 if (member_size >= sizeof(struct xar_header)) {
6019#if 0 // Useful for debugging.
6020 outs() << "could be a xar file: " << member_name << "\n";
6021#endif
6022 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6023 if (sys::IsLittleEndianHost)
6024 swapStruct(XarHeader);
6025 if(XarHeader.magic == XAR_HEADER_MAGIC)
6026 DumpBitcodeSection(O, buffer, member_size, verbose,
6027 PrintXarHeader, PrintXarFileHeaders,
6028 XarMemberName);
6029 }
6030 XarMemberName = OldXarMemberName;
6031 }
6032 delete buffer;
6033 }
6034 }
6035 xar_iter_free(xp);
6036 }
6037 xar_close(xar);
6038}
6039#endif // defined(HAVE_LIBXAR)
6040
Kevin Enderby0fc11822015-04-01 20:57:01 +00006041static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6042 if (O->is64Bit())
6043 printObjc2_64bit_MetaData(O, verbose);
6044 else {
6045 MachO::mach_header H;
6046 H = O->getHeader();
6047 if (H.cputype == MachO::CPU_TYPE_ARM)
6048 printObjc2_32bit_MetaData(O, verbose);
6049 else {
6050 // This is the 32-bit non-arm cputype case. Which is normally
6051 // the first Objective-C ABI. But it may be the case of a
6052 // binary for the iOS simulator which is the second Objective-C
6053 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6054 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006055 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006056 printObjc2_32bit_MetaData(O, verbose);
6057 }
6058 }
6059}
6060
Kevin Enderbybf246f52014-09-24 23:08:22 +00006061// GuessLiteralPointer returns a string which for the item in the Mach-O file
6062// for the address passed in as ReferenceValue for printing as a comment with
6063// the instruction and also returns the corresponding type of that item
6064// indirectly through ReferenceType.
6065//
6066// If ReferenceValue is an address of literal cstring then a pointer to the
6067// cstring is returned and ReferenceType is set to
6068// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6069//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006070// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6071// Class ref that name is returned and the ReferenceType is set accordingly.
6072//
6073// Lastly, literals which are Symbol address in a literal pool are looked for
6074// and if found the symbol name is returned and ReferenceType is set to
6075// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6076//
6077// If there is no item in the Mach-O file for the address passed in as
6078// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006079static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6080 uint64_t ReferencePC,
6081 uint64_t *ReferenceType,
6082 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006083 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006084 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6085 uint64_t sect_addr = info->S.getAddress();
6086 uint64_t sect_offset = ReferencePC - sect_addr;
6087 bool reloc_found = false;
6088 DataRefImpl Rel;
6089 MachO::any_relocation_info RE;
6090 bool isExtern = false;
6091 SymbolRef Symbol;
6092 for (const RelocationRef &Reloc : info->S.relocations()) {
6093 uint64_t RelocOffset = Reloc.getOffset();
6094 if (RelocOffset == sect_offset) {
6095 Rel = Reloc.getRawDataRefImpl();
6096 RE = info->O->getRelocation(Rel);
6097 if (info->O->isRelocationScattered(RE))
6098 continue;
6099 isExtern = info->O->getPlainRelocationExternal(RE);
6100 if (isExtern) {
6101 symbol_iterator RelocSym = Reloc.getSymbol();
6102 Symbol = *RelocSym;
6103 }
6104 reloc_found = true;
6105 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006106 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006107 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006108 // If there is an external relocation entry for a symbol in a section
6109 // then used that symbol's value for the value of the reference.
6110 if (reloc_found && isExtern) {
6111 if (info->O->getAnyRelocationPCRel(RE)) {
6112 unsigned Type = info->O->getAnyRelocationType(RE);
6113 if (Type == MachO::X86_64_RELOC_SIGNED) {
6114 ReferenceValue = Symbol.getValue();
6115 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006116 }
6117 }
6118 }
6119
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006120 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6121 // Message refs and Class refs.
6122 bool classref, selref, msgref, cfstring;
6123 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6124 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006125 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006126 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6127 // And the pointer_value in that section is typically zero as it will be
6128 // set by dyld as part of the "bind information".
6129 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6130 if (name != nullptr) {
6131 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006132 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006133 if (class_name != nullptr && class_name[1] == '_' &&
6134 class_name[2] != '\0') {
6135 info->class_name = class_name + 2;
6136 return name;
6137 }
6138 }
6139 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006140
David Blaikie33dd45d02015-03-23 18:39:02 +00006141 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006142 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6143 const char *name =
6144 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6145 if (name != nullptr)
6146 info->class_name = name;
6147 else
6148 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006149 return name;
6150 }
6151
David Blaikie33dd45d02015-03-23 18:39:02 +00006152 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006153 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6154 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6155 return name;
6156 }
6157
David Blaikie33dd45d02015-03-23 18:39:02 +00006158 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006159 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6160
6161 if (pointer_value != 0)
6162 ReferenceValue = pointer_value;
6163
6164 const char *name = GuessCstringPointer(ReferenceValue, info);
6165 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006166 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006167 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6168 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006169 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006170 info->class_name = nullptr;
6171 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6172 info->selector_name = name;
6173 } else
6174 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6175 return name;
6176 }
6177
6178 // Lastly look for an indirect symbol with this ReferenceValue which is in
6179 // a literal pool. If found return that symbol name.
6180 name = GuessIndirectSymbol(ReferenceValue, info);
6181 if (name) {
6182 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6183 return name;
6184 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006185
6186 return nullptr;
6187}
6188
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006189// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006190// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006191// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6192// is created and returns the symbol name that matches the ReferenceValue or
6193// nullptr if none. The ReferenceType is passed in for the IN type of
6194// reference the instruction is making from the values in defined in the header
6195// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6196// Out type and the ReferenceName will also be set which is added as a comment
6197// to the disassembled instruction.
6198//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006199// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006200// returned through ReferenceName and ReferenceType is set to
6201// LLVMDisassembler_ReferenceType_DeMangled_Name .
6202//
6203// When this is called to get a symbol name for a branch target then the
6204// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6205// SymbolValue will be looked for in the indirect symbol table to determine if
6206// it is an address for a symbol stub. If so then the symbol name for that
6207// stub is returned indirectly through ReferenceName and then ReferenceType is
6208// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6209//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006210// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006211// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6212// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6213// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006214// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006215static const char *SymbolizerSymbolLookUp(void *DisInfo,
6216 uint64_t ReferenceValue,
6217 uint64_t *ReferenceType,
6218 uint64_t ReferencePC,
6219 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006220 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006221 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006222 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006223 *ReferenceName = nullptr;
6224 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006225 return nullptr;
6226 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006227
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006228 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006229
Kevin Enderby85974882014-09-26 22:20:44 +00006230 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6231 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006232 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006233 method_reference(info, ReferenceType, ReferenceName);
6234 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6235 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006236 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006237 if (info->demangled_name != nullptr)
6238 free(info->demangled_name);
6239 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006240 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006241 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006242 if (info->demangled_name != nullptr) {
6243 *ReferenceName = info->demangled_name;
6244 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6245 } else
6246 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6247 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006248 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6249 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6250 *ReferenceName =
6251 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006252 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006253 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006254 else
6255 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006256 // If this is arm64 and the reference is an adrp instruction save the
6257 // instruction, passed in ReferenceValue and the address of the instruction
6258 // for use later if we see and add immediate instruction.
6259 } else if (info->O->getArch() == Triple::aarch64 &&
6260 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6261 info->adrp_inst = ReferenceValue;
6262 info->adrp_addr = ReferencePC;
6263 SymbolName = nullptr;
6264 *ReferenceName = nullptr;
6265 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6266 // If this is arm64 and reference is an add immediate instruction and we
6267 // have
6268 // seen an adrp instruction just before it and the adrp's Xd register
6269 // matches
6270 // this add's Xn register reconstruct the value being referenced and look to
6271 // see if it is a literal pointer. Note the add immediate instruction is
6272 // passed in ReferenceValue.
6273 } else if (info->O->getArch() == Triple::aarch64 &&
6274 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6275 ReferencePC - 4 == info->adrp_addr &&
6276 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6277 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6278 uint32_t addxri_inst;
6279 uint64_t adrp_imm, addxri_imm;
6280
6281 adrp_imm =
6282 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6283 if (info->adrp_inst & 0x0200000)
6284 adrp_imm |= 0xfffffffffc000000LL;
6285
6286 addxri_inst = ReferenceValue;
6287 addxri_imm = (addxri_inst >> 10) & 0xfff;
6288 if (((addxri_inst >> 22) & 0x3) == 1)
6289 addxri_imm <<= 12;
6290
6291 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6292 (adrp_imm << 12) + addxri_imm;
6293
6294 *ReferenceName =
6295 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6296 if (*ReferenceName == nullptr)
6297 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6298 // If this is arm64 and the reference is a load register instruction and we
6299 // have seen an adrp instruction just before it and the adrp's Xd register
6300 // matches this add's Xn register reconstruct the value being referenced and
6301 // look to see if it is a literal pointer. Note the load register
6302 // instruction is passed in ReferenceValue.
6303 } else if (info->O->getArch() == Triple::aarch64 &&
6304 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6305 ReferencePC - 4 == info->adrp_addr &&
6306 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6307 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6308 uint32_t ldrxui_inst;
6309 uint64_t adrp_imm, ldrxui_imm;
6310
6311 adrp_imm =
6312 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6313 if (info->adrp_inst & 0x0200000)
6314 adrp_imm |= 0xfffffffffc000000LL;
6315
6316 ldrxui_inst = ReferenceValue;
6317 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6318
6319 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6320 (adrp_imm << 12) + (ldrxui_imm << 3);
6321
6322 *ReferenceName =
6323 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6324 if (*ReferenceName == nullptr)
6325 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6326 }
6327 // If this arm64 and is an load register (PC-relative) instruction the
6328 // ReferenceValue is the PC plus the immediate value.
6329 else if (info->O->getArch() == Triple::aarch64 &&
6330 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6331 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6332 *ReferenceName =
6333 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6334 if (*ReferenceName == nullptr)
6335 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006336 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006337 if (info->demangled_name != nullptr)
6338 free(info->demangled_name);
6339 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006340 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006341 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006342 if (info->demangled_name != nullptr) {
6343 *ReferenceName = info->demangled_name;
6344 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6345 }
6346 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006347 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006348 *ReferenceName = nullptr;
6349 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6350 }
6351
6352 return SymbolName;
6353}
6354
Kevin Enderbybf246f52014-09-24 23:08:22 +00006355/// \brief Emits the comments that are stored in the CommentStream.
6356/// Each comment in the CommentStream must end with a newline.
6357static void emitComments(raw_svector_ostream &CommentStream,
6358 SmallString<128> &CommentsToEmit,
6359 formatted_raw_ostream &FormattedOS,
6360 const MCAsmInfo &MAI) {
6361 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006362 StringRef Comments = CommentsToEmit.str();
6363 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006364 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006365 unsigned CommentColumn = MAI.getCommentColumn();
6366 bool IsFirst = true;
6367 while (!Comments.empty()) {
6368 if (!IsFirst)
6369 FormattedOS << '\n';
6370 // Emit a line of comments.
6371 FormattedOS.PadToColumn(CommentColumn);
6372 size_t Position = Comments.find('\n');
6373 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6374 // Move after the newline character.
6375 Comments = Comments.substr(Position + 1);
6376 IsFirst = false;
6377 }
6378 FormattedOS.flush();
6379
6380 // Tell the comment stream that the vector changed underneath it.
6381 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006382}
6383
Kevin Enderby95df54c2015-02-04 01:01:38 +00006384static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6385 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006386 const char *McpuDefault = nullptr;
6387 const Target *ThumbTarget = nullptr;
6388 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006389 if (!TheTarget) {
6390 // GetTarget prints out stuff.
6391 return;
6392 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006393 if (MCPU.empty() && McpuDefault)
6394 MCPU = McpuDefault;
6395
Ahmed Charles56440fd2014-03-06 05:51:42 +00006396 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006397 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006398 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006399 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006400
Kevin Enderbyc9595622014-08-06 23:24:41 +00006401 // Package up features to be passed to target/subtarget
6402 std::string FeaturesStr;
6403 if (MAttrs.size()) {
6404 SubtargetFeatures Features;
6405 for (unsigned i = 0; i != MAttrs.size(); ++i)
6406 Features.AddFeature(MAttrs[i]);
6407 FeaturesStr = Features.getString();
6408 }
6409
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006410 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006411 std::unique_ptr<const MCRegisterInfo> MRI(
6412 TheTarget->createMCRegInfo(TripleName));
6413 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006414 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006415 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006416 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006417 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006418 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006419 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006420 std::unique_ptr<MCSymbolizer> Symbolizer;
6421 struct DisassembleInfo SymbolizerInfo;
6422 std::unique_ptr<MCRelocationInfo> RelInfo(
6423 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6424 if (RelInfo) {
6425 Symbolizer.reset(TheTarget->createMCSymbolizer(
6426 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006427 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006428 DisAsm->setSymbolizer(std::move(Symbolizer));
6429 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006430 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006431 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006432 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006433 // Set the display preference for hex vs. decimal immediates.
6434 IP->setPrintImmHex(PrintImmHex);
6435 // Comment stream and backing vector.
6436 SmallString<128> CommentsToEmit;
6437 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006438 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6439 // if it is done then arm64 comments for string literals don't get printed
6440 // and some constant get printed instead and not setting it causes intel
6441 // (32-bit and 64-bit) comments printed with different spacing before the
6442 // comment causing different diffs with the 'C' disassembler library API.
6443 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006444
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006445 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006446 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006447 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006448 return;
6449 }
6450
Tim Northover09ca33e2016-04-22 23:23:31 +00006451 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006452 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6453 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6454 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006455 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006456 std::unique_ptr<MCInstPrinter> ThumbIP;
6457 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006458 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6459 struct DisassembleInfo ThumbSymbolizerInfo;
6460 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006461 if (ThumbTarget) {
6462 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6463 ThumbAsmInfo.reset(
6464 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6465 ThumbSTI.reset(
6466 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6467 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6468 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006469 MCContext *PtrThumbCtx = ThumbCtx.get();
6470 ThumbRelInfo.reset(
6471 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6472 if (ThumbRelInfo) {
6473 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6474 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006475 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006476 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6477 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006478 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6479 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006480 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6481 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006482 // Set the display preference for hex vs. decimal immediates.
6483 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006484 }
6485
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006486 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006487 errs() << "error: couldn't initialize disassembler for target "
6488 << ThumbTripleName << '\n';
6489 return;
6490 }
6491
Charles Davis8bdfafd2013-09-01 04:28:48 +00006492 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006493
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006494 // FIXME: Using the -cfg command line option, this code used to be able to
6495 // annotate relocations with the referenced symbol's name, and if this was
6496 // inside a __[cf]string section, the data it points to. This is now replaced
6497 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006498 std::vector<SectionRef> Sections;
6499 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006500 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006501 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006502
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006503 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006504 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006505
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006506 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006507 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006508
Kevin Enderby273ae012013-06-06 17:20:50 +00006509 // Build a data in code table that is sorted on by the address of each entry.
6510 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006511 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006512 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006513 else
6514 BaseAddress = BaseSegmentAddress;
6515 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006516 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006517 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006518 uint32_t Offset;
6519 DI->getOffset(Offset);
6520 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6521 }
6522 array_pod_sort(Dices.begin(), Dices.end());
6523
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006524#ifndef NDEBUG
6525 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6526#else
6527 raw_ostream &DebugOut = nulls();
6528#endif
6529
Ahmed Charles56440fd2014-03-06 05:51:42 +00006530 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006531 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006532 // Try to find debug info and set up the DIContext for it.
6533 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006534 // A separate DSym file path was specified, parse it as a macho file,
6535 // get the sections and supply it to the section name parsing machinery.
6536 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006537 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006538 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006539 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006540 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006541 return;
6542 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006543 DbgObj =
6544 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6545 .get()
6546 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006547 }
6548
Eric Christopher7370b552012-11-12 21:40:38 +00006549 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006550 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006551 }
6552
Colin LeMahieufcc32762015-07-29 19:08:10 +00006553 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006554 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006555
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006556 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006557 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006558 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6559 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006560
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006561 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006562
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006563 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006564 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006565 continue;
6566
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006567 StringRef BytesStr;
6568 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006569 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6570 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006571 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006572
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006573 bool symbolTableWorked = false;
6574
Kevin Enderbybf246f52014-09-24 23:08:22 +00006575 // Create a map of symbol addresses to symbol names for use by
6576 // the SymbolizerSymbolLookUp() routine.
6577 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006578 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006579 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006580 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006581 if (!STOrErr)
6582 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006583 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006584 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6585 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006586 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006587 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006588 if (!SymNameOrErr)
6589 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006590 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006591 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006592 if (!DisSymName.empty() && DisSymName == SymName)
6593 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006594 }
6595 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006596 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006597 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6598 return;
6599 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006600 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006601 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006602 SymbolizerInfo.O = MachOOF;
6603 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006604 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006605 SymbolizerInfo.Sections = &Sections;
6606 SymbolizerInfo.class_name = nullptr;
6607 SymbolizerInfo.selector_name = nullptr;
6608 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006609 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006610 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006611 SymbolizerInfo.adrp_addr = 0;
6612 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006613 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006614 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006615 ThumbSymbolizerInfo.O = MachOOF;
6616 ThumbSymbolizerInfo.S = Sections[SectIdx];
6617 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6618 ThumbSymbolizerInfo.Sections = &Sections;
6619 ThumbSymbolizerInfo.class_name = nullptr;
6620 ThumbSymbolizerInfo.selector_name = nullptr;
6621 ThumbSymbolizerInfo.method = nullptr;
6622 ThumbSymbolizerInfo.demangled_name = nullptr;
6623 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006624 ThumbSymbolizerInfo.adrp_addr = 0;
6625 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006626
Kevin Enderby4b627be2016-04-28 20:14:13 +00006627 unsigned int Arch = MachOOF->getArch();
6628
Tim Northoverf203ab52016-07-14 22:13:32 +00006629 // Skip all symbols if this is a stubs file.
6630 if (Bytes.size() == 0)
6631 return;
6632
Kevin Enderbyc138da32017-02-06 18:43:18 +00006633 // If the section has symbols but no symbol at the start of the section
6634 // these are used to make sure the bytes before the first symbol are
6635 // disassembled.
6636 bool FirstSymbol = true;
6637 bool FirstSymbolAtSectionStart = true;
6638
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006639 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006640 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006641 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006642 if (!SymNameOrErr)
6643 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006644 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006645
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006646 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006647 if (!STOrErr)
6648 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006649 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006650 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006651 continue;
6652
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006653 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006654 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006655 if (!containsSym) {
6656 if (!DisSymName.empty() && DisSymName == SymName) {
6657 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6658 return;
6659 }
6660 continue;
6661 }
6662 // The __mh_execute_header is special and we need to deal with that fact
6663 // this symbol is before the start of the (__TEXT,__text) section and at the
6664 // address of the start of the __TEXT segment. This is because this symbol
6665 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6666 // start of the section in a standard MH_EXECUTE filetype.
6667 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6668 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6669 return;
6670 }
Tim Northoverfbefee32016-07-14 23:13:03 +00006671 // When this code is trying to disassemble a symbol at a time and in the
6672 // case there is only the __mh_execute_header symbol left as in a stripped
6673 // executable, we need to deal with this by ignoring this symbol so the
6674 // whole section is disassembled and this symbol is then not displayed.
6675 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6676 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6677 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006678 continue;
6679
Kevin Enderby6a221752015-03-17 17:10:57 +00006680 // If we are only disassembling one symbol see if this is that symbol.
6681 if (!DisSymName.empty() && DisSymName != SymName)
6682 continue;
6683
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006684 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00006685 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00006686 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006687 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006688 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006689
Tim Northoverf203ab52016-07-14 22:13:32 +00006690 if (Start > SectSize) {
6691 outs() << "section data ends, " << SymName
6692 << " lies outside valid range\n";
6693 return;
6694 }
6695
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006696 // Stop disassembling either at the beginning of the next symbol or at
6697 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006698 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006699 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006700 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006701 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006702 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006703 if (!STOrErr)
6704 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006705 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006706 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006707 containsNextSym =
6708 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006709 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006710 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006711 break;
6712 }
6713 ++NextSymIdx;
6714 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006715
Tim Northoverf203ab52016-07-14 22:13:32 +00006716 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006717 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006718
6719 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006720
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006721 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006722 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6723
6724 // We only need the dedicated Thumb target if there's a real choice
6725 // (i.e. we're not targeting M-class) and the function is Thumb.
6726 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006727
Kevin Enderbyc138da32017-02-06 18:43:18 +00006728 // If we are not specifying a symbol to start disassembly with and this
6729 // is the first symbol in the section but not at the start of the section
6730 // then move the disassembly index to the start of the section and
6731 // don't print the symbol name just yet. This is so the bytes before the
6732 // first symbol are disassembled.
6733 uint64_t SymbolStart = Start;
6734 if (DisSymName.empty() && FirstSymbol && Start != 0) {
6735 FirstSymbolAtSectionStart = false;
6736 Start = 0;
6737 }
6738 else
6739 outs() << SymName << ":\n";
6740
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006741 DILineInfo lastLine;
6742 for (uint64_t Index = Start; Index < End; Index += Size) {
6743 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006744
Kevin Enderbyc138da32017-02-06 18:43:18 +00006745 // If this is the first symbol in the section and it was not at the
6746 // start of the section, see if we are at its Index now and if so print
6747 // the symbol name.
6748 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
6749 outs() << SymName << ":\n";
6750
Kevin Enderbybf246f52014-09-24 23:08:22 +00006751 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006752 if (!NoLeadingAddr) {
6753 if (FullLeadingAddr) {
6754 if (MachOOF->is64Bit())
6755 outs() << format("%016" PRIx64, PC);
6756 else
6757 outs() << format("%08" PRIx64, PC);
6758 } else {
6759 outs() << format("%8" PRIx64 ":", PC);
6760 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006761 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006762 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006763 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006764
6765 // Check the data in code table here to see if this is data not an
6766 // instruction to be disassembled.
6767 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006768 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006769 dice_table_iterator DTI =
6770 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6771 compareDiceTableEntries);
6772 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006773 uint16_t Length;
6774 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006775 uint16_t Kind;
6776 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006777 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006778 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6779 (PC == (DTI->first + Length - 1)) && (Length & 1))
6780 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006781 continue;
6782 }
6783
Kevin Enderbybf246f52014-09-24 23:08:22 +00006784 SmallVector<char, 64> AnnotationsBytes;
6785 raw_svector_ostream Annotations(AnnotationsBytes);
6786
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006787 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006788 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006789 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006790 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006791 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006792 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006793 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006794 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006795 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006796 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006797 }
6798 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006799 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006800 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006801 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006802 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006803 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006804 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006805
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006806 // Print debug info.
6807 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006808 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006809 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006810 if (dli != lastLine && dli.Line != 0)
6811 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6812 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006813 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006814 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006815 outs() << "\n";
6816 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006817 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006818 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006819 outs() << format("\t.byte 0x%02x #bad opcode\n",
6820 *(Bytes.data() + Index) & 0xff);
6821 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006822 } else if (Arch == Triple::aarch64 ||
6823 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006824 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6825 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6826 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6827 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6828 outs() << format("\t.long\t0x%08x\n", opcode);
6829 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006830 } else if (Arch == Triple::arm) {
6831 assert(IsThumb && "ARM mode should have been dealt with above");
6832 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6833 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6834 outs() << format("\t.short\t0x%04x\n", opcode);
6835 Size = 2;
6836 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006837 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6838 if (Size == 0)
6839 Size = 1; // skip illegible bytes
6840 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006841 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006842 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00006843 // Now that we are done disassembled the first symbol set the bool that
6844 // were doing this to false.
6845 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006846 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006847 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006848 // Reading the symbol table didn't work, disassemble the whole section.
6849 uint64_t SectAddress = Sections[SectIdx].getAddress();
6850 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006851 uint64_t InstSize;
6852 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006853 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006854
Kevin Enderbybf246f52014-09-24 23:08:22 +00006855 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00006856 SmallVector<char, 64> AnnotationsBytes;
6857 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006858 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00006859 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006860 if (!NoLeadingAddr) {
6861 if (FullLeadingAddr) {
6862 if (MachOOF->is64Bit())
6863 outs() << format("%016" PRIx64, PC);
6864 else
6865 outs() << format("%08" PRIx64, PC);
6866 } else {
6867 outs() << format("%8" PRIx64 ":", PC);
6868 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006869 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006870 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006871 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006872 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006873 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00006874 StringRef AnnotationsStr = Annotations.str();
6875 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006876 outs() << "\n";
6877 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006878 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006879 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006880 outs() << format("\t.byte 0x%02x #bad opcode\n",
6881 *(Bytes.data() + Index) & 0xff);
6882 InstSize = 1; // skip exactly one illegible byte and move on.
6883 } else {
6884 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6885 if (InstSize == 0)
6886 InstSize = 1; // skip illegible bytes
6887 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006888 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006889 }
6890 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006891 // The TripleName's need to be reset if we are called again for a different
6892 // archtecture.
6893 TripleName = "";
6894 ThumbTripleName = "";
6895
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006896 if (SymbolizerInfo.method != nullptr)
6897 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006898 if (SymbolizerInfo.demangled_name != nullptr)
6899 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006900 if (ThumbSymbolizerInfo.method != nullptr)
6901 free(ThumbSymbolizerInfo.method);
6902 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6903 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006904 }
6905}
Tim Northover4bd286a2014-08-01 13:07:19 +00006906
Tim Northover39c70bb2014-08-12 11:52:59 +00006907//===----------------------------------------------------------------------===//
6908// __compact_unwind section dumping
6909//===----------------------------------------------------------------------===//
6910
Tim Northover4bd286a2014-08-01 13:07:19 +00006911namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006912
6913template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006914 using llvm::support::little;
6915 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006916
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006917 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6918 Buf += sizeof(T);
6919 return Val;
6920}
Tim Northover39c70bb2014-08-12 11:52:59 +00006921
Tim Northover4bd286a2014-08-01 13:07:19 +00006922struct CompactUnwindEntry {
6923 uint32_t OffsetInSection;
6924
6925 uint64_t FunctionAddr;
6926 uint32_t Length;
6927 uint32_t CompactEncoding;
6928 uint64_t PersonalityAddr;
6929 uint64_t LSDAAddr;
6930
6931 RelocationRef FunctionReloc;
6932 RelocationRef PersonalityReloc;
6933 RelocationRef LSDAReloc;
6934
6935 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006936 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006937 if (Is64)
6938 read<uint64_t>(Contents.data() + Offset);
6939 else
6940 read<uint32_t>(Contents.data() + Offset);
6941 }
6942
6943private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006944 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006945 FunctionAddr = readNext<UIntPtr>(Buf);
6946 Length = readNext<uint32_t>(Buf);
6947 CompactEncoding = readNext<uint32_t>(Buf);
6948 PersonalityAddr = readNext<UIntPtr>(Buf);
6949 LSDAAddr = readNext<UIntPtr>(Buf);
6950 }
6951};
6952}
6953
6954/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6955/// and data being relocated, determine the best base Name and Addend to use for
6956/// display purposes.
6957///
6958/// 1. An Extern relocation will directly reference a symbol (and the data is
6959/// then already an addend), so use that.
6960/// 2. Otherwise the data is an offset in the object file's layout; try to find
6961// a symbol before it in the same section, and use the offset from there.
6962/// 3. Finally, if all that fails, fall back to an offset from the start of the
6963/// referenced section.
6964static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6965 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006966 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006967 StringRef &Name, uint64_t &Addend) {
6968 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006969 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006970 if (!NameOrErr)
6971 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006972 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006973 Addend = Addr;
6974 return;
6975 }
6976
6977 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006978 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006979
Rafael Espindola80291272014-10-08 15:28:58 +00006980 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006981
6982 auto Sym = Symbols.upper_bound(Addr);
6983 if (Sym == Symbols.begin()) {
6984 // The first symbol in the object is after this reference, the best we can
6985 // do is section-relative notation.
6986 RelocSection.getName(Name);
6987 Addend = Addr - SectionAddr;
6988 return;
6989 }
6990
6991 // Go back one so that SymbolAddress <= Addr.
6992 --Sym;
6993
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006994 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006995 if (!SectOrErr)
6996 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006997 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006998 if (RelocSection == *SymSection) {
6999 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007000 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007001 if (!NameOrErr)
7002 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007003 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007004 Addend = Addr - Sym->first;
7005 return;
7006 }
7007
7008 // There is a symbol before this reference, but it's in a different
7009 // section. Probably not helpful to mention it, so use the section name.
7010 RelocSection.getName(Name);
7011 Addend = Addr - SectionAddr;
7012}
7013
7014static void printUnwindRelocDest(const MachOObjectFile *Obj,
7015 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007016 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007017 StringRef Name;
7018 uint64_t Addend;
7019
Rafael Espindola854038e2015-06-26 14:51:16 +00007020 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007021 return;
7022
Tim Northover4bd286a2014-08-01 13:07:19 +00007023 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7024
7025 outs() << Name;
7026 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007027 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007028}
7029
7030static void
7031printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7032 std::map<uint64_t, SymbolRef> &Symbols,
7033 const SectionRef &CompactUnwind) {
7034
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007035 if (!Obj->isLittleEndian()) {
7036 outs() << "Skipping big-endian __compact_unwind section\n";
7037 return;
7038 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007039
7040 bool Is64 = Obj->is64Bit();
7041 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7042 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7043
7044 StringRef Contents;
7045 CompactUnwind.getContents(Contents);
7046
7047 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7048
7049 // First populate the initial raw offsets, encodings and so on from the entry.
7050 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7051 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7052 CompactUnwinds.push_back(Entry);
7053 }
7054
7055 // Next we need to look at the relocations to find out what objects are
7056 // actually being referred to.
7057 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007058 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007059
7060 uint32_t EntryIdx = RelocAddress / EntrySize;
7061 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7062 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7063
7064 if (OffsetInEntry == 0)
7065 Entry.FunctionReloc = Reloc;
7066 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7067 Entry.PersonalityReloc = Reloc;
7068 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7069 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007070 else {
7071 outs() << "Invalid relocation in __compact_unwind section\n";
7072 return;
7073 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007074 }
7075
7076 // Finally, we're ready to print the data we've gathered.
7077 outs() << "Contents of __compact_unwind section:\n";
7078 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007079 outs() << " Entry at offset "
7080 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007081
7082 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007083 outs() << " start: " << format("0x%" PRIx64,
7084 Entry.FunctionAddr) << ' ';
7085 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007086 outs() << '\n';
7087
7088 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007089 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7090 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007091 // 3. The 32-bit compact encoding.
7092 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007093 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007094
7095 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007096 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007097 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007098 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007099 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7100 Entry.PersonalityAddr);
7101 outs() << '\n';
7102 }
7103
7104 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007105 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007106 outs() << " LSDA: " << format("0x%" PRIx64,
7107 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007108 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7109 outs() << '\n';
7110 }
7111 }
7112}
7113
Tim Northover39c70bb2014-08-12 11:52:59 +00007114//===----------------------------------------------------------------------===//
7115// __unwind_info section dumping
7116//===----------------------------------------------------------------------===//
7117
7118static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7119 const char *Pos = PageStart;
7120 uint32_t Kind = readNext<uint32_t>(Pos);
7121 (void)Kind;
7122 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7123
7124 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7125 uint16_t NumEntries = readNext<uint16_t>(Pos);
7126
7127 Pos = PageStart + EntriesStart;
7128 for (unsigned i = 0; i < NumEntries; ++i) {
7129 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7130 uint32_t Encoding = readNext<uint32_t>(Pos);
7131
7132 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007133 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7134 << ", "
7135 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007136 }
7137}
7138
7139static void printCompressedSecondLevelUnwindPage(
7140 const char *PageStart, uint32_t FunctionBase,
7141 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7142 const char *Pos = PageStart;
7143 uint32_t Kind = readNext<uint32_t>(Pos);
7144 (void)Kind;
7145 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7146
7147 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7148 uint16_t NumEntries = readNext<uint16_t>(Pos);
7149
7150 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7151 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007152 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7153 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007154
7155 Pos = PageStart + EntriesStart;
7156 for (unsigned i = 0; i < NumEntries; ++i) {
7157 uint32_t Entry = readNext<uint32_t>(Pos);
7158 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7159 uint32_t EncodingIdx = Entry >> 24;
7160
7161 uint32_t Encoding;
7162 if (EncodingIdx < CommonEncodings.size())
7163 Encoding = CommonEncodings[EncodingIdx];
7164 else
7165 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7166
7167 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007168 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7169 << ", "
7170 << "encoding[" << EncodingIdx
7171 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007172 }
7173}
7174
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007175static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7176 std::map<uint64_t, SymbolRef> &Symbols,
7177 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007178
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007179 if (!Obj->isLittleEndian()) {
7180 outs() << "Skipping big-endian __unwind_info section\n";
7181 return;
7182 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007183
7184 outs() << "Contents of __unwind_info section:\n";
7185
7186 StringRef Contents;
7187 UnwindInfo.getContents(Contents);
7188 const char *Pos = Contents.data();
7189
7190 //===----------------------------------
7191 // Section header
7192 //===----------------------------------
7193
7194 uint32_t Version = readNext<uint32_t>(Pos);
7195 outs() << " Version: "
7196 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007197 if (Version != 1) {
7198 outs() << " Skipping section with unknown version\n";
7199 return;
7200 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007201
7202 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7203 outs() << " Common encodings array section offset: "
7204 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7205 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7206 outs() << " Number of common encodings in array: "
7207 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7208
7209 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7210 outs() << " Personality function array section offset: "
7211 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7212 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7213 outs() << " Number of personality functions in array: "
7214 << format("0x%" PRIx32, NumPersonalities) << '\n';
7215
7216 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7217 outs() << " Index array section offset: "
7218 << format("0x%" PRIx32, IndicesStart) << '\n';
7219 uint32_t NumIndices = readNext<uint32_t>(Pos);
7220 outs() << " Number of indices in array: "
7221 << format("0x%" PRIx32, NumIndices) << '\n';
7222
7223 //===----------------------------------
7224 // A shared list of common encodings
7225 //===----------------------------------
7226
7227 // These occupy indices in the range [0, N] whenever an encoding is referenced
7228 // from a compressed 2nd level index table. In practice the linker only
7229 // creates ~128 of these, so that indices are available to embed encodings in
7230 // the 2nd level index.
7231
7232 SmallVector<uint32_t, 64> CommonEncodings;
7233 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7234 Pos = Contents.data() + CommonEncodingsStart;
7235 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7236 uint32_t Encoding = readNext<uint32_t>(Pos);
7237 CommonEncodings.push_back(Encoding);
7238
7239 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7240 << '\n';
7241 }
7242
Tim Northover39c70bb2014-08-12 11:52:59 +00007243 //===----------------------------------
7244 // Personality functions used in this executable
7245 //===----------------------------------
7246
7247 // There should be only a handful of these (one per source language,
7248 // roughly). Particularly since they only get 2 bits in the compact encoding.
7249
7250 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7251 Pos = Contents.data() + PersonalitiesStart;
7252 for (unsigned i = 0; i < NumPersonalities; ++i) {
7253 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7254 outs() << " personality[" << i + 1
7255 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7256 }
7257
7258 //===----------------------------------
7259 // The level 1 index entries
7260 //===----------------------------------
7261
7262 // These specify an approximate place to start searching for the more detailed
7263 // information, sorted by PC.
7264
7265 struct IndexEntry {
7266 uint32_t FunctionOffset;
7267 uint32_t SecondLevelPageStart;
7268 uint32_t LSDAStart;
7269 };
7270
7271 SmallVector<IndexEntry, 4> IndexEntries;
7272
7273 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7274 Pos = Contents.data() + IndicesStart;
7275 for (unsigned i = 0; i < NumIndices; ++i) {
7276 IndexEntry Entry;
7277
7278 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7279 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7280 Entry.LSDAStart = readNext<uint32_t>(Pos);
7281 IndexEntries.push_back(Entry);
7282
7283 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007284 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7285 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007286 << "2nd level page offset="
7287 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007288 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007289 }
7290
Tim Northover39c70bb2014-08-12 11:52:59 +00007291 //===----------------------------------
7292 // Next come the LSDA tables
7293 //===----------------------------------
7294
7295 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7296 // the first top-level index's LSDAOffset to the last (sentinel).
7297
7298 outs() << " LSDA descriptors:\n";
7299 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7300 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7301 (2 * sizeof(uint32_t));
7302 for (int i = 0; i < NumLSDAs; ++i) {
7303 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7304 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7305 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007306 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7307 << ", "
7308 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007309 }
7310
7311 //===----------------------------------
7312 // Finally, the 2nd level indices
7313 //===----------------------------------
7314
7315 // Generally these are 4K in size, and have 2 possible forms:
7316 // + Regular stores up to 511 entries with disparate encodings
7317 // + Compressed stores up to 1021 entries if few enough compact encoding
7318 // values are used.
7319 outs() << " Second level indices:\n";
7320 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7321 // The final sentinel top-level index has no associated 2nd level page
7322 if (IndexEntries[i].SecondLevelPageStart == 0)
7323 break;
7324
7325 outs() << " Second level index[" << i << "]: "
7326 << "offset in section="
7327 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7328 << ", "
7329 << "base function offset="
7330 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7331
7332 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007333 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007334 if (Kind == 2)
7335 printRegularSecondLevelUnwindPage(Pos);
7336 else if (Kind == 3)
7337 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7338 CommonEncodings);
7339 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007340 outs() << " Skipping 2nd level page with unknown kind " << Kind
7341 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007342 }
7343}
7344
Tim Northover4bd286a2014-08-01 13:07:19 +00007345void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7346 std::map<uint64_t, SymbolRef> Symbols;
7347 for (const SymbolRef &SymRef : Obj->symbols()) {
7348 // Discard any undefined or absolute symbols. They're not going to take part
7349 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007350 auto SectOrErr = SymRef.getSection();
7351 if (!SectOrErr) {
7352 // TODO: Actually report errors helpfully.
7353 consumeError(SectOrErr.takeError());
7354 continue;
7355 }
7356 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007357 if (Section == Obj->section_end())
7358 continue;
7359
Rafael Espindoladea00162015-07-03 17:44:18 +00007360 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007361 Symbols.insert(std::make_pair(Addr, SymRef));
7362 }
7363
7364 for (const SectionRef &Section : Obj->sections()) {
7365 StringRef SectName;
7366 Section.getName(SectName);
7367 if (SectName == "__compact_unwind")
7368 printMachOCompactUnwindSection(Obj, Symbols, Section);
7369 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007370 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007371 }
7372}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007373
7374static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7375 uint32_t cpusubtype, uint32_t filetype,
7376 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7377 bool verbose) {
7378 outs() << "Mach header\n";
7379 outs() << " magic cputype cpusubtype caps filetype ncmds "
7380 "sizeofcmds flags\n";
7381 if (verbose) {
7382 if (magic == MachO::MH_MAGIC)
7383 outs() << " MH_MAGIC";
7384 else if (magic == MachO::MH_MAGIC_64)
7385 outs() << "MH_MAGIC_64";
7386 else
7387 outs() << format(" 0x%08" PRIx32, magic);
7388 switch (cputype) {
7389 case MachO::CPU_TYPE_I386:
7390 outs() << " I386";
7391 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7392 case MachO::CPU_SUBTYPE_I386_ALL:
7393 outs() << " ALL";
7394 break;
7395 default:
7396 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7397 break;
7398 }
7399 break;
7400 case MachO::CPU_TYPE_X86_64:
7401 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007402 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7403 case MachO::CPU_SUBTYPE_X86_64_ALL:
7404 outs() << " ALL";
7405 break;
7406 case MachO::CPU_SUBTYPE_X86_64_H:
7407 outs() << " Haswell";
7408 break;
7409 default:
7410 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7411 break;
7412 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007413 break;
7414 case MachO::CPU_TYPE_ARM:
7415 outs() << " ARM";
7416 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7417 case MachO::CPU_SUBTYPE_ARM_ALL:
7418 outs() << " ALL";
7419 break;
7420 case MachO::CPU_SUBTYPE_ARM_V4T:
7421 outs() << " V4T";
7422 break;
7423 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7424 outs() << " V5TEJ";
7425 break;
7426 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7427 outs() << " XSCALE";
7428 break;
7429 case MachO::CPU_SUBTYPE_ARM_V6:
7430 outs() << " V6";
7431 break;
7432 case MachO::CPU_SUBTYPE_ARM_V6M:
7433 outs() << " V6M";
7434 break;
7435 case MachO::CPU_SUBTYPE_ARM_V7:
7436 outs() << " V7";
7437 break;
7438 case MachO::CPU_SUBTYPE_ARM_V7EM:
7439 outs() << " V7EM";
7440 break;
7441 case MachO::CPU_SUBTYPE_ARM_V7K:
7442 outs() << " V7K";
7443 break;
7444 case MachO::CPU_SUBTYPE_ARM_V7M:
7445 outs() << " V7M";
7446 break;
7447 case MachO::CPU_SUBTYPE_ARM_V7S:
7448 outs() << " V7S";
7449 break;
7450 default:
7451 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7452 break;
7453 }
7454 break;
7455 case MachO::CPU_TYPE_ARM64:
7456 outs() << " ARM64";
7457 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7458 case MachO::CPU_SUBTYPE_ARM64_ALL:
7459 outs() << " ALL";
7460 break;
7461 default:
7462 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7463 break;
7464 }
7465 break;
7466 case MachO::CPU_TYPE_POWERPC:
7467 outs() << " PPC";
7468 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7469 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7470 outs() << " ALL";
7471 break;
7472 default:
7473 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7474 break;
7475 }
7476 break;
7477 case MachO::CPU_TYPE_POWERPC64:
7478 outs() << " PPC64";
7479 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7480 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7481 outs() << " ALL";
7482 break;
7483 default:
7484 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7485 break;
7486 }
7487 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007488 default:
7489 outs() << format(" %7d", cputype);
7490 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7491 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007492 }
7493 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007494 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007495 } else {
7496 outs() << format(" 0x%02" PRIx32,
7497 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7498 }
7499 switch (filetype) {
7500 case MachO::MH_OBJECT:
7501 outs() << " OBJECT";
7502 break;
7503 case MachO::MH_EXECUTE:
7504 outs() << " EXECUTE";
7505 break;
7506 case MachO::MH_FVMLIB:
7507 outs() << " FVMLIB";
7508 break;
7509 case MachO::MH_CORE:
7510 outs() << " CORE";
7511 break;
7512 case MachO::MH_PRELOAD:
7513 outs() << " PRELOAD";
7514 break;
7515 case MachO::MH_DYLIB:
7516 outs() << " DYLIB";
7517 break;
7518 case MachO::MH_DYLIB_STUB:
7519 outs() << " DYLIB_STUB";
7520 break;
7521 case MachO::MH_DYLINKER:
7522 outs() << " DYLINKER";
7523 break;
7524 case MachO::MH_BUNDLE:
7525 outs() << " BUNDLE";
7526 break;
7527 case MachO::MH_DSYM:
7528 outs() << " DSYM";
7529 break;
7530 case MachO::MH_KEXT_BUNDLE:
7531 outs() << " KEXTBUNDLE";
7532 break;
7533 default:
7534 outs() << format(" %10u", filetype);
7535 break;
7536 }
7537 outs() << format(" %5u", ncmds);
7538 outs() << format(" %10u", sizeofcmds);
7539 uint32_t f = flags;
7540 if (f & MachO::MH_NOUNDEFS) {
7541 outs() << " NOUNDEFS";
7542 f &= ~MachO::MH_NOUNDEFS;
7543 }
7544 if (f & MachO::MH_INCRLINK) {
7545 outs() << " INCRLINK";
7546 f &= ~MachO::MH_INCRLINK;
7547 }
7548 if (f & MachO::MH_DYLDLINK) {
7549 outs() << " DYLDLINK";
7550 f &= ~MachO::MH_DYLDLINK;
7551 }
7552 if (f & MachO::MH_BINDATLOAD) {
7553 outs() << " BINDATLOAD";
7554 f &= ~MachO::MH_BINDATLOAD;
7555 }
7556 if (f & MachO::MH_PREBOUND) {
7557 outs() << " PREBOUND";
7558 f &= ~MachO::MH_PREBOUND;
7559 }
7560 if (f & MachO::MH_SPLIT_SEGS) {
7561 outs() << " SPLIT_SEGS";
7562 f &= ~MachO::MH_SPLIT_SEGS;
7563 }
7564 if (f & MachO::MH_LAZY_INIT) {
7565 outs() << " LAZY_INIT";
7566 f &= ~MachO::MH_LAZY_INIT;
7567 }
7568 if (f & MachO::MH_TWOLEVEL) {
7569 outs() << " TWOLEVEL";
7570 f &= ~MachO::MH_TWOLEVEL;
7571 }
7572 if (f & MachO::MH_FORCE_FLAT) {
7573 outs() << " FORCE_FLAT";
7574 f &= ~MachO::MH_FORCE_FLAT;
7575 }
7576 if (f & MachO::MH_NOMULTIDEFS) {
7577 outs() << " NOMULTIDEFS";
7578 f &= ~MachO::MH_NOMULTIDEFS;
7579 }
7580 if (f & MachO::MH_NOFIXPREBINDING) {
7581 outs() << " NOFIXPREBINDING";
7582 f &= ~MachO::MH_NOFIXPREBINDING;
7583 }
7584 if (f & MachO::MH_PREBINDABLE) {
7585 outs() << " PREBINDABLE";
7586 f &= ~MachO::MH_PREBINDABLE;
7587 }
7588 if (f & MachO::MH_ALLMODSBOUND) {
7589 outs() << " ALLMODSBOUND";
7590 f &= ~MachO::MH_ALLMODSBOUND;
7591 }
7592 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7593 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7594 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7595 }
7596 if (f & MachO::MH_CANONICAL) {
7597 outs() << " CANONICAL";
7598 f &= ~MachO::MH_CANONICAL;
7599 }
7600 if (f & MachO::MH_WEAK_DEFINES) {
7601 outs() << " WEAK_DEFINES";
7602 f &= ~MachO::MH_WEAK_DEFINES;
7603 }
7604 if (f & MachO::MH_BINDS_TO_WEAK) {
7605 outs() << " BINDS_TO_WEAK";
7606 f &= ~MachO::MH_BINDS_TO_WEAK;
7607 }
7608 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7609 outs() << " ALLOW_STACK_EXECUTION";
7610 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7611 }
7612 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7613 outs() << " DEAD_STRIPPABLE_DYLIB";
7614 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7615 }
7616 if (f & MachO::MH_PIE) {
7617 outs() << " PIE";
7618 f &= ~MachO::MH_PIE;
7619 }
7620 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7621 outs() << " NO_REEXPORTED_DYLIBS";
7622 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7623 }
7624 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7625 outs() << " MH_HAS_TLV_DESCRIPTORS";
7626 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7627 }
7628 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7629 outs() << " MH_NO_HEAP_EXECUTION";
7630 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7631 }
7632 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7633 outs() << " APP_EXTENSION_SAFE";
7634 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7635 }
7636 if (f != 0 || flags == 0)
7637 outs() << format(" 0x%08" PRIx32, f);
7638 } else {
7639 outs() << format(" 0x%08" PRIx32, magic);
7640 outs() << format(" %7d", cputype);
7641 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7642 outs() << format(" 0x%02" PRIx32,
7643 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7644 outs() << format(" %10u", filetype);
7645 outs() << format(" %5u", ncmds);
7646 outs() << format(" %10u", sizeofcmds);
7647 outs() << format(" 0x%08" PRIx32, flags);
7648 }
7649 outs() << "\n";
7650}
7651
Kevin Enderby956366c2014-08-29 22:30:52 +00007652static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7653 StringRef SegName, uint64_t vmaddr,
7654 uint64_t vmsize, uint64_t fileoff,
7655 uint64_t filesize, uint32_t maxprot,
7656 uint32_t initprot, uint32_t nsects,
7657 uint32_t flags, uint32_t object_size,
7658 bool verbose) {
7659 uint64_t expected_cmdsize;
7660 if (cmd == MachO::LC_SEGMENT) {
7661 outs() << " cmd LC_SEGMENT\n";
7662 expected_cmdsize = nsects;
7663 expected_cmdsize *= sizeof(struct MachO::section);
7664 expected_cmdsize += sizeof(struct MachO::segment_command);
7665 } else {
7666 outs() << " cmd LC_SEGMENT_64\n";
7667 expected_cmdsize = nsects;
7668 expected_cmdsize *= sizeof(struct MachO::section_64);
7669 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7670 }
7671 outs() << " cmdsize " << cmdsize;
7672 if (cmdsize != expected_cmdsize)
7673 outs() << " Inconsistent size\n";
7674 else
7675 outs() << "\n";
7676 outs() << " segname " << SegName << "\n";
7677 if (cmd == MachO::LC_SEGMENT_64) {
7678 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7679 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7680 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007681 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7682 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007683 }
7684 outs() << " fileoff " << fileoff;
7685 if (fileoff > object_size)
7686 outs() << " (past end of file)\n";
7687 else
7688 outs() << "\n";
7689 outs() << " filesize " << filesize;
7690 if (fileoff + filesize > object_size)
7691 outs() << " (past end of file)\n";
7692 else
7693 outs() << "\n";
7694 if (verbose) {
7695 if ((maxprot &
7696 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7697 MachO::VM_PROT_EXECUTE)) != 0)
7698 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7699 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007700 outs() << " maxprot ";
7701 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7702 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7703 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007704 }
7705 if ((initprot &
7706 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7707 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00007708 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007709 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00007710 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00007711 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7712 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7713 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007714 }
7715 } else {
7716 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7717 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7718 }
7719 outs() << " nsects " << nsects << "\n";
7720 if (verbose) {
7721 outs() << " flags";
7722 if (flags == 0)
7723 outs() << " (none)\n";
7724 else {
7725 if (flags & MachO::SG_HIGHVM) {
7726 outs() << " HIGHVM";
7727 flags &= ~MachO::SG_HIGHVM;
7728 }
7729 if (flags & MachO::SG_FVMLIB) {
7730 outs() << " FVMLIB";
7731 flags &= ~MachO::SG_FVMLIB;
7732 }
7733 if (flags & MachO::SG_NORELOC) {
7734 outs() << " NORELOC";
7735 flags &= ~MachO::SG_NORELOC;
7736 }
7737 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7738 outs() << " PROTECTED_VERSION_1";
7739 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7740 }
7741 if (flags)
7742 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7743 else
7744 outs() << "\n";
7745 }
7746 } else {
7747 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7748 }
7749}
7750
7751static void PrintSection(const char *sectname, const char *segname,
7752 uint64_t addr, uint64_t size, uint32_t offset,
7753 uint32_t align, uint32_t reloff, uint32_t nreloc,
7754 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7755 uint32_t cmd, const char *sg_segname,
7756 uint32_t filetype, uint32_t object_size,
7757 bool verbose) {
7758 outs() << "Section\n";
7759 outs() << " sectname " << format("%.16s\n", sectname);
7760 outs() << " segname " << format("%.16s", segname);
7761 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7762 outs() << " (does not match segment)\n";
7763 else
7764 outs() << "\n";
7765 if (cmd == MachO::LC_SEGMENT_64) {
7766 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7767 outs() << " size " << format("0x%016" PRIx64, size);
7768 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007769 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7770 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007771 }
7772 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7773 outs() << " (past end of file)\n";
7774 else
7775 outs() << "\n";
7776 outs() << " offset " << offset;
7777 if (offset > object_size)
7778 outs() << " (past end of file)\n";
7779 else
7780 outs() << "\n";
7781 uint32_t align_shifted = 1 << align;
7782 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7783 outs() << " reloff " << reloff;
7784 if (reloff > object_size)
7785 outs() << " (past end of file)\n";
7786 else
7787 outs() << "\n";
7788 outs() << " nreloc " << nreloc;
7789 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7790 outs() << " (past end of file)\n";
7791 else
7792 outs() << "\n";
7793 uint32_t section_type = flags & MachO::SECTION_TYPE;
7794 if (verbose) {
7795 outs() << " type";
7796 if (section_type == MachO::S_REGULAR)
7797 outs() << " S_REGULAR\n";
7798 else if (section_type == MachO::S_ZEROFILL)
7799 outs() << " S_ZEROFILL\n";
7800 else if (section_type == MachO::S_CSTRING_LITERALS)
7801 outs() << " S_CSTRING_LITERALS\n";
7802 else if (section_type == MachO::S_4BYTE_LITERALS)
7803 outs() << " S_4BYTE_LITERALS\n";
7804 else if (section_type == MachO::S_8BYTE_LITERALS)
7805 outs() << " S_8BYTE_LITERALS\n";
7806 else if (section_type == MachO::S_16BYTE_LITERALS)
7807 outs() << " S_16BYTE_LITERALS\n";
7808 else if (section_type == MachO::S_LITERAL_POINTERS)
7809 outs() << " S_LITERAL_POINTERS\n";
7810 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7811 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7812 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7813 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7814 else if (section_type == MachO::S_SYMBOL_STUBS)
7815 outs() << " S_SYMBOL_STUBS\n";
7816 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7817 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7818 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7819 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7820 else if (section_type == MachO::S_COALESCED)
7821 outs() << " S_COALESCED\n";
7822 else if (section_type == MachO::S_INTERPOSING)
7823 outs() << " S_INTERPOSING\n";
7824 else if (section_type == MachO::S_DTRACE_DOF)
7825 outs() << " S_DTRACE_DOF\n";
7826 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7827 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7828 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7829 outs() << " S_THREAD_LOCAL_REGULAR\n";
7830 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7831 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7832 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7833 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7834 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7835 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7836 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7837 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7838 else
7839 outs() << format("0x%08" PRIx32, section_type) << "\n";
7840 outs() << "attributes";
7841 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7842 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7843 outs() << " PURE_INSTRUCTIONS";
7844 if (section_attributes & MachO::S_ATTR_NO_TOC)
7845 outs() << " NO_TOC";
7846 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7847 outs() << " STRIP_STATIC_SYMS";
7848 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7849 outs() << " NO_DEAD_STRIP";
7850 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7851 outs() << " LIVE_SUPPORT";
7852 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7853 outs() << " SELF_MODIFYING_CODE";
7854 if (section_attributes & MachO::S_ATTR_DEBUG)
7855 outs() << " DEBUG";
7856 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7857 outs() << " SOME_INSTRUCTIONS";
7858 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7859 outs() << " EXT_RELOC";
7860 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7861 outs() << " LOC_RELOC";
7862 if (section_attributes == 0)
7863 outs() << " (none)";
7864 outs() << "\n";
7865 } else
7866 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7867 outs() << " reserved1 " << reserved1;
7868 if (section_type == MachO::S_SYMBOL_STUBS ||
7869 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7870 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7871 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7872 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7873 outs() << " (index into indirect symbol table)\n";
7874 else
7875 outs() << "\n";
7876 outs() << " reserved2 " << reserved2;
7877 if (section_type == MachO::S_SYMBOL_STUBS)
7878 outs() << " (size of stubs)\n";
7879 else
7880 outs() << "\n";
7881}
7882
David Majnemer73cc6ff2014-11-13 19:48:56 +00007883static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007884 uint32_t object_size) {
7885 outs() << " cmd LC_SYMTAB\n";
7886 outs() << " cmdsize " << st.cmdsize;
7887 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7888 outs() << " Incorrect size\n";
7889 else
7890 outs() << "\n";
7891 outs() << " symoff " << st.symoff;
7892 if (st.symoff > object_size)
7893 outs() << " (past end of file)\n";
7894 else
7895 outs() << "\n";
7896 outs() << " nsyms " << st.nsyms;
7897 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007898 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007899 big_size = st.nsyms;
7900 big_size *= sizeof(struct MachO::nlist_64);
7901 big_size += st.symoff;
7902 if (big_size > object_size)
7903 outs() << " (past end of file)\n";
7904 else
7905 outs() << "\n";
7906 } else {
7907 big_size = st.nsyms;
7908 big_size *= sizeof(struct MachO::nlist);
7909 big_size += st.symoff;
7910 if (big_size > object_size)
7911 outs() << " (past end of file)\n";
7912 else
7913 outs() << "\n";
7914 }
7915 outs() << " stroff " << st.stroff;
7916 if (st.stroff > object_size)
7917 outs() << " (past end of file)\n";
7918 else
7919 outs() << "\n";
7920 outs() << " strsize " << st.strsize;
7921 big_size = st.stroff;
7922 big_size += st.strsize;
7923 if (big_size > object_size)
7924 outs() << " (past end of file)\n";
7925 else
7926 outs() << "\n";
7927}
7928
7929static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7930 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007931 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007932 outs() << " cmd LC_DYSYMTAB\n";
7933 outs() << " cmdsize " << dyst.cmdsize;
7934 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7935 outs() << " Incorrect size\n";
7936 else
7937 outs() << "\n";
7938 outs() << " ilocalsym " << dyst.ilocalsym;
7939 if (dyst.ilocalsym > nsyms)
7940 outs() << " (greater than the number of symbols)\n";
7941 else
7942 outs() << "\n";
7943 outs() << " nlocalsym " << dyst.nlocalsym;
7944 uint64_t big_size;
7945 big_size = dyst.ilocalsym;
7946 big_size += dyst.nlocalsym;
7947 if (big_size > nsyms)
7948 outs() << " (past the end of the symbol table)\n";
7949 else
7950 outs() << "\n";
7951 outs() << " iextdefsym " << dyst.iextdefsym;
7952 if (dyst.iextdefsym > nsyms)
7953 outs() << " (greater than the number of symbols)\n";
7954 else
7955 outs() << "\n";
7956 outs() << " nextdefsym " << dyst.nextdefsym;
7957 big_size = dyst.iextdefsym;
7958 big_size += dyst.nextdefsym;
7959 if (big_size > nsyms)
7960 outs() << " (past the end of the symbol table)\n";
7961 else
7962 outs() << "\n";
7963 outs() << " iundefsym " << dyst.iundefsym;
7964 if (dyst.iundefsym > nsyms)
7965 outs() << " (greater than the number of symbols)\n";
7966 else
7967 outs() << "\n";
7968 outs() << " nundefsym " << dyst.nundefsym;
7969 big_size = dyst.iundefsym;
7970 big_size += dyst.nundefsym;
7971 if (big_size > nsyms)
7972 outs() << " (past the end of the symbol table)\n";
7973 else
7974 outs() << "\n";
7975 outs() << " tocoff " << dyst.tocoff;
7976 if (dyst.tocoff > object_size)
7977 outs() << " (past end of file)\n";
7978 else
7979 outs() << "\n";
7980 outs() << " ntoc " << dyst.ntoc;
7981 big_size = dyst.ntoc;
7982 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7983 big_size += dyst.tocoff;
7984 if (big_size > object_size)
7985 outs() << " (past end of file)\n";
7986 else
7987 outs() << "\n";
7988 outs() << " modtaboff " << dyst.modtaboff;
7989 if (dyst.modtaboff > object_size)
7990 outs() << " (past end of file)\n";
7991 else
7992 outs() << "\n";
7993 outs() << " nmodtab " << dyst.nmodtab;
7994 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007995 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007996 modtabend = dyst.nmodtab;
7997 modtabend *= sizeof(struct MachO::dylib_module_64);
7998 modtabend += dyst.modtaboff;
7999 } else {
8000 modtabend = dyst.nmodtab;
8001 modtabend *= sizeof(struct MachO::dylib_module);
8002 modtabend += dyst.modtaboff;
8003 }
8004 if (modtabend > object_size)
8005 outs() << " (past end of file)\n";
8006 else
8007 outs() << "\n";
8008 outs() << " extrefsymoff " << dyst.extrefsymoff;
8009 if (dyst.extrefsymoff > object_size)
8010 outs() << " (past end of file)\n";
8011 else
8012 outs() << "\n";
8013 outs() << " nextrefsyms " << dyst.nextrefsyms;
8014 big_size = dyst.nextrefsyms;
8015 big_size *= sizeof(struct MachO::dylib_reference);
8016 big_size += dyst.extrefsymoff;
8017 if (big_size > object_size)
8018 outs() << " (past end of file)\n";
8019 else
8020 outs() << "\n";
8021 outs() << " indirectsymoff " << dyst.indirectsymoff;
8022 if (dyst.indirectsymoff > object_size)
8023 outs() << " (past end of file)\n";
8024 else
8025 outs() << "\n";
8026 outs() << " nindirectsyms " << dyst.nindirectsyms;
8027 big_size = dyst.nindirectsyms;
8028 big_size *= sizeof(uint32_t);
8029 big_size += dyst.indirectsymoff;
8030 if (big_size > object_size)
8031 outs() << " (past end of file)\n";
8032 else
8033 outs() << "\n";
8034 outs() << " extreloff " << dyst.extreloff;
8035 if (dyst.extreloff > object_size)
8036 outs() << " (past end of file)\n";
8037 else
8038 outs() << "\n";
8039 outs() << " nextrel " << dyst.nextrel;
8040 big_size = dyst.nextrel;
8041 big_size *= sizeof(struct MachO::relocation_info);
8042 big_size += dyst.extreloff;
8043 if (big_size > object_size)
8044 outs() << " (past end of file)\n";
8045 else
8046 outs() << "\n";
8047 outs() << " locreloff " << dyst.locreloff;
8048 if (dyst.locreloff > object_size)
8049 outs() << " (past end of file)\n";
8050 else
8051 outs() << "\n";
8052 outs() << " nlocrel " << dyst.nlocrel;
8053 big_size = dyst.nlocrel;
8054 big_size *= sizeof(struct MachO::relocation_info);
8055 big_size += dyst.locreloff;
8056 if (big_size > object_size)
8057 outs() << " (past end of file)\n";
8058 else
8059 outs() << "\n";
8060}
8061
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008062static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8063 uint32_t object_size) {
8064 if (dc.cmd == MachO::LC_DYLD_INFO)
8065 outs() << " cmd LC_DYLD_INFO\n";
8066 else
8067 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8068 outs() << " cmdsize " << dc.cmdsize;
8069 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8070 outs() << " Incorrect size\n";
8071 else
8072 outs() << "\n";
8073 outs() << " rebase_off " << dc.rebase_off;
8074 if (dc.rebase_off > object_size)
8075 outs() << " (past end of file)\n";
8076 else
8077 outs() << "\n";
8078 outs() << " rebase_size " << dc.rebase_size;
8079 uint64_t big_size;
8080 big_size = dc.rebase_off;
8081 big_size += dc.rebase_size;
8082 if (big_size > object_size)
8083 outs() << " (past end of file)\n";
8084 else
8085 outs() << "\n";
8086 outs() << " bind_off " << dc.bind_off;
8087 if (dc.bind_off > object_size)
8088 outs() << " (past end of file)\n";
8089 else
8090 outs() << "\n";
8091 outs() << " bind_size " << dc.bind_size;
8092 big_size = dc.bind_off;
8093 big_size += dc.bind_size;
8094 if (big_size > object_size)
8095 outs() << " (past end of file)\n";
8096 else
8097 outs() << "\n";
8098 outs() << " weak_bind_off " << dc.weak_bind_off;
8099 if (dc.weak_bind_off > object_size)
8100 outs() << " (past end of file)\n";
8101 else
8102 outs() << "\n";
8103 outs() << " weak_bind_size " << dc.weak_bind_size;
8104 big_size = dc.weak_bind_off;
8105 big_size += dc.weak_bind_size;
8106 if (big_size > object_size)
8107 outs() << " (past end of file)\n";
8108 else
8109 outs() << "\n";
8110 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8111 if (dc.lazy_bind_off > object_size)
8112 outs() << " (past end of file)\n";
8113 else
8114 outs() << "\n";
8115 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8116 big_size = dc.lazy_bind_off;
8117 big_size += dc.lazy_bind_size;
8118 if (big_size > object_size)
8119 outs() << " (past end of file)\n";
8120 else
8121 outs() << "\n";
8122 outs() << " export_off " << dc.export_off;
8123 if (dc.export_off > object_size)
8124 outs() << " (past end of file)\n";
8125 else
8126 outs() << "\n";
8127 outs() << " export_size " << dc.export_size;
8128 big_size = dc.export_off;
8129 big_size += dc.export_size;
8130 if (big_size > object_size)
8131 outs() << " (past end of file)\n";
8132 else
8133 outs() << "\n";
8134}
8135
8136static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8137 const char *Ptr) {
8138 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8139 outs() << " cmd LC_ID_DYLINKER\n";
8140 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8141 outs() << " cmd LC_LOAD_DYLINKER\n";
8142 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8143 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8144 else
8145 outs() << " cmd ?(" << dyld.cmd << ")\n";
8146 outs() << " cmdsize " << dyld.cmdsize;
8147 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8148 outs() << " Incorrect size\n";
8149 else
8150 outs() << "\n";
8151 if (dyld.name >= dyld.cmdsize)
8152 outs() << " name ?(bad offset " << dyld.name << ")\n";
8153 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008154 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008155 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8156 }
8157}
8158
8159static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8160 outs() << " cmd LC_UUID\n";
8161 outs() << " cmdsize " << uuid.cmdsize;
8162 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8163 outs() << " Incorrect size\n";
8164 else
8165 outs() << "\n";
8166 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008167 for (int i = 0; i < 16; ++i) {
8168 outs() << format("%02" PRIX32, uuid.uuid[i]);
8169 if (i == 3 || i == 5 || i == 7 || i == 9)
8170 outs() << "-";
8171 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008172 outs() << "\n";
8173}
8174
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008175static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008176 outs() << " cmd LC_RPATH\n";
8177 outs() << " cmdsize " << rpath.cmdsize;
8178 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8179 outs() << " Incorrect size\n";
8180 else
8181 outs() << "\n";
8182 if (rpath.path >= rpath.cmdsize)
8183 outs() << " path ?(bad offset " << rpath.path << ")\n";
8184 else {
8185 const char *P = (const char *)(Ptr) + rpath.path;
8186 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8187 }
8188}
8189
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008190static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008191 StringRef LoadCmdName;
8192 switch (vd.cmd) {
8193 case MachO::LC_VERSION_MIN_MACOSX:
8194 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8195 break;
8196 case MachO::LC_VERSION_MIN_IPHONEOS:
8197 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8198 break;
8199 case MachO::LC_VERSION_MIN_TVOS:
8200 LoadCmdName = "LC_VERSION_MIN_TVOS";
8201 break;
8202 case MachO::LC_VERSION_MIN_WATCHOS:
8203 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8204 break;
8205 default:
8206 llvm_unreachable("Unknown version min load command");
8207 }
8208
8209 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008210 outs() << " cmdsize " << vd.cmdsize;
8211 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8212 outs() << " Incorrect size\n";
8213 else
8214 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008215 outs() << " version "
8216 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8217 << MachOObjectFile::getVersionMinMinor(vd, false);
8218 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8219 if (Update != 0)
8220 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008221 outs() << "\n";
8222 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008223 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008224 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008225 outs() << " sdk "
8226 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8227 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008228 }
Davide Italiano56baef32015-08-26 12:26:11 +00008229 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8230 if (Update != 0)
8231 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008232 outs() << "\n";
8233}
8234
Kevin Enderbya4579c42017-01-19 17:36:31 +00008235static void PrintNoteLoadCommand(MachO::note_command Nt) {
8236 outs() << " cmd LC_NOTE\n";
8237 outs() << " cmdsize " << Nt.cmdsize;
8238 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8239 outs() << " Incorrect size\n";
8240 else
8241 outs() << "\n";
8242 const char *d = Nt.data_owner;
8243 outs() << "data_owner " << format("%.16s\n", d);
8244 outs() << " offset " << Nt.offset << "\n";
8245 outs() << " size " << Nt.size << "\n";
8246}
8247
Steven Wu5b54a422017-01-23 20:07:55 +00008248static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8249 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8250 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8251 << "\n";
8252}
8253
8254static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8255 MachO::build_version_command bd) {
8256 outs() << " cmd LC_BUILD_VERSION\n";
8257 outs() << " cmdsize " << bd.cmdsize;
8258 if (bd.cmdsize !=
8259 sizeof(struct MachO::build_version_command) +
8260 bd.ntools * sizeof(struct MachO::build_tool_version))
8261 outs() << " Incorrect size\n";
8262 else
8263 outs() << "\n";
8264 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8265 << "\n";
8266 if (bd.sdk)
8267 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8268 << "\n";
8269 else
8270 outs() << " sdk n/a\n";
8271 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8272 << "\n";
8273 outs() << " ntools " << bd.ntools << "\n";
8274 for (unsigned i = 0; i < bd.ntools; ++i) {
8275 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8276 PrintBuildToolVersion(bv);
8277 }
8278}
8279
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008280static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8281 outs() << " cmd LC_SOURCE_VERSION\n";
8282 outs() << " cmdsize " << sd.cmdsize;
8283 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8284 outs() << " Incorrect size\n";
8285 else
8286 outs() << "\n";
8287 uint64_t a = (sd.version >> 40) & 0xffffff;
8288 uint64_t b = (sd.version >> 30) & 0x3ff;
8289 uint64_t c = (sd.version >> 20) & 0x3ff;
8290 uint64_t d = (sd.version >> 10) & 0x3ff;
8291 uint64_t e = sd.version & 0x3ff;
8292 outs() << " version " << a << "." << b;
8293 if (e != 0)
8294 outs() << "." << c << "." << d << "." << e;
8295 else if (d != 0)
8296 outs() << "." << c << "." << d;
8297 else if (c != 0)
8298 outs() << "." << c;
8299 outs() << "\n";
8300}
8301
8302static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8303 outs() << " cmd LC_MAIN\n";
8304 outs() << " cmdsize " << ep.cmdsize;
8305 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8306 outs() << " Incorrect size\n";
8307 else
8308 outs() << "\n";
8309 outs() << " entryoff " << ep.entryoff << "\n";
8310 outs() << " stacksize " << ep.stacksize << "\n";
8311}
8312
Kevin Enderby0804f4672014-12-16 23:25:52 +00008313static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8314 uint32_t object_size) {
8315 outs() << " cmd LC_ENCRYPTION_INFO\n";
8316 outs() << " cmdsize " << ec.cmdsize;
8317 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8318 outs() << " Incorrect size\n";
8319 else
8320 outs() << "\n";
8321 outs() << " cryptoff " << ec.cryptoff;
8322 if (ec.cryptoff > object_size)
8323 outs() << " (past end of file)\n";
8324 else
8325 outs() << "\n";
8326 outs() << " cryptsize " << ec.cryptsize;
8327 if (ec.cryptsize > object_size)
8328 outs() << " (past end of file)\n";
8329 else
8330 outs() << "\n";
8331 outs() << " cryptid " << ec.cryptid << "\n";
8332}
8333
Kevin Enderby57538292014-12-17 01:01:30 +00008334static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008335 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008336 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8337 outs() << " cmdsize " << ec.cmdsize;
8338 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8339 outs() << " Incorrect size\n";
8340 else
8341 outs() << "\n";
8342 outs() << " cryptoff " << ec.cryptoff;
8343 if (ec.cryptoff > object_size)
8344 outs() << " (past end of file)\n";
8345 else
8346 outs() << "\n";
8347 outs() << " cryptsize " << ec.cryptsize;
8348 if (ec.cryptsize > object_size)
8349 outs() << " (past end of file)\n";
8350 else
8351 outs() << "\n";
8352 outs() << " cryptid " << ec.cryptid << "\n";
8353 outs() << " pad " << ec.pad << "\n";
8354}
8355
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008356static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8357 const char *Ptr) {
8358 outs() << " cmd LC_LINKER_OPTION\n";
8359 outs() << " cmdsize " << lo.cmdsize;
8360 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8361 outs() << " Incorrect size\n";
8362 else
8363 outs() << "\n";
8364 outs() << " count " << lo.count << "\n";
8365 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8366 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8367 uint32_t i = 0;
8368 while (left > 0) {
8369 while (*string == '\0' && left > 0) {
8370 string++;
8371 left--;
8372 }
8373 if (left > 0) {
8374 i++;
8375 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008376 uint32_t NullPos = StringRef(string, left).find('\0');
8377 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008378 string += len;
8379 left -= len;
8380 }
8381 }
8382 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008383 outs() << " count " << lo.count << " does not match number of strings "
8384 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008385}
8386
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008387static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8388 const char *Ptr) {
8389 outs() << " cmd LC_SUB_FRAMEWORK\n";
8390 outs() << " cmdsize " << sub.cmdsize;
8391 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8392 outs() << " Incorrect size\n";
8393 else
8394 outs() << "\n";
8395 if (sub.umbrella < sub.cmdsize) {
8396 const char *P = Ptr + sub.umbrella;
8397 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8398 } else {
8399 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8400 }
8401}
8402
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008403static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8404 const char *Ptr) {
8405 outs() << " cmd LC_SUB_UMBRELLA\n";
8406 outs() << " cmdsize " << sub.cmdsize;
8407 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8408 outs() << " Incorrect size\n";
8409 else
8410 outs() << "\n";
8411 if (sub.sub_umbrella < sub.cmdsize) {
8412 const char *P = Ptr + sub.sub_umbrella;
8413 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8414 } else {
8415 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8416 }
8417}
8418
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008419static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008420 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008421 outs() << " cmd LC_SUB_LIBRARY\n";
8422 outs() << " cmdsize " << sub.cmdsize;
8423 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8424 outs() << " Incorrect size\n";
8425 else
8426 outs() << "\n";
8427 if (sub.sub_library < sub.cmdsize) {
8428 const char *P = Ptr + sub.sub_library;
8429 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8430 } else {
8431 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8432 }
8433}
8434
Kevin Enderby186eac32014-12-19 21:06:24 +00008435static void PrintSubClientCommand(MachO::sub_client_command sub,
8436 const char *Ptr) {
8437 outs() << " cmd LC_SUB_CLIENT\n";
8438 outs() << " cmdsize " << sub.cmdsize;
8439 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8440 outs() << " Incorrect size\n";
8441 else
8442 outs() << "\n";
8443 if (sub.client < sub.cmdsize) {
8444 const char *P = Ptr + sub.client;
8445 outs() << " client " << P << " (offset " << sub.client << ")\n";
8446 } else {
8447 outs() << " client ?(bad offset " << sub.client << ")\n";
8448 }
8449}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008450
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008451static void PrintRoutinesCommand(MachO::routines_command r) {
8452 outs() << " cmd LC_ROUTINES\n";
8453 outs() << " cmdsize " << r.cmdsize;
8454 if (r.cmdsize != sizeof(struct MachO::routines_command))
8455 outs() << " Incorrect size\n";
8456 else
8457 outs() << "\n";
8458 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8459 outs() << " init_module " << r.init_module << "\n";
8460 outs() << " reserved1 " << r.reserved1 << "\n";
8461 outs() << " reserved2 " << r.reserved2 << "\n";
8462 outs() << " reserved3 " << r.reserved3 << "\n";
8463 outs() << " reserved4 " << r.reserved4 << "\n";
8464 outs() << " reserved5 " << r.reserved5 << "\n";
8465 outs() << " reserved6 " << r.reserved6 << "\n";
8466}
8467
8468static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8469 outs() << " cmd LC_ROUTINES_64\n";
8470 outs() << " cmdsize " << r.cmdsize;
8471 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8472 outs() << " Incorrect size\n";
8473 else
8474 outs() << "\n";
8475 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8476 outs() << " init_module " << r.init_module << "\n";
8477 outs() << " reserved1 " << r.reserved1 << "\n";
8478 outs() << " reserved2 " << r.reserved2 << "\n";
8479 outs() << " reserved3 " << r.reserved3 << "\n";
8480 outs() << " reserved4 " << r.reserved4 << "\n";
8481 outs() << " reserved5 " << r.reserved5 << "\n";
8482 outs() << " reserved6 " << r.reserved6 << "\n";
8483}
8484
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008485static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8486 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8487 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8488 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8489 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8490 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8491 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8492 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8493 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8494 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8495 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8496 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8497 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8498 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8499 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8500 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8501 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8502}
8503
Kevin Enderby48ef5342014-12-23 22:56:39 +00008504static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8505 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8506 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8507 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8508 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8509 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8510 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8511 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8512 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8513 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8514 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8515 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8516 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8517 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8518 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8519 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8520 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8521 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8522 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8523 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8524 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8525 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8526}
8527
Kevin Enderby227df342014-12-23 23:43:59 +00008528static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008529 uint32_t f;
8530 outs() << "\t mmst_reg ";
8531 for (f = 0; f < 10; f++)
8532 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8533 outs() << "\n";
8534 outs() << "\t mmst_rsrv ";
8535 for (f = 0; f < 6; f++)
8536 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8537 outs() << "\n";
8538}
8539
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008540static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008541 uint32_t f;
8542 outs() << "\t xmm_reg ";
8543 for (f = 0; f < 16; f++)
8544 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8545 outs() << "\n";
8546}
8547
8548static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8549 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8550 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8551 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8552 outs() << " denorm " << fpu.fpu_fcw.denorm;
8553 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8554 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8555 outs() << " undfl " << fpu.fpu_fcw.undfl;
8556 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8557 outs() << "\t\t pc ";
8558 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8559 outs() << "FP_PREC_24B ";
8560 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8561 outs() << "FP_PREC_53B ";
8562 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8563 outs() << "FP_PREC_64B ";
8564 else
8565 outs() << fpu.fpu_fcw.pc << " ";
8566 outs() << "rc ";
8567 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8568 outs() << "FP_RND_NEAR ";
8569 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8570 outs() << "FP_RND_DOWN ";
8571 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8572 outs() << "FP_RND_UP ";
8573 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008574 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008575 outs() << "\n";
8576 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8577 outs() << " denorm " << fpu.fpu_fsw.denorm;
8578 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8579 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8580 outs() << " undfl " << fpu.fpu_fsw.undfl;
8581 outs() << " precis " << fpu.fpu_fsw.precis;
8582 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8583 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8584 outs() << " c0 " << fpu.fpu_fsw.c0;
8585 outs() << " c1 " << fpu.fpu_fsw.c1;
8586 outs() << " c2 " << fpu.fpu_fsw.c2;
8587 outs() << " tos " << fpu.fpu_fsw.tos;
8588 outs() << " c3 " << fpu.fpu_fsw.c3;
8589 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8590 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8591 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8592 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8593 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8594 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8595 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8596 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8597 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8598 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8599 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8600 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8601 outs() << "\n";
8602 outs() << "\t fpu_stmm0:\n";
8603 Print_mmst_reg(fpu.fpu_stmm0);
8604 outs() << "\t fpu_stmm1:\n";
8605 Print_mmst_reg(fpu.fpu_stmm1);
8606 outs() << "\t fpu_stmm2:\n";
8607 Print_mmst_reg(fpu.fpu_stmm2);
8608 outs() << "\t fpu_stmm3:\n";
8609 Print_mmst_reg(fpu.fpu_stmm3);
8610 outs() << "\t fpu_stmm4:\n";
8611 Print_mmst_reg(fpu.fpu_stmm4);
8612 outs() << "\t fpu_stmm5:\n";
8613 Print_mmst_reg(fpu.fpu_stmm5);
8614 outs() << "\t fpu_stmm6:\n";
8615 Print_mmst_reg(fpu.fpu_stmm6);
8616 outs() << "\t fpu_stmm7:\n";
8617 Print_mmst_reg(fpu.fpu_stmm7);
8618 outs() << "\t fpu_xmm0:\n";
8619 Print_xmm_reg(fpu.fpu_xmm0);
8620 outs() << "\t fpu_xmm1:\n";
8621 Print_xmm_reg(fpu.fpu_xmm1);
8622 outs() << "\t fpu_xmm2:\n";
8623 Print_xmm_reg(fpu.fpu_xmm2);
8624 outs() << "\t fpu_xmm3:\n";
8625 Print_xmm_reg(fpu.fpu_xmm3);
8626 outs() << "\t fpu_xmm4:\n";
8627 Print_xmm_reg(fpu.fpu_xmm4);
8628 outs() << "\t fpu_xmm5:\n";
8629 Print_xmm_reg(fpu.fpu_xmm5);
8630 outs() << "\t fpu_xmm6:\n";
8631 Print_xmm_reg(fpu.fpu_xmm6);
8632 outs() << "\t fpu_xmm7:\n";
8633 Print_xmm_reg(fpu.fpu_xmm7);
8634 outs() << "\t fpu_xmm8:\n";
8635 Print_xmm_reg(fpu.fpu_xmm8);
8636 outs() << "\t fpu_xmm9:\n";
8637 Print_xmm_reg(fpu.fpu_xmm9);
8638 outs() << "\t fpu_xmm10:\n";
8639 Print_xmm_reg(fpu.fpu_xmm10);
8640 outs() << "\t fpu_xmm11:\n";
8641 Print_xmm_reg(fpu.fpu_xmm11);
8642 outs() << "\t fpu_xmm12:\n";
8643 Print_xmm_reg(fpu.fpu_xmm12);
8644 outs() << "\t fpu_xmm13:\n";
8645 Print_xmm_reg(fpu.fpu_xmm13);
8646 outs() << "\t fpu_xmm14:\n";
8647 Print_xmm_reg(fpu.fpu_xmm14);
8648 outs() << "\t fpu_xmm15:\n";
8649 Print_xmm_reg(fpu.fpu_xmm15);
8650 outs() << "\t fpu_rsrv4:\n";
8651 for (uint32_t f = 0; f < 6; f++) {
8652 outs() << "\t ";
8653 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008654 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008655 outs() << "\n";
8656 }
8657 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8658 outs() << "\n";
8659}
8660
8661static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8662 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8663 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8664 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8665}
8666
Kevin Enderby41c9c002016-10-21 18:22:35 +00008667static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
8668 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
8669 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
8670 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
8671 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
8672 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
8673 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
8674 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
8675 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
8676 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
8677 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
8678 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
8679 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
8680 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
8681 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
8682 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
8683 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
8684 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
8685}
8686
Kevin Enderby7747cb52016-11-03 20:51:28 +00008687static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
8688 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
8689 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
8690 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
8691 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
8692 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
8693 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
8694 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
8695 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
8696 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
8697 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
8698 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
8699 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
8700 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
8701 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
8702 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
8703 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
8704 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
8705 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
8706 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
8707 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
8708 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
8709 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
8710 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
8711 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
8712 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
8713 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
8714 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
8715 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
8716 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
8717 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
8718 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
8719 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
8720 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
8721 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
8722}
8723
Kevin Enderby48ef5342014-12-23 22:56:39 +00008724static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8725 bool isLittleEndian, uint32_t cputype) {
8726 if (t.cmd == MachO::LC_THREAD)
8727 outs() << " cmd LC_THREAD\n";
8728 else if (t.cmd == MachO::LC_UNIXTHREAD)
8729 outs() << " cmd LC_UNIXTHREAD\n";
8730 else
8731 outs() << " cmd " << t.cmd << " (unknown)\n";
8732 outs() << " cmdsize " << t.cmdsize;
8733 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8734 outs() << " Incorrect size\n";
8735 else
8736 outs() << "\n";
8737
8738 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8739 const char *end = Ptr + t.cmdsize;
8740 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008741 if (cputype == MachO::CPU_TYPE_I386) {
8742 while (begin < end) {
8743 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8744 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8745 begin += sizeof(uint32_t);
8746 } else {
8747 flavor = 0;
8748 begin = end;
8749 }
8750 if (isLittleEndian != sys::IsLittleEndianHost)
8751 sys::swapByteOrder(flavor);
8752 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8753 memcpy((char *)&count, begin, sizeof(uint32_t));
8754 begin += sizeof(uint32_t);
8755 } else {
8756 count = 0;
8757 begin = end;
8758 }
8759 if (isLittleEndian != sys::IsLittleEndianHost)
8760 sys::swapByteOrder(count);
8761 if (flavor == MachO::x86_THREAD_STATE32) {
8762 outs() << " flavor i386_THREAD_STATE\n";
8763 if (count == MachO::x86_THREAD_STATE32_COUNT)
8764 outs() << " count i386_THREAD_STATE_COUNT\n";
8765 else
8766 outs() << " count " << count
8767 << " (not x86_THREAD_STATE32_COUNT)\n";
8768 MachO::x86_thread_state32_t cpu32;
8769 left = end - begin;
8770 if (left >= sizeof(MachO::x86_thread_state32_t)) {
8771 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
8772 begin += sizeof(MachO::x86_thread_state32_t);
8773 } else {
8774 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
8775 memcpy(&cpu32, begin, left);
8776 begin += left;
8777 }
8778 if (isLittleEndian != sys::IsLittleEndianHost)
8779 swapStruct(cpu32);
8780 Print_x86_thread_state32_t(cpu32);
8781 } else if (flavor == MachO::x86_THREAD_STATE) {
8782 outs() << " flavor x86_THREAD_STATE\n";
8783 if (count == MachO::x86_THREAD_STATE_COUNT)
8784 outs() << " count x86_THREAD_STATE_COUNT\n";
8785 else
8786 outs() << " count " << count
8787 << " (not x86_THREAD_STATE_COUNT)\n";
8788 struct MachO::x86_thread_state_t ts;
8789 left = end - begin;
8790 if (left >= sizeof(MachO::x86_thread_state_t)) {
8791 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8792 begin += sizeof(MachO::x86_thread_state_t);
8793 } else {
8794 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8795 memcpy(&ts, begin, left);
8796 begin += left;
8797 }
8798 if (isLittleEndian != sys::IsLittleEndianHost)
8799 swapStruct(ts);
8800 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
8801 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
8802 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
8803 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
8804 else
8805 outs() << "tsh.count " << ts.tsh.count
8806 << " (not x86_THREAD_STATE32_COUNT\n";
8807 Print_x86_thread_state32_t(ts.uts.ts32);
8808 } else {
8809 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8810 << ts.tsh.count << "\n";
8811 }
8812 } else {
8813 outs() << " flavor " << flavor << " (unknown)\n";
8814 outs() << " count " << count << "\n";
8815 outs() << " state (unknown)\n";
8816 begin += count * sizeof(uint32_t);
8817 }
8818 }
8819 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008820 while (begin < end) {
8821 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8822 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8823 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008824 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008825 flavor = 0;
8826 begin = end;
8827 }
8828 if (isLittleEndian != sys::IsLittleEndianHost)
8829 sys::swapByteOrder(flavor);
8830 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8831 memcpy((char *)&count, begin, sizeof(uint32_t));
8832 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008833 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008834 count = 0;
8835 begin = end;
8836 }
8837 if (isLittleEndian != sys::IsLittleEndianHost)
8838 sys::swapByteOrder(count);
8839 if (flavor == MachO::x86_THREAD_STATE64) {
8840 outs() << " flavor x86_THREAD_STATE64\n";
8841 if (count == MachO::x86_THREAD_STATE64_COUNT)
8842 outs() << " count x86_THREAD_STATE64_COUNT\n";
8843 else
8844 outs() << " count " << count
8845 << " (not x86_THREAD_STATE64_COUNT)\n";
8846 MachO::x86_thread_state64_t cpu64;
8847 left = end - begin;
8848 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8849 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8850 begin += sizeof(MachO::x86_thread_state64_t);
8851 } else {
8852 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8853 memcpy(&cpu64, begin, left);
8854 begin += left;
8855 }
8856 if (isLittleEndian != sys::IsLittleEndianHost)
8857 swapStruct(cpu64);
8858 Print_x86_thread_state64_t(cpu64);
8859 } else if (flavor == MachO::x86_THREAD_STATE) {
8860 outs() << " flavor x86_THREAD_STATE\n";
8861 if (count == MachO::x86_THREAD_STATE_COUNT)
8862 outs() << " count x86_THREAD_STATE_COUNT\n";
8863 else
8864 outs() << " count " << count
8865 << " (not x86_THREAD_STATE_COUNT)\n";
8866 struct MachO::x86_thread_state_t ts;
8867 left = end - begin;
8868 if (left >= sizeof(MachO::x86_thread_state_t)) {
8869 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8870 begin += sizeof(MachO::x86_thread_state_t);
8871 } else {
8872 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8873 memcpy(&ts, begin, left);
8874 begin += left;
8875 }
8876 if (isLittleEndian != sys::IsLittleEndianHost)
8877 swapStruct(ts);
8878 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8879 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8880 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8881 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8882 else
8883 outs() << "tsh.count " << ts.tsh.count
8884 << " (not x86_THREAD_STATE64_COUNT\n";
8885 Print_x86_thread_state64_t(ts.uts.ts64);
8886 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008887 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8888 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008889 }
8890 } else if (flavor == MachO::x86_FLOAT_STATE) {
8891 outs() << " flavor x86_FLOAT_STATE\n";
8892 if (count == MachO::x86_FLOAT_STATE_COUNT)
8893 outs() << " count x86_FLOAT_STATE_COUNT\n";
8894 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008895 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008896 struct MachO::x86_float_state_t fs;
8897 left = end - begin;
8898 if (left >= sizeof(MachO::x86_float_state_t)) {
8899 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8900 begin += sizeof(MachO::x86_float_state_t);
8901 } else {
8902 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8903 memcpy(&fs, begin, left);
8904 begin += left;
8905 }
8906 if (isLittleEndian != sys::IsLittleEndianHost)
8907 swapStruct(fs);
8908 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8909 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008910 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008911 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8912 else
8913 outs() << "fsh.count " << fs.fsh.count
8914 << " (not x86_FLOAT_STATE64_COUNT\n";
8915 Print_x86_float_state_t(fs.ufs.fs64);
8916 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008917 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8918 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008919 }
8920 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8921 outs() << " flavor x86_EXCEPTION_STATE\n";
8922 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8923 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8924 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008925 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008926 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8927 struct MachO::x86_exception_state_t es;
8928 left = end - begin;
8929 if (left >= sizeof(MachO::x86_exception_state_t)) {
8930 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8931 begin += sizeof(MachO::x86_exception_state_t);
8932 } else {
8933 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8934 memcpy(&es, begin, left);
8935 begin += left;
8936 }
8937 if (isLittleEndian != sys::IsLittleEndianHost)
8938 swapStruct(es);
8939 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8940 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008941 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008942 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8943 else
8944 outs() << "\t esh.count " << es.esh.count
8945 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8946 Print_x86_exception_state_t(es.ues.es64);
8947 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008948 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8949 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008950 }
8951 } else {
8952 outs() << " flavor " << flavor << " (unknown)\n";
8953 outs() << " count " << count << "\n";
8954 outs() << " state (unknown)\n";
8955 begin += count * sizeof(uint32_t);
8956 }
8957 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00008958 } else if (cputype == MachO::CPU_TYPE_ARM) {
8959 while (begin < end) {
8960 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8961 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8962 begin += sizeof(uint32_t);
8963 } else {
8964 flavor = 0;
8965 begin = end;
8966 }
8967 if (isLittleEndian != sys::IsLittleEndianHost)
8968 sys::swapByteOrder(flavor);
8969 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8970 memcpy((char *)&count, begin, sizeof(uint32_t));
8971 begin += sizeof(uint32_t);
8972 } else {
8973 count = 0;
8974 begin = end;
8975 }
8976 if (isLittleEndian != sys::IsLittleEndianHost)
8977 sys::swapByteOrder(count);
8978 if (flavor == MachO::ARM_THREAD_STATE) {
8979 outs() << " flavor ARM_THREAD_STATE\n";
8980 if (count == MachO::ARM_THREAD_STATE_COUNT)
8981 outs() << " count ARM_THREAD_STATE_COUNT\n";
8982 else
8983 outs() << " count " << count
8984 << " (not ARM_THREAD_STATE_COUNT)\n";
8985 MachO::arm_thread_state32_t cpu32;
8986 left = end - begin;
8987 if (left >= sizeof(MachO::arm_thread_state32_t)) {
8988 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
8989 begin += sizeof(MachO::arm_thread_state32_t);
8990 } else {
8991 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
8992 memcpy(&cpu32, begin, left);
8993 begin += left;
8994 }
8995 if (isLittleEndian != sys::IsLittleEndianHost)
8996 swapStruct(cpu32);
8997 Print_arm_thread_state32_t(cpu32);
8998 } else {
8999 outs() << " flavor " << flavor << " (unknown)\n";
9000 outs() << " count " << count << "\n";
9001 outs() << " state (unknown)\n";
9002 begin += count * sizeof(uint32_t);
9003 }
9004 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009005 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9006 while (begin < end) {
9007 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9008 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9009 begin += sizeof(uint32_t);
9010 } else {
9011 flavor = 0;
9012 begin = end;
9013 }
9014 if (isLittleEndian != sys::IsLittleEndianHost)
9015 sys::swapByteOrder(flavor);
9016 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9017 memcpy((char *)&count, begin, sizeof(uint32_t));
9018 begin += sizeof(uint32_t);
9019 } else {
9020 count = 0;
9021 begin = end;
9022 }
9023 if (isLittleEndian != sys::IsLittleEndianHost)
9024 sys::swapByteOrder(count);
9025 if (flavor == MachO::ARM_THREAD_STATE64) {
9026 outs() << " flavor ARM_THREAD_STATE64\n";
9027 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9028 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9029 else
9030 outs() << " count " << count
9031 << " (not ARM_THREAD_STATE64_COUNT)\n";
9032 MachO::arm_thread_state64_t cpu64;
9033 left = end - begin;
9034 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9035 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9036 begin += sizeof(MachO::arm_thread_state64_t);
9037 } else {
9038 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9039 memcpy(&cpu64, begin, left);
9040 begin += left;
9041 }
9042 if (isLittleEndian != sys::IsLittleEndianHost)
9043 swapStruct(cpu64);
9044 Print_arm_thread_state64_t(cpu64);
9045 } else {
9046 outs() << " flavor " << flavor << " (unknown)\n";
9047 outs() << " count " << count << "\n";
9048 outs() << " state (unknown)\n";
9049 begin += count * sizeof(uint32_t);
9050 }
9051 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009052 } else {
9053 while (begin < end) {
9054 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9055 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9056 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009057 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009058 flavor = 0;
9059 begin = end;
9060 }
9061 if (isLittleEndian != sys::IsLittleEndianHost)
9062 sys::swapByteOrder(flavor);
9063 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9064 memcpy((char *)&count, begin, sizeof(uint32_t));
9065 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009066 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009067 count = 0;
9068 begin = end;
9069 }
9070 if (isLittleEndian != sys::IsLittleEndianHost)
9071 sys::swapByteOrder(count);
9072 outs() << " flavor " << flavor << "\n";
9073 outs() << " count " << count << "\n";
9074 outs() << " state (Unknown cputype/cpusubtype)\n";
9075 begin += count * sizeof(uint32_t);
9076 }
9077 }
9078}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009079
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009080static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9081 if (dl.cmd == MachO::LC_ID_DYLIB)
9082 outs() << " cmd LC_ID_DYLIB\n";
9083 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9084 outs() << " cmd LC_LOAD_DYLIB\n";
9085 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9086 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9087 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9088 outs() << " cmd LC_REEXPORT_DYLIB\n";
9089 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9090 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9091 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9092 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9093 else
9094 outs() << " cmd " << dl.cmd << " (unknown)\n";
9095 outs() << " cmdsize " << dl.cmdsize;
9096 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9097 outs() << " Incorrect size\n";
9098 else
9099 outs() << "\n";
9100 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009101 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009102 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9103 } else {
9104 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9105 }
9106 outs() << " time stamp " << dl.dylib.timestamp << " ";
9107 time_t t = dl.dylib.timestamp;
9108 outs() << ctime(&t);
9109 outs() << " current version ";
9110 if (dl.dylib.current_version == 0xffffffff)
9111 outs() << "n/a\n";
9112 else
9113 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9114 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9115 << (dl.dylib.current_version & 0xff) << "\n";
9116 outs() << "compatibility version ";
9117 if (dl.dylib.compatibility_version == 0xffffffff)
9118 outs() << "n/a\n";
9119 else
9120 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9121 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9122 << (dl.dylib.compatibility_version & 0xff) << "\n";
9123}
9124
9125static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9126 uint32_t object_size) {
9127 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009128 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009129 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9130 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9131 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9132 outs() << " cmd LC_FUNCTION_STARTS\n";
9133 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9134 outs() << " cmd LC_DATA_IN_CODE\n";
9135 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9136 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9137 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9138 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9139 else
9140 outs() << " cmd " << ld.cmd << " (?)\n";
9141 outs() << " cmdsize " << ld.cmdsize;
9142 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9143 outs() << " Incorrect size\n";
9144 else
9145 outs() << "\n";
9146 outs() << " dataoff " << ld.dataoff;
9147 if (ld.dataoff > object_size)
9148 outs() << " (past end of file)\n";
9149 else
9150 outs() << "\n";
9151 outs() << " datasize " << ld.datasize;
9152 uint64_t big_size = ld.dataoff;
9153 big_size += ld.datasize;
9154 if (big_size > object_size)
9155 outs() << " (past end of file)\n";
9156 else
9157 outs() << "\n";
9158}
9159
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009160static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9161 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009162 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009163 unsigned Index = 0;
9164 for (const auto &Command : Obj->load_commands()) {
9165 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009166 if (Command.C.cmd == MachO::LC_SEGMENT) {
9167 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9168 const char *sg_segname = SLC.segname;
9169 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9170 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9171 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9172 verbose);
9173 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009174 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009175 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9176 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9177 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9178 }
9179 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9180 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9181 const char *sg_segname = SLC_64.segname;
9182 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9183 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9184 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9185 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9186 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9187 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9188 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9189 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9190 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9191 sg_segname, filetype, Buf.size(), verbose);
9192 }
9193 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9194 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009195 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009196 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9197 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9198 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009199 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9200 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009201 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9202 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9203 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9204 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9205 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9206 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9207 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9208 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9209 PrintDyldLoadCommand(Dyld, Command.Ptr);
9210 } else if (Command.C.cmd == MachO::LC_UUID) {
9211 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9212 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009213 } else if (Command.C.cmd == MachO::LC_RPATH) {
9214 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9215 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009216 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009217 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9218 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9219 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009220 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9221 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009222 } else if (Command.C.cmd == MachO::LC_NOTE) {
9223 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9224 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009225 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9226 MachO::build_version_command Bv =
9227 Obj->getBuildVersionLoadCommand(Command);
9228 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009229 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9230 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9231 PrintSourceVersionCommand(Sd);
9232 } else if (Command.C.cmd == MachO::LC_MAIN) {
9233 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9234 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009235 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009236 MachO::encryption_info_command Ei =
9237 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009238 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009239 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009240 MachO::encryption_info_command_64 Ei =
9241 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009242 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009243 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009244 MachO::linker_option_command Lo =
9245 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009246 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009247 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9248 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9249 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009250 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9251 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9252 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009253 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9254 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9255 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009256 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9257 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9258 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009259 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9260 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9261 PrintRoutinesCommand(Rc);
9262 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9263 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9264 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009265 } else if (Command.C.cmd == MachO::LC_THREAD ||
9266 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9267 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9268 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009269 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9270 Command.C.cmd == MachO::LC_ID_DYLIB ||
9271 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9272 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9273 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9274 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009275 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9276 PrintDylibCommand(Dl, Command.Ptr);
9277 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9278 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9279 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9280 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9281 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9282 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9283 MachO::linkedit_data_command Ld =
9284 Obj->getLinkeditDataLoadCommand(Command);
9285 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009286 } else {
9287 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9288 << ")\n";
9289 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9290 // TODO: get and print the raw bytes of the load command.
9291 }
9292 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009293 }
9294}
9295
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009296static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009297 if (Obj->is64Bit()) {
9298 MachO::mach_header_64 H_64;
9299 H_64 = Obj->getHeader64();
9300 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9301 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9302 } else {
9303 MachO::mach_header H;
9304 H = Obj->getHeader();
9305 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9306 H.sizeofcmds, H.flags, verbose);
9307 }
9308}
9309
9310void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9311 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009312 PrintMachHeader(file, !NonVerbose);
9313}
9314
9315void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9316 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009317 uint32_t filetype = 0;
9318 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009319 if (file->is64Bit()) {
9320 MachO::mach_header_64 H_64;
9321 H_64 = file->getHeader64();
9322 filetype = H_64.filetype;
9323 cputype = H_64.cputype;
9324 } else {
9325 MachO::mach_header H;
9326 H = file->getHeader();
9327 filetype = H.filetype;
9328 cputype = H.cputype;
9329 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009330 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009331}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009332
9333//===----------------------------------------------------------------------===//
9334// export trie dumping
9335//===----------------------------------------------------------------------===//
9336
9337void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009338 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9339 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009340 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9341 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9342 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9343 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9344 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9345 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9346 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9347 if (ReExport)
9348 outs() << "[re-export] ";
9349 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009350 outs() << format("0x%08llX ",
9351 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009352 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009353 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009354 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009355 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009356 if (WeakDef) {
9357 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009358 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009359 }
9360 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009361 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009362 outs() << ", ";
9363 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009364 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009365 }
9366 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009367 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009368 outs() << ", ";
9369 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009370 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009371 }
9372 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009373 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009374 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009375 outs() << format("resolver=0x%08llX", Entry.other());
9376 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009377 }
9378 outs() << "]";
9379 }
9380 if (ReExport) {
9381 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009382 int Ordinal = Entry.other() - 1;
9383 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9384 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009385 outs() << " (from " << DylibName << ")";
9386 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009387 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009388 }
9389 outs() << "\n";
9390 }
9391}
Nick Kledzikac431442014-09-12 21:34:15 +00009392
Nick Kledzikac431442014-09-12 21:34:15 +00009393//===----------------------------------------------------------------------===//
9394// rebase table dumping
9395//===----------------------------------------------------------------------===//
9396
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009397void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009398 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009399 Error Err = Error::success();
9400 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9401 StringRef SegmentName = Entry.segmentName();
9402 StringRef SectionName = Entry.sectionName();
9403 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009404
9405 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009406 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9407 SegmentName.str().c_str(), SectionName.str().c_str(),
9408 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009409 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009410 if (Err)
9411 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009412}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009413
9414static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9415 StringRef DylibName;
9416 switch (Ordinal) {
9417 case MachO::BIND_SPECIAL_DYLIB_SELF:
9418 return "this-image";
9419 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9420 return "main-executable";
9421 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9422 return "flat-namespace";
9423 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009424 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009425 std::error_code EC =
9426 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009427 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009428 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009429 return DylibName;
9430 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009431 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009432 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009433}
9434
9435//===----------------------------------------------------------------------===//
9436// bind table dumping
9437//===----------------------------------------------------------------------===//
9438
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009439void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009440 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009441 outs() << "segment section address type "
9442 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009443 Error Err = Error::success();
9444 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009445 StringRef SegmentName = Entry.segmentName();
9446 StringRef SectionName = Entry.sectionName();
9447 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009448
9449 // Table lines look like:
9450 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009451 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009452 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009453 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009454 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009455 << left_justify(SectionName, 18) << " "
9456 << format_hex(Address, 10, true) << " "
9457 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009458 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009459 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009460 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009461 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009462 if (Err)
9463 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009464}
9465
9466//===----------------------------------------------------------------------===//
9467// lazy bind table dumping
9468//===----------------------------------------------------------------------===//
9469
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009470void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009471 outs() << "segment section address "
9472 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009473 Error Err = Error::success();
9474 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009475 StringRef SegmentName = Entry.segmentName();
9476 StringRef SectionName = Entry.sectionName();
9477 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009478
9479 // Table lines look like:
9480 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009481 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009482 << left_justify(SectionName, 18) << " "
9483 << format_hex(Address, 10, true) << " "
9484 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009485 << Entry.symbolName() << "\n";
9486 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009487 if (Err)
9488 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009489}
9490
Nick Kledzik56ebef42014-09-16 01:41:51 +00009491//===----------------------------------------------------------------------===//
9492// weak bind table dumping
9493//===----------------------------------------------------------------------===//
9494
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009495void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009496 outs() << "segment section address "
9497 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009498 Error Err = Error::success();
9499 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009500 // Strong symbols don't have a location to update.
9501 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009502 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009503 << Entry.symbolName() << "\n";
9504 continue;
9505 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009506 StringRef SegmentName = Entry.segmentName();
9507 StringRef SectionName = Entry.sectionName();
9508 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009509
9510 // Table lines look like:
9511 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009512 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009513 << left_justify(SectionName, 18) << " "
9514 << format_hex(Address, 10, true) << " "
9515 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009516 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9517 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009518 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009519 if (Err)
9520 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009521}
9522
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009523// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9524// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9525// information for that address. If the address is found its binding symbol
9526// name is returned. If not nullptr is returned.
9527static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9528 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009529 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009530 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009531 Error Err = Error::success();
9532 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009533 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009534 StringRef name = Entry.symbolName();
9535 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009536 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009537 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009538 if (Err)
9539 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009540 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009541 auto name = info->bindtable->lookup(ReferenceValue);
9542 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009543}