blob: d70b26a05bb2c77dbd0d677b546d778f9c3fc3f7 [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000015#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000016#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000017#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000019#include "llvm/BinaryFormat/MachO.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000023#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000024#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000025#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000026#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000027#include "llvm/MC/MCInst.h"
28#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCInstrDesc.h"
30#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000031#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000032#include "llvm/MC/MCSubtargetInfo.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000033#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000034#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000035#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000038#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000042#include "llvm/Support/LEB128.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000046#include "llvm/Support/ToolOutputFile.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include <algorithm>
49#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000050#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000051
Kevin Enderby9873e2c2016-05-23 21:34:12 +000052#ifdef HAVE_LIBXAR
53extern "C" {
54#include <xar/xar.h>
55}
56#endif
57
Benjamin Kramer43a772e2011-09-19 17:56:04 +000058using namespace llvm;
59using namespace object;
60
61static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062 UseDbg("g",
63 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<std::string> DSYMFile("dsym",
66 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000070
Kevin Enderbyf9d60f02016-11-29 21:43:40 +000071static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
72 cl::desc("Print no leading headers"));
73
Kevin Enderby13023a12015-01-15 23:19:11 +000074cl::opt<bool> llvm::UniversalHeaders("universal-headers",
75 cl::desc("Print Mach-O universal headers "
76 "(requires -macho)"));
77
Kevin Enderby131d1772015-01-09 19:22:37 +000078cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000079 ArchiveMemberOffsets("archive-member-offsets",
80 cl::desc("Print the offset to each archive member for "
81 "Mach-O archives (requires -macho and "
82 "-archive-headers)"));
83
84cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000085 llvm::IndirectSymbols("indirect-symbols",
86 cl::desc("Print indirect symbol table for Mach-O "
87 "objects (requires -macho)"));
88
Kevin Enderby69fe98d2015-01-23 18:52:17 +000089cl::opt<bool>
90 llvm::DataInCode("data-in-code",
91 cl::desc("Print the data in code table for Mach-O objects "
92 "(requires -macho)"));
93
Kevin Enderby9a509442015-01-27 21:28:24 +000094cl::opt<bool>
95 llvm::LinkOptHints("link-opt-hints",
96 cl::desc("Print the linker optimization hints for "
97 "Mach-O objects (requires -macho)"));
98
Kevin Enderbycd66be52015-03-11 22:06:32 +000099cl::opt<bool>
100 llvm::InfoPlist("info-plist",
101 cl::desc("Print the info plist section as strings for "
102 "Mach-O objects (requires -macho)"));
103
Kevin Enderbyf0640752015-03-13 17:56:32 +0000104cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000105 llvm::DylibsUsed("dylibs-used",
106 cl::desc("Print the shared libraries used for linked "
107 "Mach-O files (requires -macho)"));
108
109cl::opt<bool>
110 llvm::DylibId("dylib-id",
111 cl::desc("Print the shared library's id for the dylib Mach-O "
112 "file (requires -macho)"));
113
114cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000115 llvm::NonVerbose("non-verbose",
116 cl::desc("Print the info for Mach-O objects in "
117 "non-verbose or numeric form (requires -macho)"));
118
Kevin Enderby0fc11822015-04-01 20:57:01 +0000119cl::opt<bool>
120 llvm::ObjcMetaData("objc-meta-data",
121 cl::desc("Print the Objective-C runtime meta data for "
122 "Mach-O files (requires -macho)"));
123
Kevin Enderby6a221752015-03-17 17:10:57 +0000124cl::opt<std::string> llvm::DisSymName(
125 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000126 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000127
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000128static cl::opt<bool> NoSymbolicOperands(
129 "no-symbolic-operands",
130 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
131
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000132static cl::list<std::string>
133 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
134 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000135
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000136bool ArchAll = false;
137
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000138static std::string ThumbTripleName;
139
140static const Target *GetTarget(const MachOObjectFile *MachOObj,
141 const char **McpuDefault,
142 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000143 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000144 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000145 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000146 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000147 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000148 }
149
150 if (TT.getArch() == Triple::arm) {
151 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
152 // that support ARM are also capable of Thumb mode.
153 llvm::Triple ThumbTriple = TT;
154 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
155 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000156 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 }
158
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000159 // Get the target specific parser.
160 std::string Error;
161 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000162 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000163 return TheTarget;
164
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000165 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
166 if (*ThumbTarget)
167 return TheTarget;
168
169 errs() << "llvm-objdump: error: unable to get target for '";
170 if (!TheTarget)
171 errs() << TripleName;
172 else
173 errs() << ThumbTripleName;
174 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000175 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000176}
177
Owen Andersond9243c42011-10-17 21:37:35 +0000178struct SymbolSorter {
179 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000180 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000181 if (!ATypeOrErr)
182 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000183 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000184 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000185 if (!BTypeOrErr)
186 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000187 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000188 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
189 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000190 return AAddr < BAddr;
191 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000192};
193
Kevin Enderby273ae012013-06-06 17:20:50 +0000194// Types for the storted data in code table that is built before disassembly
195// and the predicate function to sort them.
196typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
197typedef std::vector<DiceTableEntry> DiceTable;
198typedef DiceTable::iterator dice_table_iterator;
199
Francis Ricci195a66f2017-10-06 15:54:20 +0000200#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000201namespace {
202struct ScopedXarFile {
203 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000204 ScopedXarFile(const char *filename, int32_t flags)
205 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000206 ~ScopedXarFile() {
207 if (xar)
208 xar_close(xar);
209 }
210 ScopedXarFile(const ScopedXarFile &) = delete;
211 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
212 operator xar_t() { return xar; }
213};
214
215struct ScopedXarIter {
216 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000217 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000218 ~ScopedXarIter() {
219 if (iter)
220 xar_iter_free(iter);
221 }
222 ScopedXarIter(const ScopedXarIter &) = delete;
223 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
224 operator xar_iter_t() { return iter; }
225};
226} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000227#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000228
Kevin Enderby930fdc72014-11-06 19:00:13 +0000229// This is used to search for a data in code table entry for the PC being
230// disassembled. The j parameter has the PC in j.first. A single data in code
231// table entry can cover many bytes for each of its Kind's. So if the offset,
232// aka the i.first value, of the data in code table entry plus its Length
233// covers the PC being searched for this will return true. If not it will
234// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000235static bool compareDiceTableEntries(const DiceTableEntry &i,
236 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 uint16_t Length;
238 i.second.getLength(Length);
239
240 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000241}
242
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000243static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000244 unsigned short Kind) {
245 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000246
247 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000249 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 if (Length >= 4) {
251 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000252 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000253 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000254 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000255 Size = 4;
256 } else if (Length >= 2) {
257 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000258 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000259 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000260 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000261 Size = 2;
262 } else {
263 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000264 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000265 Value = bytes[0];
266 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000268 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000269 if (Kind == MachO::DICE_KIND_DATA)
270 outs() << "\t@ KIND_DATA\n";
271 else
272 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000273 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000274 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000275 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000276 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000277 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000278 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
279 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000280 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000281 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000282 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000283 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000284 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000285 outs() << "\t.short " << format("%5u", Value & 0xffff)
286 << "\t@ KIND_JUMP_TABLE16\n";
287 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000288 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000289 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000290 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
291 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000292 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000293 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000294 outs() << "\t.long " << Value;
295 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
296 outs() << "\t@ KIND_JUMP_TABLE32\n";
297 else
298 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
299 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000300 break;
301 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000302 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000303}
304
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000305static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000306 std::vector<SectionRef> &Sections,
307 std::vector<SymbolRef> &Symbols,
308 SmallVectorImpl<uint64_t> &FoundFns,
309 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000310 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000311 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000312 if (!SymName)
313 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000314 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000315 Symbols.push_back(Symbol);
316 }
Owen Andersond9243c42011-10-17 21:37:35 +0000317
Alexey Samsonov48803e52014-03-13 14:37:36 +0000318 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000319 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000320 Section.getName(SectName);
321 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000322 }
323
Kevin Enderby273ae012013-06-06 17:20:50 +0000324 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000325 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000326 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000327 // We found a function starts segment, parse the addresses for later
328 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000329 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000330 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000331
Charles Davis8bdfafd2013-09-01 04:28:48 +0000332 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000333 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
334 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000335 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000336 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000337 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000338 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000339 }
340 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000341 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000342}
343
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000344static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
345 uint32_t n, uint32_t count,
346 uint32_t stride, uint64_t addr) {
347 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
348 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
349 if (n > nindirectsyms)
350 outs() << " (entries start past the end of the indirect symbol "
351 "table) (reserved1 field greater than the table size)";
352 else if (n + count > nindirectsyms)
353 outs() << " (entries extends past the end of the indirect symbol "
354 "table)";
355 outs() << "\n";
356 uint32_t cputype = O->getHeader().cputype;
357 if (cputype & MachO::CPU_ARCH_ABI64)
358 outs() << "address index";
359 else
360 outs() << "address index";
361 if (verbose)
362 outs() << " name\n";
363 else
364 outs() << "\n";
365 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
366 if (cputype & MachO::CPU_ARCH_ABI64)
367 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
368 else
Tim Northover43978372016-04-26 18:29:16 +0000369 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000370 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
371 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
372 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
373 outs() << "LOCAL\n";
374 continue;
375 }
376 if (indirect_symbol ==
377 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
378 outs() << "LOCAL ABSOLUTE\n";
379 continue;
380 }
381 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
382 outs() << "ABSOLUTE\n";
383 continue;
384 }
385 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000386 if (verbose) {
387 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
388 if (indirect_symbol < Symtab.nsyms) {
389 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
390 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000391 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000392 if (!SymName)
393 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000394 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000395 } else {
396 outs() << "?";
397 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000398 }
399 outs() << "\n";
400 }
401}
402
403static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000404 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000405 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
406 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
407 for (unsigned J = 0; J < Seg.nsects; ++J) {
408 MachO::section_64 Sec = O->getSection64(Load, J);
409 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
410 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
411 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
412 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
413 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
414 section_type == MachO::S_SYMBOL_STUBS) {
415 uint32_t stride;
416 if (section_type == MachO::S_SYMBOL_STUBS)
417 stride = Sec.reserved2;
418 else
419 stride = 8;
420 if (stride == 0) {
421 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
422 << Sec.sectname << ") "
423 << "(size of stubs in reserved2 field is zero)\n";
424 continue;
425 }
426 uint32_t count = Sec.size / stride;
427 outs() << "Indirect symbols for (" << Sec.segname << ","
428 << Sec.sectname << ") " << count << " entries";
429 uint32_t n = Sec.reserved1;
430 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
431 }
432 }
433 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
434 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
435 for (unsigned J = 0; J < Seg.nsects; ++J) {
436 MachO::section Sec = O->getSection(Load, J);
437 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
438 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
439 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
440 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
441 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
442 section_type == MachO::S_SYMBOL_STUBS) {
443 uint32_t stride;
444 if (section_type == MachO::S_SYMBOL_STUBS)
445 stride = Sec.reserved2;
446 else
447 stride = 4;
448 if (stride == 0) {
449 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
450 << Sec.sectname << ") "
451 << "(size of stubs in reserved2 field is zero)\n";
452 continue;
453 }
454 uint32_t count = Sec.size / stride;
455 outs() << "Indirect symbols for (" << Sec.segname << ","
456 << Sec.sectname << ") " << count << " entries";
457 uint32_t n = Sec.reserved1;
458 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
459 }
460 }
461 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000462 }
463}
464
Michael Trenta1703b12017-12-15 17:57:40 +0000465static void PrintRType(const uint64_t cputype, const unsigned r_type) {
466 static char const *generic_r_types[] = {
467 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
468 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
469 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
470 };
471 static char const *x86_64_r_types[] = {
472 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
473 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
474 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
475 };
476 static char const *arm_r_types[] = {
477 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
478 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
479 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
480 };
481 static char const *arm64_r_types[] = {
482 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
483 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
484 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
485 };
486
487 if (r_type > 0xf){
488 outs() << format("%-7u", r_type) << " ";
489 return;
490 }
491 switch (cputype) {
492 case MachO::CPU_TYPE_I386:
493 outs() << generic_r_types[r_type];
494 break;
495 case MachO::CPU_TYPE_X86_64:
496 outs() << x86_64_r_types[r_type];
497 break;
498 case MachO::CPU_TYPE_ARM:
499 outs() << arm_r_types[r_type];
500 break;
501 case MachO::CPU_TYPE_ARM64:
502 outs() << arm64_r_types[r_type];
503 break;
504 default:
505 outs() << format("%-7u ", r_type);
506 }
507}
508
509static void PrintRLength(const uint64_t cputype, const unsigned r_type,
510 const unsigned r_length, const bool previous_arm_half){
511 if (cputype == MachO::CPU_TYPE_ARM &&
512 (r_type == llvm::MachO::ARM_RELOC_HALF ||
513 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
514 previous_arm_half == true)) {
515 if ((r_length & 0x1) == 0)
516 outs() << "lo/";
517 else
518 outs() << "hi/";
519 if ((r_length & 0x1) == 0)
520 outs() << "arm ";
521 else
522 outs() << "thm ";
523 } else {
524 switch (r_length) {
525 case 0:
526 outs() << "byte ";
527 break;
528 case 1:
529 outs() << "word ";
530 break;
531 case 2:
532 outs() << "long ";
533 break;
534 case 3:
535 if (cputype == MachO::CPU_TYPE_X86_64)
536 outs() << "quad ";
537 else
538 outs() << format("?(%2d) ", r_length);
539 break;
540 default:
541 outs() << format("?(%2d) ", r_length);
542 }
543 }
544}
545
546static void PrintRelocationEntries(const MachOObjectFile *O,
547 const relocation_iterator Begin,
548 const relocation_iterator End,
549 const uint64_t cputype,
550 const bool verbose) {
551 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
552 bool previous_arm_half = false;
553 bool previous_sectdiff = false;
554 uint32_t sectdiff_r_type = 0;
555
556 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
557 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
558 const MachO::any_relocation_info RE = O->getRelocation(Rel);
559 const unsigned r_type = O->getAnyRelocationType(RE);
560 const bool r_scattered = O->isRelocationScattered(RE);
561 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
562 const unsigned r_length = O->getAnyRelocationLength(RE);
563 const unsigned r_address = O->getAnyRelocationAddress(RE);
564 const bool r_extern = (r_scattered ? false :
565 O->getPlainRelocationExternal(RE));
566 const uint32_t r_value = (r_scattered ?
567 O->getScatteredRelocationValue(RE) : 0);
568 const unsigned r_symbolnum = (r_scattered ? 0 :
569 O->getPlainRelocationSymbolNum(RE));
570
571 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
572 if (verbose) {
573 // scattered: address
574 if ((cputype == MachO::CPU_TYPE_I386 &&
575 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
576 (cputype == MachO::CPU_TYPE_ARM &&
577 r_type == llvm::MachO::ARM_RELOC_PAIR))
578 outs() << " ";
579 else
580 outs() << format("%08x ", (unsigned int)r_address);
581
582 // scattered: pcrel
583 if (r_pcrel)
584 outs() << "True ";
585 else
586 outs() << "False ";
587
588 // scattered: length
589 PrintRLength(cputype, r_type, r_length, previous_arm_half);
590
591 // scattered: extern & type
592 outs() << "n/a ";
593 PrintRType(cputype, r_type);
594
595 // scattered: scattered & value
596 outs() << format("True 0x%08x", (unsigned int)r_value);
597 if (previous_sectdiff == false) {
598 if ((cputype == MachO::CPU_TYPE_ARM &&
599 r_type == llvm::MachO::ARM_RELOC_PAIR))
600 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
601 }
602 else if (cputype == MachO::CPU_TYPE_ARM &&
603 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
604 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
605 if ((cputype == MachO::CPU_TYPE_I386 &&
606 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
607 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
608 (cputype == MachO::CPU_TYPE_ARM &&
609 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
610 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
611 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
612 previous_sectdiff = true;
613 sectdiff_r_type = r_type;
614 }
615 else {
616 previous_sectdiff = false;
617 sectdiff_r_type = 0;
618 }
619 if (cputype == MachO::CPU_TYPE_ARM &&
620 (r_type == llvm::MachO::ARM_RELOC_HALF ||
621 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
622 previous_arm_half = true;
623 else
624 previous_arm_half = false;
625 outs() << "\n";
626 }
627 else {
628 // scattered: address pcrel length extern type scattered value
629 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
630 (unsigned int)r_address, r_pcrel, r_length, r_type,
631 (unsigned int)r_value);
632 }
633 }
634 else {
635 if (verbose) {
636 // plain: address
637 if (cputype == MachO::CPU_TYPE_ARM &&
638 r_type == llvm::MachO::ARM_RELOC_PAIR)
639 outs() << " ";
640 else
641 outs() << format("%08x ", (unsigned int)r_address);
642
643 // plain: pcrel
644 if (r_pcrel)
645 outs() << "True ";
646 else
647 outs() << "False ";
648
649 // plain: length
650 PrintRLength(cputype, r_type, r_length, previous_arm_half);
651
652 if (r_extern) {
653 // plain: extern & type & scattered
654 outs() << "True ";
655 PrintRType(cputype, r_type);
656 outs() << "False ";
657
658 // plain: symbolnum/value
659 if (r_symbolnum > Symtab.nsyms)
660 outs() << format("?(%d)\n", r_symbolnum);
661 else {
662 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
663 Expected<StringRef> SymNameNext = Symbol.getName();
664 const char *name = NULL;
665 if (SymNameNext)
666 name = SymNameNext->data();
667 if (name == NULL)
668 outs() << format("?(%d)\n", r_symbolnum);
669 else
670 outs() << name << "\n";
671 }
672 }
673 else {
674 // plain: extern & type & scattered
675 outs() << "False ";
676 PrintRType(cputype, r_type);
677 outs() << "False ";
678
679 // plain: symbolnum/value
680 if (cputype == MachO::CPU_TYPE_ARM &&
681 r_type == llvm::MachO::ARM_RELOC_PAIR)
682 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
683 else if (cputype == MachO::CPU_TYPE_ARM64 &&
684 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
685 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
686 else {
687 outs() << format("%d ", r_symbolnum);
688 if (r_symbolnum == llvm::MachO::R_ABS)
689 outs() << "R_ABS\n";
690 else {
691 // in this case, r_symbolnum is actually a 1-based section number
692 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
693 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
694 llvm::object::DataRefImpl DRI;
695 DRI.d.a = r_symbolnum-1;
696 StringRef SegName = O->getSectionFinalSegmentName(DRI);
697 StringRef SectName;
698 if (O->getSectionName(DRI, SectName))
699 outs() << "(?,?)\n";
700 else
701 outs() << "(" << SegName << "," << SectName << ")\n";
702 }
703 else {
704 outs() << "(?,?)\n";
705 }
706 }
707 }
708 }
709 if (cputype == MachO::CPU_TYPE_ARM &&
710 (r_type == llvm::MachO::ARM_RELOC_HALF ||
711 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
712 previous_arm_half = true;
713 else
714 previous_arm_half = false;
715 }
716 else {
717 // plain: address pcrel length extern type scattered symbolnum/section
718 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
719 (unsigned int)r_address, r_pcrel, r_length, r_extern,
720 r_type, r_symbolnum);
721 }
722 }
723 }
724}
725
726static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
727 const uint64_t cputype = O->getHeader().cputype;
728 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
729 if (Dysymtab.nextrel != 0) {
730 outs() << "External relocation information " << Dysymtab.nextrel
731 << " entries";
732 outs() << "\naddress pcrel length extern type scattered "
733 "symbolnum/value\n";
734 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
735 verbose);
736 }
737 if (Dysymtab.nlocrel != 0) {
738 outs() << format("Local relocation information %u entries",
739 Dysymtab.nlocrel);
740 outs() << "\naddress pcrel length extern type scattered "
741 "symbolnum/value\n";
742 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
743 verbose);
744 }
745 for (const auto &Load : O->load_commands()) {
746 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
747 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
748 for (unsigned J = 0; J < Seg.nsects; ++J) {
749 const MachO::section_64 Sec = O->getSection64(Load, J);
750 if (Sec.nreloc != 0) {
751 DataRefImpl DRI;
752 DRI.d.a = J;
753 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
754 StringRef SectName;
755 if (O->getSectionName(DRI, SectName))
756 outs() << "Relocation information (" << SegName << ",?) "
757 << format("%u entries", Sec.nreloc);
758 else
759 outs() << "Relocation information (" << SegName << ","
760 << SectName << format(") %u entries", Sec.nreloc);
761 outs() << "\naddress pcrel length extern type scattered "
762 "symbolnum/value\n";
763 PrintRelocationEntries(O, O->section_rel_begin(DRI),
764 O->section_rel_end(DRI), cputype, verbose);
765 }
766 }
767 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
768 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
769 for (unsigned J = 0; J < Seg.nsects; ++J) {
770 const MachO::section Sec = O->getSection(Load, J);
771 if (Sec.nreloc != 0) {
772 DataRefImpl DRI;
773 DRI.d.a = J;
774 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
775 StringRef SectName;
776 if (O->getSectionName(DRI, SectName))
777 outs() << "Relocation information (" << SegName << ",?) "
778 << format("%u entries", Sec.nreloc);
779 else
780 outs() << "Relocation information (" << SegName << ","
781 << SectName << format(") %u entries", Sec.nreloc);
782 outs() << "\naddress pcrel length extern type scattered "
783 "symbolnum/value\n";
784 PrintRelocationEntries(O, O->section_rel_begin(DRI),
785 O->section_rel_end(DRI), cputype, verbose);
786 }
787 }
788 }
789 }
790}
791
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000792static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
793 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
794 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
795 outs() << "Data in code table (" << nentries << " entries)\n";
796 outs() << "offset length kind\n";
797 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
798 ++DI) {
799 uint32_t Offset;
800 DI->getOffset(Offset);
801 outs() << format("0x%08" PRIx32, Offset) << " ";
802 uint16_t Length;
803 DI->getLength(Length);
804 outs() << format("%6u", Length) << " ";
805 uint16_t Kind;
806 DI->getKind(Kind);
807 if (verbose) {
808 switch (Kind) {
809 case MachO::DICE_KIND_DATA:
810 outs() << "DATA";
811 break;
812 case MachO::DICE_KIND_JUMP_TABLE8:
813 outs() << "JUMP_TABLE8";
814 break;
815 case MachO::DICE_KIND_JUMP_TABLE16:
816 outs() << "JUMP_TABLE16";
817 break;
818 case MachO::DICE_KIND_JUMP_TABLE32:
819 outs() << "JUMP_TABLE32";
820 break;
821 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
822 outs() << "ABS_JUMP_TABLE32";
823 break;
824 default:
825 outs() << format("0x%04" PRIx32, Kind);
826 break;
827 }
828 } else
829 outs() << format("0x%04" PRIx32, Kind);
830 outs() << "\n";
831 }
832}
833
Kevin Enderby9a509442015-01-27 21:28:24 +0000834static void PrintLinkOptHints(MachOObjectFile *O) {
835 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
836 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
837 uint32_t nloh = LohLC.datasize;
838 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
839 for (uint32_t i = 0; i < nloh;) {
840 unsigned n;
841 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
842 i += n;
843 outs() << " identifier " << identifier << " ";
844 if (i >= nloh)
845 return;
846 switch (identifier) {
847 case 1:
848 outs() << "AdrpAdrp\n";
849 break;
850 case 2:
851 outs() << "AdrpLdr\n";
852 break;
853 case 3:
854 outs() << "AdrpAddLdr\n";
855 break;
856 case 4:
857 outs() << "AdrpLdrGotLdr\n";
858 break;
859 case 5:
860 outs() << "AdrpAddStr\n";
861 break;
862 case 6:
863 outs() << "AdrpLdrGotStr\n";
864 break;
865 case 7:
866 outs() << "AdrpAdd\n";
867 break;
868 case 8:
869 outs() << "AdrpLdrGot\n";
870 break;
871 default:
872 outs() << "Unknown identifier value\n";
873 break;
874 }
875 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
876 i += n;
877 outs() << " narguments " << narguments << "\n";
878 if (i >= nloh)
879 return;
880
881 for (uint32_t j = 0; j < narguments; j++) {
882 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
883 i += n;
884 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
885 if (i >= nloh)
886 return;
887 }
888 }
889}
890
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000891static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000892 unsigned Index = 0;
893 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000894 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
895 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
896 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
897 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
898 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
899 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
900 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
901 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
902 if (dl.dylib.name < dl.cmdsize) {
903 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
904 if (JustId)
905 outs() << p << "\n";
906 else {
907 outs() << "\t" << p;
908 outs() << " (compatibility version "
909 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
910 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
911 << (dl.dylib.compatibility_version & 0xff) << ",";
912 outs() << " current version "
913 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
914 << ((dl.dylib.current_version >> 8) & 0xff) << "."
915 << (dl.dylib.current_version & 0xff) << ")\n";
916 }
917 } else {
918 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
919 if (Load.C.cmd == MachO::LC_ID_DYLIB)
920 outs() << "LC_ID_DYLIB ";
921 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
922 outs() << "LC_LOAD_DYLIB ";
923 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
924 outs() << "LC_LOAD_WEAK_DYLIB ";
925 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
926 outs() << "LC_LAZY_LOAD_DYLIB ";
927 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
928 outs() << "LC_REEXPORT_DYLIB ";
929 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
930 outs() << "LC_LOAD_UPWARD_DYLIB ";
931 else
932 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000933 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000934 }
935 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000936 }
937}
938
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000939typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
940
941static void CreateSymbolAddressMap(MachOObjectFile *O,
942 SymbolAddressMap *AddrMap) {
943 // Create a map of symbol addresses to symbol names.
944 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000945 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000946 if (!STOrErr)
947 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000948 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000949 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
950 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000951 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000952 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000953 if (!SymNameOrErr)
954 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000955 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000956 if (!SymName.startswith(".objc"))
957 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000958 }
959 }
960}
961
962// GuessSymbolName is passed the address of what might be a symbol and a
963// pointer to the SymbolAddressMap. It returns the name of a symbol
964// with that address or nullptr if no symbol is found with that address.
965static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
966 const char *SymbolName = nullptr;
967 // A DenseMap can't lookup up some values.
968 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
969 StringRef name = AddrMap->lookup(value);
970 if (!name.empty())
971 SymbolName = name.data();
972 }
973 return SymbolName;
974}
975
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000976static void DumpCstringChar(const char c) {
977 char p[2];
978 p[0] = c;
979 p[1] = '\0';
980 outs().write_escaped(p);
981}
982
Kevin Enderby10ba0412015-02-04 21:38:42 +0000983static void DumpCstringSection(MachOObjectFile *O, const char *sect,
984 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000985 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000986 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000987 if (print_addresses) {
988 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000989 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000990 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000991 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000992 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000993 for (; i < sect_size && sect[i] != '\0'; i++)
994 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000995 if (i < sect_size && sect[i] == '\0')
996 outs() << "\n";
997 }
998}
999
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001000static void DumpLiteral4(uint32_t l, float f) {
1001 outs() << format("0x%08" PRIx32, l);
1002 if ((l & 0x7f800000) != 0x7f800000)
1003 outs() << format(" (%.16e)\n", f);
1004 else {
1005 if (l == 0x7f800000)
1006 outs() << " (+Infinity)\n";
1007 else if (l == 0xff800000)
1008 outs() << " (-Infinity)\n";
1009 else if ((l & 0x00400000) == 0x00400000)
1010 outs() << " (non-signaling Not-a-Number)\n";
1011 else
1012 outs() << " (signaling Not-a-Number)\n";
1013 }
1014}
1015
1016static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1017 uint32_t sect_size, uint64_t sect_addr,
1018 bool print_addresses) {
1019 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1020 if (print_addresses) {
1021 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001022 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001023 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001024 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001025 }
1026 float f;
1027 memcpy(&f, sect + i, sizeof(float));
1028 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1029 sys::swapByteOrder(f);
1030 uint32_t l;
1031 memcpy(&l, sect + i, sizeof(uint32_t));
1032 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1033 sys::swapByteOrder(l);
1034 DumpLiteral4(l, f);
1035 }
1036}
1037
1038static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1039 double d) {
1040 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1041 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001042 Hi = (O->isLittleEndian()) ? l1 : l0;
1043 Lo = (O->isLittleEndian()) ? l0 : l1;
1044
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001045 // Hi is the high word, so this is equivalent to if(isfinite(d))
1046 if ((Hi & 0x7ff00000) != 0x7ff00000)
1047 outs() << format(" (%.16e)\n", d);
1048 else {
1049 if (Hi == 0x7ff00000 && Lo == 0)
1050 outs() << " (+Infinity)\n";
1051 else if (Hi == 0xfff00000 && Lo == 0)
1052 outs() << " (-Infinity)\n";
1053 else if ((Hi & 0x00080000) == 0x00080000)
1054 outs() << " (non-signaling Not-a-Number)\n";
1055 else
1056 outs() << " (signaling Not-a-Number)\n";
1057 }
1058}
1059
1060static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1061 uint32_t sect_size, uint64_t sect_addr,
1062 bool print_addresses) {
1063 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1064 if (print_addresses) {
1065 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001066 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001067 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001068 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001069 }
1070 double d;
1071 memcpy(&d, sect + i, sizeof(double));
1072 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1073 sys::swapByteOrder(d);
1074 uint32_t l0, l1;
1075 memcpy(&l0, sect + i, sizeof(uint32_t));
1076 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1077 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1078 sys::swapByteOrder(l0);
1079 sys::swapByteOrder(l1);
1080 }
1081 DumpLiteral8(O, l0, l1, d);
1082 }
1083}
1084
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001085static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1086 outs() << format("0x%08" PRIx32, l0) << " ";
1087 outs() << format("0x%08" PRIx32, l1) << " ";
1088 outs() << format("0x%08" PRIx32, l2) << " ";
1089 outs() << format("0x%08" PRIx32, l3) << "\n";
1090}
1091
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001092static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1093 uint32_t sect_size, uint64_t sect_addr,
1094 bool print_addresses) {
1095 for (uint32_t i = 0; i < sect_size; i += 16) {
1096 if (print_addresses) {
1097 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001098 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001099 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001100 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001101 }
1102 uint32_t l0, l1, l2, l3;
1103 memcpy(&l0, sect + i, sizeof(uint32_t));
1104 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1105 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1106 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1107 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1108 sys::swapByteOrder(l0);
1109 sys::swapByteOrder(l1);
1110 sys::swapByteOrder(l2);
1111 sys::swapByteOrder(l3);
1112 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001113 DumpLiteral16(l0, l1, l2, l3);
1114 }
1115}
1116
1117static void DumpLiteralPointerSection(MachOObjectFile *O,
1118 const SectionRef &Section,
1119 const char *sect, uint32_t sect_size,
1120 uint64_t sect_addr,
1121 bool print_addresses) {
1122 // Collect the literal sections in this Mach-O file.
1123 std::vector<SectionRef> LiteralSections;
1124 for (const SectionRef &Section : O->sections()) {
1125 DataRefImpl Ref = Section.getRawDataRefImpl();
1126 uint32_t section_type;
1127 if (O->is64Bit()) {
1128 const MachO::section_64 Sec = O->getSection64(Ref);
1129 section_type = Sec.flags & MachO::SECTION_TYPE;
1130 } else {
1131 const MachO::section Sec = O->getSection(Ref);
1132 section_type = Sec.flags & MachO::SECTION_TYPE;
1133 }
1134 if (section_type == MachO::S_CSTRING_LITERALS ||
1135 section_type == MachO::S_4BYTE_LITERALS ||
1136 section_type == MachO::S_8BYTE_LITERALS ||
1137 section_type == MachO::S_16BYTE_LITERALS)
1138 LiteralSections.push_back(Section);
1139 }
1140
1141 // Set the size of the literal pointer.
1142 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1143
Eric Christopher572e03a2015-06-19 01:53:21 +00001144 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001145 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1146 for (const RelocationRef &Reloc : Section.relocations()) {
1147 DataRefImpl Rel;
1148 MachO::any_relocation_info RE;
1149 bool isExtern = false;
1150 Rel = Reloc.getRawDataRefImpl();
1151 RE = O->getRelocation(Rel);
1152 isExtern = O->getPlainRelocationExternal(RE);
1153 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001154 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001155 symbol_iterator RelocSym = Reloc.getSymbol();
1156 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1157 }
1158 }
1159 array_pod_sort(Relocs.begin(), Relocs.end());
1160
1161 // Dump each literal pointer.
1162 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1163 if (print_addresses) {
1164 if (O->is64Bit())
1165 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1166 else
1167 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1168 }
1169 uint64_t lp;
1170 if (O->is64Bit()) {
1171 memcpy(&lp, sect + i, sizeof(uint64_t));
1172 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1173 sys::swapByteOrder(lp);
1174 } else {
1175 uint32_t li;
1176 memcpy(&li, sect + i, sizeof(uint32_t));
1177 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1178 sys::swapByteOrder(li);
1179 lp = li;
1180 }
1181
1182 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001183 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1184 return P.first == i;
1185 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001186 if (Reloc != Relocs.end()) {
1187 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001188 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001189 if (!SymName)
1190 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001191 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001192 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001193 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001194
1195 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001196 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1197 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1198 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001199 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001200 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001201 continue;
1202 }
1203
1204 uint64_t SectAddress = Sect->getAddress();
1205 uint64_t SectSize = Sect->getSize();
1206
1207 StringRef SectName;
1208 Sect->getName(SectName);
1209 DataRefImpl Ref = Sect->getRawDataRefImpl();
1210 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1211 outs() << SegmentName << ":" << SectName << ":";
1212
1213 uint32_t section_type;
1214 if (O->is64Bit()) {
1215 const MachO::section_64 Sec = O->getSection64(Ref);
1216 section_type = Sec.flags & MachO::SECTION_TYPE;
1217 } else {
1218 const MachO::section Sec = O->getSection(Ref);
1219 section_type = Sec.flags & MachO::SECTION_TYPE;
1220 }
1221
1222 StringRef BytesStr;
1223 Sect->getContents(BytesStr);
1224 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1225
1226 switch (section_type) {
1227 case MachO::S_CSTRING_LITERALS:
1228 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1229 i++) {
1230 DumpCstringChar(Contents[i]);
1231 }
1232 outs() << "\n";
1233 break;
1234 case MachO::S_4BYTE_LITERALS:
1235 float f;
1236 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1237 uint32_t l;
1238 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1239 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1240 sys::swapByteOrder(f);
1241 sys::swapByteOrder(l);
1242 }
1243 DumpLiteral4(l, f);
1244 break;
1245 case MachO::S_8BYTE_LITERALS: {
1246 double d;
1247 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1248 uint32_t l0, l1;
1249 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1250 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1251 sizeof(uint32_t));
1252 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1253 sys::swapByteOrder(f);
1254 sys::swapByteOrder(l0);
1255 sys::swapByteOrder(l1);
1256 }
1257 DumpLiteral8(O, l0, l1, d);
1258 break;
1259 }
1260 case MachO::S_16BYTE_LITERALS: {
1261 uint32_t l0, l1, l2, l3;
1262 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1263 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1264 sizeof(uint32_t));
1265 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1266 sizeof(uint32_t));
1267 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1268 sizeof(uint32_t));
1269 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1270 sys::swapByteOrder(l0);
1271 sys::swapByteOrder(l1);
1272 sys::swapByteOrder(l2);
1273 sys::swapByteOrder(l3);
1274 }
1275 DumpLiteral16(l0, l1, l2, l3);
1276 break;
1277 }
1278 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001279 }
1280}
1281
Kevin Enderby85b7a662018-03-20 20:29:52 +00001282static void DumpInitTermPointerSection(MachOObjectFile *O,
1283 const SectionRef &Section,
1284 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001285 uint32_t sect_size, uint64_t sect_addr,
1286 SymbolAddressMap *AddrMap,
1287 bool verbose) {
1288 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001289 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001290
1291 // Collect the external relocation symbols for the pointers.
1292 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1293 for (const RelocationRef &Reloc : Section.relocations()) {
1294 DataRefImpl Rel;
1295 MachO::any_relocation_info RE;
1296 bool isExtern = false;
1297 Rel = Reloc.getRawDataRefImpl();
1298 RE = O->getRelocation(Rel);
1299 isExtern = O->getPlainRelocationExternal(RE);
1300 if (isExtern) {
1301 uint64_t RelocOffset = Reloc.getOffset();
1302 symbol_iterator RelocSym = Reloc.getSymbol();
1303 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1304 }
1305 }
1306 array_pod_sort(Relocs.begin(), Relocs.end());
1307
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001308 for (uint32_t i = 0; i < sect_size; i += stride) {
1309 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001310 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001311 if (O->is64Bit()) {
1312 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1313 uint64_t pointer_value;
1314 memcpy(&pointer_value, sect + i, stride);
1315 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1316 sys::swapByteOrder(pointer_value);
1317 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001318 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001319 } else {
1320 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1321 uint32_t pointer_value;
1322 memcpy(&pointer_value, sect + i, stride);
1323 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1324 sys::swapByteOrder(pointer_value);
1325 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001326 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001327 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001328 if (verbose) {
1329 // First look for an external relocation entry for this pointer.
1330 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1331 return P.first == i;
1332 });
1333 if (Reloc != Relocs.end()) {
1334 symbol_iterator RelocSym = Reloc->second;
1335 Expected<StringRef> SymName = RelocSym->getName();
1336 if (!SymName)
1337 report_error(O->getFileName(), SymName.takeError());
1338 outs() << " " << *SymName;
1339 } else {
1340 SymbolName = GuessSymbolName(p, AddrMap);
1341 if (SymbolName)
1342 outs() << " " << SymbolName;
1343 }
1344 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001345 outs() << "\n";
1346 }
1347}
1348
1349static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1350 uint32_t size, uint64_t addr) {
1351 uint32_t cputype = O->getHeader().cputype;
1352 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1353 uint32_t j;
1354 for (uint32_t i = 0; i < size; i += j, addr += j) {
1355 if (O->is64Bit())
1356 outs() << format("%016" PRIx64, addr) << "\t";
1357 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001358 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001359 for (j = 0; j < 16 && i + j < size; j++) {
1360 uint8_t byte_word = *(sect + i + j);
1361 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1362 }
1363 outs() << "\n";
1364 }
1365 } else {
1366 uint32_t j;
1367 for (uint32_t i = 0; i < size; i += j, addr += j) {
1368 if (O->is64Bit())
1369 outs() << format("%016" PRIx64, addr) << "\t";
1370 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001371 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001372 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1373 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001374 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001375 uint32_t long_word;
1376 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1377 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1378 sys::swapByteOrder(long_word);
1379 outs() << format("%08" PRIx32, long_word) << " ";
1380 } else {
1381 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001382 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001383 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1384 }
1385 }
1386 }
1387 outs() << "\n";
1388 }
1389 }
1390}
1391
Kevin Enderby95df54c2015-02-04 01:01:38 +00001392static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1393 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001394static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1395 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001396#ifdef HAVE_LIBXAR
1397static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1398 uint32_t size, bool verbose,
1399 bool PrintXarHeader, bool PrintXarFileHeaders,
1400 std::string XarMemberName);
1401#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001402
1403static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1404 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001405 SymbolAddressMap AddrMap;
1406 if (verbose)
1407 CreateSymbolAddressMap(O, &AddrMap);
1408
Colin LeMahieufcc32762015-07-29 19:08:10 +00001409 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1410 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001411 std::pair<StringRef, StringRef> DumpSegSectName;
1412 DumpSegSectName = DumpSection.split(',');
1413 StringRef DumpSegName, DumpSectName;
1414 if (DumpSegSectName.second.size()) {
1415 DumpSegName = DumpSegSectName.first;
1416 DumpSectName = DumpSegSectName.second;
1417 } else {
1418 DumpSegName = "";
1419 DumpSectName = DumpSegSectName.first;
1420 }
1421 for (const SectionRef &Section : O->sections()) {
1422 StringRef SectName;
1423 Section.getName(SectName);
1424 DataRefImpl Ref = Section.getRawDataRefImpl();
1425 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1426 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1427 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001428
Kevin Enderby95df54c2015-02-04 01:01:38 +00001429 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001430 if (O->is64Bit()) {
1431 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001432 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001433
1434 } else {
1435 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001436 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001437 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001438 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001439
1440 StringRef BytesStr;
1441 Section.getContents(BytesStr);
1442 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1443 uint32_t sect_size = BytesStr.size();
1444 uint64_t sect_addr = Section.getAddress();
1445
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001446 outs() << "Contents of (" << SegName << "," << SectName
1447 << ") section\n";
1448
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001449 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001450 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1451 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1452 DisassembleMachO(Filename, O, SegName, SectName);
1453 continue;
1454 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001455 if (SegName == "__TEXT" && SectName == "__info_plist") {
1456 outs() << sect;
1457 continue;
1458 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001459 if (SegName == "__OBJC" && SectName == "__protocol") {
1460 DumpProtocolSection(O, sect, sect_size, sect_addr);
1461 continue;
1462 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001463#ifdef HAVE_LIBXAR
1464 if (SegName == "__LLVM" && SectName == "__bundle") {
1465 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1466 ArchiveHeaders, "");
1467 continue;
1468 }
1469#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001470 switch (section_type) {
1471 case MachO::S_REGULAR:
1472 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1473 break;
1474 case MachO::S_ZEROFILL:
1475 outs() << "zerofill section and has no contents in the file\n";
1476 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001477 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001478 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001479 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001480 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001481 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001482 break;
1483 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001484 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001485 break;
1486 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001487 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1488 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001489 case MachO::S_LITERAL_POINTERS:
1490 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001491 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001492 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001493 case MachO::S_MOD_INIT_FUNC_POINTERS:
1494 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001495 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1496 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001497 break;
1498 default:
1499 outs() << "Unknown section type ("
1500 << format("0x%08" PRIx32, section_type) << ")\n";
1501 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1502 break;
1503 }
1504 } else {
1505 if (section_type == MachO::S_ZEROFILL)
1506 outs() << "zerofill section and has no contents in the file\n";
1507 else
1508 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1509 }
1510 }
1511 }
1512 }
1513}
1514
Kevin Enderbycd66be52015-03-11 22:06:32 +00001515static void DumpInfoPlistSectionContents(StringRef Filename,
1516 MachOObjectFile *O) {
1517 for (const SectionRef &Section : O->sections()) {
1518 StringRef SectName;
1519 Section.getName(SectName);
1520 DataRefImpl Ref = Section.getRawDataRefImpl();
1521 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1522 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001523 if (!NoLeadingHeaders)
1524 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001525 StringRef BytesStr;
1526 Section.getContents(BytesStr);
1527 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001528 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001529 return;
1530 }
1531 }
1532}
1533
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001534// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1535// and if it is and there is a list of architecture flags is specified then
1536// check to make sure this Mach-O file is one of those architectures or all
1537// architectures were specified. If not then an error is generated and this
1538// routine returns false. Else it returns true.
1539static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001540 auto *MachO = dyn_cast<MachOObjectFile>(O);
1541
1542 if (!MachO || ArchAll || ArchFlags.empty())
1543 return true;
1544
1545 MachO::mach_header H;
1546 MachO::mach_header_64 H_64;
1547 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001548 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001549 if (MachO->is64Bit()) {
1550 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001551 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1552 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001553 } else {
1554 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001555 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1556 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001557 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001558 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001559 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001560 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001561 })) {
1562 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1563 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001564 }
1565 return true;
1566}
1567
Kevin Enderby0fc11822015-04-01 20:57:01 +00001568static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1569
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001570// ProcessMachO() is passed a single opened Mach-O file, which may be an
1571// archive member and or in a slice of a universal file. It prints the
1572// the file name and header info and then processes it according to the
1573// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001574static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001575 StringRef ArchiveMemberName = StringRef(),
1576 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001577 // If we are doing some processing here on the Mach-O file print the header
1578 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001579 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001580 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1581 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1582 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1583 (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001584 if (!NoLeadingHeaders) {
1585 outs() << Name;
1586 if (!ArchiveMemberName.empty())
1587 outs() << '(' << ArchiveMemberName << ')';
1588 if (!ArchitectureName.empty())
1589 outs() << " (architecture " << ArchitectureName << ")";
1590 outs() << ":\n";
1591 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001592 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001593 // To use the report_error() form with an ArchiveName and FileName set
1594 // these up based on what is passed for Name and ArchiveMemberName.
1595 StringRef ArchiveName;
1596 StringRef FileName;
1597 if (!ArchiveMemberName.empty()) {
1598 ArchiveName = Name;
1599 FileName = ArchiveMemberName;
1600 } else {
1601 ArchiveName = StringRef();
1602 FileName = Name;
1603 }
1604
1605 // If we need the symbol table to do the operation then check it here to
1606 // produce a good error message as to where the Mach-O file comes from in
1607 // the error message.
1608 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1609 UnwindInfo)
1610 if (Error Err = MachOOF->checkSymbolTable())
1611 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001612
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001613 if (Disassemble) {
1614 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001615 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001616 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1617 else
1618 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1619 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001620 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001621 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001622 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001623 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001624 if (LinkOptHints)
1625 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001626 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001627 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001628 if (SectionHeaders)
1629 PrintSectionHeaders(MachOOF);
1630 if (SectionContents)
1631 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001632 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001633 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001634 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001635 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001636 if (DylibsUsed)
1637 PrintDylibs(MachOOF, false);
1638 if (DylibId)
1639 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001640 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001641 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001642 if (UnwindInfo)
1643 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001644 if (PrivateHeaders) {
1645 printMachOFileHeader(MachOOF);
1646 printMachOLoadCommands(MachOOF);
1647 }
1648 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001649 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001650 if (ObjcMetaData)
1651 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001652 if (ExportsTrie)
1653 printExportsTrie(MachOOF);
1654 if (Rebase)
1655 printRebaseTable(MachOOF);
1656 if (Bind)
1657 printBindTable(MachOOF);
1658 if (LazyBind)
1659 printLazyBindTable(MachOOF);
1660 if (WeakBind)
1661 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001662
1663 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001664 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001665 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001666 DIDumpOptions DumpOpts;
1667 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001668 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001669 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001670}
1671
Kevin Enderby131d1772015-01-09 19:22:37 +00001672// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1673static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1674 outs() << " cputype (" << cputype << ")\n";
1675 outs() << " cpusubtype (" << cpusubtype << ")\n";
1676}
1677
1678// printCPUType() helps print_fat_headers by printing the cputype and
1679// pusubtype (symbolically for the one's it knows about).
1680static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1681 switch (cputype) {
1682 case MachO::CPU_TYPE_I386:
1683 switch (cpusubtype) {
1684 case MachO::CPU_SUBTYPE_I386_ALL:
1685 outs() << " cputype CPU_TYPE_I386\n";
1686 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1687 break;
1688 default:
1689 printUnknownCPUType(cputype, cpusubtype);
1690 break;
1691 }
1692 break;
1693 case MachO::CPU_TYPE_X86_64:
1694 switch (cpusubtype) {
1695 case MachO::CPU_SUBTYPE_X86_64_ALL:
1696 outs() << " cputype CPU_TYPE_X86_64\n";
1697 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1698 break;
1699 case MachO::CPU_SUBTYPE_X86_64_H:
1700 outs() << " cputype CPU_TYPE_X86_64\n";
1701 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1702 break;
1703 default:
1704 printUnknownCPUType(cputype, cpusubtype);
1705 break;
1706 }
1707 break;
1708 case MachO::CPU_TYPE_ARM:
1709 switch (cpusubtype) {
1710 case MachO::CPU_SUBTYPE_ARM_ALL:
1711 outs() << " cputype CPU_TYPE_ARM\n";
1712 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1713 break;
1714 case MachO::CPU_SUBTYPE_ARM_V4T:
1715 outs() << " cputype CPU_TYPE_ARM\n";
1716 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1717 break;
1718 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1719 outs() << " cputype CPU_TYPE_ARM\n";
1720 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1721 break;
1722 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1723 outs() << " cputype CPU_TYPE_ARM\n";
1724 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1725 break;
1726 case MachO::CPU_SUBTYPE_ARM_V6:
1727 outs() << " cputype CPU_TYPE_ARM\n";
1728 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1729 break;
1730 case MachO::CPU_SUBTYPE_ARM_V6M:
1731 outs() << " cputype CPU_TYPE_ARM\n";
1732 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1733 break;
1734 case MachO::CPU_SUBTYPE_ARM_V7:
1735 outs() << " cputype CPU_TYPE_ARM\n";
1736 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1737 break;
1738 case MachO::CPU_SUBTYPE_ARM_V7EM:
1739 outs() << " cputype CPU_TYPE_ARM\n";
1740 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1741 break;
1742 case MachO::CPU_SUBTYPE_ARM_V7K:
1743 outs() << " cputype CPU_TYPE_ARM\n";
1744 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1745 break;
1746 case MachO::CPU_SUBTYPE_ARM_V7M:
1747 outs() << " cputype CPU_TYPE_ARM\n";
1748 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1749 break;
1750 case MachO::CPU_SUBTYPE_ARM_V7S:
1751 outs() << " cputype CPU_TYPE_ARM\n";
1752 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1753 break;
1754 default:
1755 printUnknownCPUType(cputype, cpusubtype);
1756 break;
1757 }
1758 break;
1759 case MachO::CPU_TYPE_ARM64:
1760 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1761 case MachO::CPU_SUBTYPE_ARM64_ALL:
1762 outs() << " cputype CPU_TYPE_ARM64\n";
1763 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1764 break;
1765 default:
1766 printUnknownCPUType(cputype, cpusubtype);
1767 break;
1768 }
1769 break;
1770 default:
1771 printUnknownCPUType(cputype, cpusubtype);
1772 break;
1773 }
1774}
1775
1776static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1777 bool verbose) {
1778 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001779 if (verbose) {
1780 if (UB->getMagic() == MachO::FAT_MAGIC)
1781 outs() << "fat_magic FAT_MAGIC\n";
1782 else // UB->getMagic() == MachO::FAT_MAGIC_64
1783 outs() << "fat_magic FAT_MAGIC_64\n";
1784 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001785 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1786
1787 uint32_t nfat_arch = UB->getNumberOfObjects();
1788 StringRef Buf = UB->getData();
1789 uint64_t size = Buf.size();
1790 uint64_t big_size = sizeof(struct MachO::fat_header) +
1791 nfat_arch * sizeof(struct MachO::fat_arch);
1792 outs() << "nfat_arch " << UB->getNumberOfObjects();
1793 if (nfat_arch == 0)
1794 outs() << " (malformed, contains zero architecture types)\n";
1795 else if (big_size > size)
1796 outs() << " (malformed, architectures past end of file)\n";
1797 else
1798 outs() << "\n";
1799
1800 for (uint32_t i = 0; i < nfat_arch; ++i) {
1801 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1802 uint32_t cputype = OFA.getCPUType();
1803 uint32_t cpusubtype = OFA.getCPUSubType();
1804 outs() << "architecture ";
1805 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1806 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1807 uint32_t other_cputype = other_OFA.getCPUType();
1808 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001809 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001810 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001811 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001812 outs() << "(illegal duplicate architecture) ";
1813 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001814 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001815 }
1816 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001817 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001818 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1819 } else {
1820 outs() << i << "\n";
1821 outs() << " cputype " << cputype << "\n";
1822 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1823 << "\n";
1824 }
1825 if (verbose &&
1826 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1827 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1828 else
1829 outs() << " capabilities "
1830 << format("0x%" PRIx32,
1831 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1832 outs() << " offset " << OFA.getOffset();
1833 if (OFA.getOffset() > size)
1834 outs() << " (past end of file)";
1835 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1836 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1837 outs() << "\n";
1838 outs() << " size " << OFA.getSize();
1839 big_size = OFA.getOffset() + OFA.getSize();
1840 if (big_size > size)
1841 outs() << " (past end of file)";
1842 outs() << "\n";
1843 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1844 << ")\n";
1845 }
1846}
1847
Kevin Enderby6524bd82016-07-19 20:47:07 +00001848static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1849 bool verbose, bool print_offset,
1850 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001851 if (print_offset)
1852 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001853 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1854 if (!ModeOrErr)
1855 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1856 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001857 if (verbose) {
1858 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1859 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1860 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001861 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1862 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1863 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1864 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1865 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1866 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1867 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1868 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1869 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001870 } else {
1871 outs() << format("0%o ", Mode);
1872 }
1873
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001874 Expected<unsigned> UIDOrErr = C.getUID();
1875 if (!UIDOrErr)
1876 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1877 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001878 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001879 Expected<unsigned> GIDOrErr = C.getGID();
1880 if (!GIDOrErr)
1881 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1882 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001883 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001884 Expected<uint64_t> Size = C.getRawSize();
1885 if (!Size)
1886 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001887 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001888
1889 StringRef RawLastModified = C.getRawLastModified();
1890 if (verbose) {
1891 unsigned Seconds;
1892 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001893 outs() << "(date: \"" << RawLastModified
1894 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001895 else {
1896 // Since cime(3) returns a 26 character string of the form:
1897 // "Sun Sep 16 01:03:52 1973\n\0"
1898 // just print 24 characters.
1899 time_t t = Seconds;
1900 outs() << format("%.24s ", ctime(&t));
1901 }
1902 } else {
1903 outs() << RawLastModified << " ";
1904 }
1905
1906 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001907 Expected<StringRef> NameOrErr = C.getName();
1908 if (!NameOrErr) {
1909 consumeError(NameOrErr.takeError());
1910 Expected<StringRef> NameOrErr = C.getRawName();
1911 if (!NameOrErr)
1912 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1913 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001914 outs() << RawName << "\n";
1915 } else {
1916 StringRef Name = NameOrErr.get();
1917 outs() << Name << "\n";
1918 }
1919 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001920 Expected<StringRef> NameOrErr = C.getRawName();
1921 if (!NameOrErr)
1922 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1923 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001924 outs() << RawName << "\n";
1925 }
1926}
1927
Kevin Enderby6524bd82016-07-19 20:47:07 +00001928static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1929 bool print_offset,
1930 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001931 Error Err = Error::success();
1932 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001933 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001934 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1935
Lang Hamesfc209622016-07-14 02:24:01 +00001936 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001937 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001938}
1939
Dave Lee3fb120f2018-08-03 00:06:38 +00001940static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001941 // Check for -arch all and verifiy the -arch flags are valid.
1942 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1943 if (ArchFlags[i] == "all") {
1944 ArchAll = true;
1945 } else {
1946 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1947 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1948 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00001949 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001950 }
1951 }
1952 }
Dave Lee3fb120f2018-08-03 00:06:38 +00001953 return true;
1954}
1955
1956// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1957// -arch flags selecting just those slices as specified by them and also parses
1958// archive files. Then for each individual Mach-O file ProcessMachO() is
1959// called to process the file based on the command line options.
1960void llvm::ParseInputMachO(StringRef Filename) {
1961 if (!ValidateArchFlags())
1962 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001963
1964 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001965 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001966 if (!BinaryOrErr) {
1967 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1968 report_error(Filename, std::move(E));
1969 else
1970 outs() << Filename << ": is not an object file\n";
1971 return;
1972 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001973 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001974
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001975 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1976 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001977 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001978 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1979
Mehdi Amini41af4302016-11-11 04:28:40 +00001980 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001981 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001982 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1983 if (!ChildOrErr) {
1984 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1985 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001986 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001987 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001988 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1989 if (!checkMachOAndArchFlags(O, Filename))
1990 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001991 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001992 }
1993 }
Lang Hamesfc209622016-07-14 02:24:01 +00001994 if (Err)
1995 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001996 return;
1997 }
1998 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
Dave Lee3fb120f2018-08-03 00:06:38 +00001999 ParseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002000 return;
2001 }
2002 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2003 if (!checkMachOAndArchFlags(O, Filename))
2004 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002005 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002006 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002007 else
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002008 errs() << "llvm-objdump: '" << Filename << "': "
2009 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002010 return;
2011 }
2012 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002013}
2014
Dave Lee3fb120f2018-08-03 00:06:38 +00002015void llvm::ParseInputMachO(MachOUniversalBinary *UB) {
2016 if (!ValidateArchFlags())
2017 return;
2018
2019 auto Filename = UB->getFileName();
2020
2021 if (UniversalHeaders)
2022 printMachOUniversalHeaders(UB, !NonVerbose);
2023
2024 // If we have a list of architecture flags specified dump only those.
2025 if (!ArchAll && ArchFlags.size() != 0) {
2026 // Look for a slice in the universal binary that matches each ArchFlag.
2027 bool ArchFound;
2028 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2029 ArchFound = false;
2030 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2031 E = UB->end_objects();
2032 I != E; ++I) {
2033 if (ArchFlags[i] == I->getArchFlagName()) {
2034 ArchFound = true;
2035 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2036 I->getAsObjectFile();
2037 std::string ArchitectureName = "";
2038 if (ArchFlags.size() > 1)
2039 ArchitectureName = I->getArchFlagName();
2040 if (ObjOrErr) {
2041 ObjectFile &O = *ObjOrErr.get();
2042 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2043 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2044 } else if (auto E = isNotObjectErrorInvalidFileType(
2045 ObjOrErr.takeError())) {
2046 report_error(Filename, StringRef(), std::move(E),
2047 ArchitectureName);
2048 continue;
2049 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2050 I->getAsArchive()) {
2051 std::unique_ptr<Archive> &A = *AOrErr;
2052 outs() << "Archive : " << Filename;
2053 if (!ArchitectureName.empty())
2054 outs() << " (architecture " << ArchitectureName << ")";
2055 outs() << "\n";
2056 if (ArchiveHeaders)
2057 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2058 ArchiveMemberOffsets, ArchitectureName);
2059 Error Err = Error::success();
2060 for (auto &C : A->children(Err)) {
2061 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2062 if (!ChildOrErr) {
2063 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2064 report_error(Filename, C, std::move(E), ArchitectureName);
2065 continue;
2066 }
2067 if (MachOObjectFile *O =
2068 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2069 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2070 }
2071 if (Err)
2072 report_error(Filename, std::move(Err));
2073 } else {
2074 consumeError(AOrErr.takeError());
2075 error("Mach-O universal file: " + Filename + " for " +
2076 "architecture " + StringRef(I->getArchFlagName()) +
2077 " is not a Mach-O file or an archive file");
2078 }
2079 }
2080 }
2081 if (!ArchFound) {
2082 errs() << "llvm-objdump: file: " + Filename + " does not contain "
2083 << "architecture: " + ArchFlags[i] + "\n";
2084 return;
2085 }
2086 }
2087 return;
2088 }
2089 // No architecture flags were specified so if this contains a slice that
2090 // matches the host architecture dump only that.
2091 if (!ArchAll) {
2092 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2093 E = UB->end_objects();
2094 I != E; ++I) {
2095 if (MachOObjectFile::getHostArch().getArchName() ==
2096 I->getArchFlagName()) {
2097 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2098 std::string ArchiveName;
2099 ArchiveName.clear();
2100 if (ObjOrErr) {
2101 ObjectFile &O = *ObjOrErr.get();
2102 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2103 ProcessMachO(Filename, MachOOF);
2104 } else if (auto E = isNotObjectErrorInvalidFileType(
2105 ObjOrErr.takeError())) {
2106 report_error(Filename, std::move(E));
2107 continue;
2108 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2109 I->getAsArchive()) {
2110 std::unique_ptr<Archive> &A = *AOrErr;
2111 outs() << "Archive : " << Filename << "\n";
2112 if (ArchiveHeaders)
2113 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2114 ArchiveMemberOffsets);
2115 Error Err = Error::success();
2116 for (auto &C : A->children(Err)) {
2117 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2118 if (!ChildOrErr) {
2119 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2120 report_error(Filename, C, std::move(E));
2121 continue;
2122 }
2123 if (MachOObjectFile *O =
2124 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2125 ProcessMachO(Filename, O, O->getFileName());
2126 }
2127 if (Err)
2128 report_error(Filename, std::move(Err));
2129 } else {
2130 consumeError(AOrErr.takeError());
2131 error("Mach-O universal file: " + Filename + " for architecture " +
2132 StringRef(I->getArchFlagName()) +
2133 " is not a Mach-O file or an archive file");
2134 }
2135 return;
2136 }
2137 }
2138 }
2139 // Either all architectures have been specified or none have been specified
2140 // and this does not contain the host architecture so dump all the slices.
2141 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2142 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2143 E = UB->end_objects();
2144 I != E; ++I) {
2145 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2146 std::string ArchitectureName = "";
2147 if (moreThanOneArch)
2148 ArchitectureName = I->getArchFlagName();
2149 if (ObjOrErr) {
2150 ObjectFile &Obj = *ObjOrErr.get();
2151 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2152 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2153 } else if (auto E = isNotObjectErrorInvalidFileType(
2154 ObjOrErr.takeError())) {
2155 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
2156 continue;
2157 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2158 I->getAsArchive()) {
2159 std::unique_ptr<Archive> &A = *AOrErr;
2160 outs() << "Archive : " << Filename;
2161 if (!ArchitectureName.empty())
2162 outs() << " (architecture " << ArchitectureName << ")";
2163 outs() << "\n";
2164 if (ArchiveHeaders)
2165 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2166 ArchiveMemberOffsets, ArchitectureName);
2167 Error Err = Error::success();
2168 for (auto &C : A->children(Err)) {
2169 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2170 if (!ChildOrErr) {
2171 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2172 report_error(Filename, C, std::move(E), ArchitectureName);
2173 continue;
2174 }
2175 if (MachOObjectFile *O =
2176 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2177 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2178 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2179 ArchitectureName);
2180 }
2181 }
2182 if (Err)
2183 report_error(Filename, std::move(Err));
2184 } else {
2185 consumeError(AOrErr.takeError());
2186 error("Mach-O universal file: " + Filename + " for architecture " +
2187 StringRef(I->getArchFlagName()) +
2188 " is not a Mach-O file or an archive file");
2189 }
2190 }
2191}
2192
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002193// The block of info used by the Symbolizer call backs.
2194struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002195 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2196 std::vector<SectionRef> *Sections, bool verbose)
2197 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002198 bool verbose;
2199 MachOObjectFile *O;
2200 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002201 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002202 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002203 const char *class_name = nullptr;
2204 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002205 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002206 char *demangled_name = nullptr;
2207 uint64_t adrp_addr = 0;
2208 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002209 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002210 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002211};
2212
2213// SymbolizerGetOpInfo() is the operand information call back function.
2214// This is called to get the symbolic information for operand(s) of an
2215// instruction when it is being done. This routine does this from
2216// the relocation information, symbol table, etc. That block of information
2217// is a pointer to the struct DisassembleInfo that was passed when the
2218// disassembler context was created and passed to back to here when
2219// called back by the disassembler for instruction operands that could have
2220// relocation information. The address of the instruction containing operand is
2221// at the Pc parameter. The immediate value the operand has is passed in
2222// op_info->Value and is at Offset past the start of the instruction and has a
2223// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2224// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2225// names and addends of the symbolic expression to add for the operand. The
2226// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2227// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002228static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2229 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002230 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2231 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002232 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002233
2234 // Make sure all fields returned are zero if we don't set them.
2235 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2236 op_info->Value = value;
2237
2238 // If the TagType is not the value 1 which it code knows about or if no
2239 // verbose symbolic information is wanted then just return 0, indicating no
2240 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002241 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002242 return 0;
2243
2244 unsigned int Arch = info->O->getArch();
2245 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002246 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2247 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002248 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2249 // TODO:
2250 // Search the external relocation entries of a fully linked image
2251 // (if any) for an entry that matches this segment offset.
2252 // uint32_t seg_offset = (Pc + Offset);
2253 return 0;
2254 }
2255 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2256 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002257 uint32_t sect_addr = info->S.getAddress();
2258 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2259 bool reloc_found = false;
2260 DataRefImpl Rel;
2261 MachO::any_relocation_info RE;
2262 bool isExtern = false;
2263 SymbolRef Symbol;
2264 bool r_scattered = false;
2265 uint32_t r_value, pair_r_value, r_type;
2266 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002267 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002268 if (RelocOffset == sect_offset) {
2269 Rel = Reloc.getRawDataRefImpl();
2270 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002271 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002272 r_scattered = info->O->isRelocationScattered(RE);
2273 if (r_scattered) {
2274 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002275 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2276 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2277 DataRefImpl RelNext = Rel;
2278 info->O->moveRelocationNext(RelNext);
2279 MachO::any_relocation_info RENext;
2280 RENext = info->O->getRelocation(RelNext);
2281 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002282 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002283 else
2284 return 0;
2285 }
2286 } else {
2287 isExtern = info->O->getPlainRelocationExternal(RE);
2288 if (isExtern) {
2289 symbol_iterator RelocSym = Reloc.getSymbol();
2290 Symbol = *RelocSym;
2291 }
2292 }
2293 reloc_found = true;
2294 break;
2295 }
2296 }
2297 if (reloc_found && isExtern) {
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 Enderby9907d0a2014-11-04 00:43:16 +00002302 op_info->AddSymbol.Present = 1;
2303 op_info->AddSymbol.Name = name;
2304 // For i386 extern relocation entries the value in the instruction is
2305 // the offset from the symbol, and value is already set in op_info->Value.
2306 return 1;
2307 }
2308 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2309 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002310 const char *add = GuessSymbolName(r_value, info->AddrMap);
2311 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002312 uint32_t offset = value - (r_value - pair_r_value);
2313 op_info->AddSymbol.Present = 1;
2314 if (add != nullptr)
2315 op_info->AddSymbol.Name = add;
2316 else
2317 op_info->AddSymbol.Value = r_value;
2318 op_info->SubtractSymbol.Present = 1;
2319 if (sub != nullptr)
2320 op_info->SubtractSymbol.Name = sub;
2321 else
2322 op_info->SubtractSymbol.Value = pair_r_value;
2323 op_info->Value = offset;
2324 return 1;
2325 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002326 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002327 }
2328 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002329 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2330 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002331 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2332 // relocation entries of a linked image (if any) for an entry that matches
2333 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002334 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002335 uint64_t seg_offset = Pc + Offset;
2336 bool reloc_found = false;
2337 DataRefImpl Rel;
2338 MachO::any_relocation_info RE;
2339 bool isExtern = false;
2340 SymbolRef Symbol;
2341 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2342 uint64_t RelocOffset = Reloc.getOffset();
2343 if (RelocOffset == seg_offset) {
2344 Rel = Reloc.getRawDataRefImpl();
2345 RE = info->O->getRelocation(Rel);
2346 // external relocation entries should always be external.
2347 isExtern = info->O->getPlainRelocationExternal(RE);
2348 if (isExtern) {
2349 symbol_iterator RelocSym = Reloc.getSymbol();
2350 Symbol = *RelocSym;
2351 }
2352 reloc_found = true;
2353 break;
2354 }
2355 }
2356 if (reloc_found && isExtern) {
2357 // The Value passed in will be adjusted by the Pc if the instruction
2358 // adds the Pc. But for x86_64 external relocation entries the Value
2359 // is the offset from the external symbol.
2360 if (info->O->getAnyRelocationPCRel(RE))
2361 op_info->Value -= Pc + Offset + Size;
2362 Expected<StringRef> SymName = Symbol.getName();
2363 if (!SymName)
2364 report_error(info->O->getFileName(), SymName.takeError());
2365 const char *name = SymName->data();
2366 op_info->AddSymbol.Present = 1;
2367 op_info->AddSymbol.Name = name;
2368 return 1;
2369 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002370 return 0;
2371 }
2372 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2373 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002374 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002375 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2376 bool reloc_found = false;
2377 DataRefImpl Rel;
2378 MachO::any_relocation_info RE;
2379 bool isExtern = false;
2380 SymbolRef Symbol;
2381 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002382 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002383 if (RelocOffset == sect_offset) {
2384 Rel = Reloc.getRawDataRefImpl();
2385 RE = info->O->getRelocation(Rel);
2386 // NOTE: Scattered relocations don't exist on x86_64.
2387 isExtern = info->O->getPlainRelocationExternal(RE);
2388 if (isExtern) {
2389 symbol_iterator RelocSym = Reloc.getSymbol();
2390 Symbol = *RelocSym;
2391 }
2392 reloc_found = true;
2393 break;
2394 }
2395 }
2396 if (reloc_found && isExtern) {
2397 // The Value passed in will be adjusted by the Pc if the instruction
2398 // adds the Pc. But for x86_64 external relocation entries the Value
2399 // is the offset from the external symbol.
2400 if (info->O->getAnyRelocationPCRel(RE))
2401 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002402 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002403 if (!SymName)
2404 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002405 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002406 unsigned Type = info->O->getAnyRelocationType(RE);
2407 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2408 DataRefImpl RelNext = Rel;
2409 info->O->moveRelocationNext(RelNext);
2410 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2411 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2412 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2413 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2414 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2415 op_info->SubtractSymbol.Present = 1;
2416 op_info->SubtractSymbol.Name = name;
2417 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2418 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002419 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002420 if (!SymNameNext)
2421 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002422 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002423 }
2424 }
2425 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2426 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2427 op_info->AddSymbol.Present = 1;
2428 op_info->AddSymbol.Name = name;
2429 return 1;
2430 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002431 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002432 }
2433 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002434 if (Offset != 0 || (Size != 4 && Size != 2))
2435 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002436 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2437 // TODO:
2438 // Search the external relocation entries of a fully linked image
2439 // (if any) for an entry that matches this segment offset.
2440 // uint32_t seg_offset = (Pc + Offset);
2441 return 0;
2442 }
2443 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2444 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002445 uint32_t sect_addr = info->S.getAddress();
2446 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002447 DataRefImpl Rel;
2448 MachO::any_relocation_info RE;
2449 bool isExtern = false;
2450 SymbolRef Symbol;
2451 bool r_scattered = false;
2452 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002453 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002454 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2455 uint64_t RelocOffset = Reloc.getOffset();
2456 return RelocOffset == sect_offset;
2457 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002458
2459 if (Reloc == info->S.relocations().end())
2460 return 0;
2461
2462 Rel = Reloc->getRawDataRefImpl();
2463 RE = info->O->getRelocation(Rel);
2464 r_length = info->O->getAnyRelocationLength(RE);
2465 r_scattered = info->O->isRelocationScattered(RE);
2466 if (r_scattered) {
2467 r_value = info->O->getScatteredRelocationValue(RE);
2468 r_type = info->O->getScatteredRelocationType(RE);
2469 } else {
2470 r_type = info->O->getAnyRelocationType(RE);
2471 isExtern = info->O->getPlainRelocationExternal(RE);
2472 if (isExtern) {
2473 symbol_iterator RelocSym = Reloc->getSymbol();
2474 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002475 }
2476 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002477 if (r_type == MachO::ARM_RELOC_HALF ||
2478 r_type == MachO::ARM_RELOC_SECTDIFF ||
2479 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2480 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2481 DataRefImpl RelNext = Rel;
2482 info->O->moveRelocationNext(RelNext);
2483 MachO::any_relocation_info RENext;
2484 RENext = info->O->getRelocation(RelNext);
2485 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2486 if (info->O->isRelocationScattered(RENext))
2487 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2488 }
2489
2490 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002491 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002492 if (!SymName)
2493 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002494 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002495 op_info->AddSymbol.Present = 1;
2496 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002497 switch (r_type) {
2498 case MachO::ARM_RELOC_HALF:
2499 if ((r_length & 0x1) == 1) {
2500 op_info->Value = value << 16 | other_half;
2501 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2502 } else {
2503 op_info->Value = other_half << 16 | value;
2504 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002505 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002506 break;
2507 default:
2508 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002509 }
2510 return 1;
2511 }
2512 // If we have a branch that is not an external relocation entry then
2513 // return 0 so the code in tryAddingSymbolicOperand() can use the
2514 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002515 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002516 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2517 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002518 return 0;
2519
2520 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002521 if (r_type == MachO::ARM_RELOC_HALF ||
2522 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2523 if ((r_length & 0x1) == 1)
2524 value = value << 16 | other_half;
2525 else
2526 value = other_half << 16 | value;
2527 }
2528 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2529 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2530 offset = value - r_value;
2531 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002532 }
2533
David Blaikie33dd45d02015-03-23 18:39:02 +00002534 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002535 if ((r_length & 0x1) == 1)
2536 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2537 else
2538 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002539 const char *add = GuessSymbolName(r_value, info->AddrMap);
2540 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002541 int32_t offset = value - (r_value - pair_r_value);
2542 op_info->AddSymbol.Present = 1;
2543 if (add != nullptr)
2544 op_info->AddSymbol.Name = add;
2545 else
2546 op_info->AddSymbol.Value = r_value;
2547 op_info->SubtractSymbol.Present = 1;
2548 if (sub != nullptr)
2549 op_info->SubtractSymbol.Name = sub;
2550 else
2551 op_info->SubtractSymbol.Value = pair_r_value;
2552 op_info->Value = offset;
2553 return 1;
2554 }
2555
Kevin Enderby930fdc72014-11-06 19:00:13 +00002556 op_info->AddSymbol.Present = 1;
2557 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002558 if (r_type == MachO::ARM_RELOC_HALF) {
2559 if ((r_length & 0x1) == 1)
2560 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2561 else
2562 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002563 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002564 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002565 if (add != nullptr) {
2566 op_info->AddSymbol.Name = add;
2567 return 1;
2568 }
2569 op_info->AddSymbol.Value = value;
2570 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002571 }
2572 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002573 if (Offset != 0 || Size != 4)
2574 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002575 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2576 // TODO:
2577 // Search the external relocation entries of a fully linked image
2578 // (if any) for an entry that matches this segment offset.
2579 // uint64_t seg_offset = (Pc + Offset);
2580 return 0;
2581 }
2582 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2583 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002584 uint64_t sect_addr = info->S.getAddress();
2585 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002586 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002587 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2588 uint64_t RelocOffset = Reloc.getOffset();
2589 return RelocOffset == sect_offset;
2590 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002591
David Blaikie33dd45d02015-03-23 18:39:02 +00002592 if (Reloc == info->S.relocations().end())
2593 return 0;
2594
2595 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2596 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2597 uint32_t r_type = info->O->getAnyRelocationType(RE);
2598 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2599 DataRefImpl RelNext = Rel;
2600 info->O->moveRelocationNext(RelNext);
2601 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2602 if (value == 0) {
2603 value = info->O->getPlainRelocationSymbolNum(RENext);
2604 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002605 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002606 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002607 // NOTE: Scattered relocations don't exist on arm64.
2608 if (!info->O->getPlainRelocationExternal(RE))
2609 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002610 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002611 if (!SymName)
2612 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002613 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002614 op_info->AddSymbol.Present = 1;
2615 op_info->AddSymbol.Name = name;
2616
2617 switch (r_type) {
2618 case MachO::ARM64_RELOC_PAGE21:
2619 /* @page */
2620 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2621 break;
2622 case MachO::ARM64_RELOC_PAGEOFF12:
2623 /* @pageoff */
2624 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2625 break;
2626 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2627 /* @gotpage */
2628 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2629 break;
2630 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2631 /* @gotpageoff */
2632 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2633 break;
2634 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2635 /* @tvlppage is not implemented in llvm-mc */
2636 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2637 break;
2638 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2639 /* @tvlppageoff is not implemented in llvm-mc */
2640 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2641 break;
2642 default:
2643 case MachO::ARM64_RELOC_BRANCH26:
2644 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2645 break;
2646 }
2647 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002648 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002649 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002650}
2651
Kevin Enderbybf246f52014-09-24 23:08:22 +00002652// GuessCstringPointer is passed the address of what might be a pointer to a
2653// literal string in a cstring section. If that address is in a cstring section
2654// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002655static const char *GuessCstringPointer(uint64_t ReferenceValue,
2656 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002657 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002658 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2659 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2660 for (unsigned J = 0; J < Seg.nsects; ++J) {
2661 MachO::section_64 Sec = info->O->getSection64(Load, J);
2662 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2663 if (section_type == MachO::S_CSTRING_LITERALS &&
2664 ReferenceValue >= Sec.addr &&
2665 ReferenceValue < Sec.addr + Sec.size) {
2666 uint64_t sect_offset = ReferenceValue - Sec.addr;
2667 uint64_t object_offset = Sec.offset + sect_offset;
2668 StringRef MachOContents = info->O->getData();
2669 uint64_t object_size = MachOContents.size();
2670 const char *object_addr = (const char *)MachOContents.data();
2671 if (object_offset < object_size) {
2672 const char *name = object_addr + object_offset;
2673 return name;
2674 } else {
2675 return nullptr;
2676 }
2677 }
2678 }
2679 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2680 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2681 for (unsigned J = 0; J < Seg.nsects; ++J) {
2682 MachO::section Sec = info->O->getSection(Load, J);
2683 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2684 if (section_type == MachO::S_CSTRING_LITERALS &&
2685 ReferenceValue >= Sec.addr &&
2686 ReferenceValue < Sec.addr + Sec.size) {
2687 uint64_t sect_offset = ReferenceValue - Sec.addr;
2688 uint64_t object_offset = Sec.offset + sect_offset;
2689 StringRef MachOContents = info->O->getData();
2690 uint64_t object_size = MachOContents.size();
2691 const char *object_addr = (const char *)MachOContents.data();
2692 if (object_offset < object_size) {
2693 const char *name = object_addr + object_offset;
2694 return name;
2695 } else {
2696 return nullptr;
2697 }
2698 }
2699 }
2700 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002701 }
2702 return nullptr;
2703}
2704
Kevin Enderby85974882014-09-26 22:20:44 +00002705// GuessIndirectSymbol returns the name of the indirect symbol for the
2706// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2707// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2708// symbol name being referenced by the stub or pointer.
2709static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2710 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002711 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2712 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002713 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002714 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2715 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2716 for (unsigned J = 0; J < Seg.nsects; ++J) {
2717 MachO::section_64 Sec = info->O->getSection64(Load, J);
2718 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2719 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2720 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2721 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2722 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2723 section_type == MachO::S_SYMBOL_STUBS) &&
2724 ReferenceValue >= Sec.addr &&
2725 ReferenceValue < Sec.addr + Sec.size) {
2726 uint32_t stride;
2727 if (section_type == MachO::S_SYMBOL_STUBS)
2728 stride = Sec.reserved2;
2729 else
2730 stride = 8;
2731 if (stride == 0)
2732 return nullptr;
2733 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2734 if (index < Dysymtab.nindirectsyms) {
2735 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002736 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002737 if (indirect_symbol < Symtab.nsyms) {
2738 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2739 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002740 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002741 if (!SymName)
2742 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002743 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002744 return name;
2745 }
2746 }
2747 }
2748 }
2749 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2750 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2751 for (unsigned J = 0; J < Seg.nsects; ++J) {
2752 MachO::section Sec = info->O->getSection(Load, J);
2753 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2754 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2755 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2756 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2757 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2758 section_type == MachO::S_SYMBOL_STUBS) &&
2759 ReferenceValue >= Sec.addr &&
2760 ReferenceValue < Sec.addr + Sec.size) {
2761 uint32_t stride;
2762 if (section_type == MachO::S_SYMBOL_STUBS)
2763 stride = Sec.reserved2;
2764 else
2765 stride = 4;
2766 if (stride == 0)
2767 return nullptr;
2768 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2769 if (index < Dysymtab.nindirectsyms) {
2770 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002771 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002772 if (indirect_symbol < Symtab.nsyms) {
2773 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2774 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002775 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002776 if (!SymName)
2777 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002778 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002779 return name;
2780 }
2781 }
2782 }
2783 }
2784 }
Kevin Enderby85974882014-09-26 22:20:44 +00002785 }
2786 return nullptr;
2787}
2788
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002789// method_reference() is called passing it the ReferenceName that might be
2790// a reference it to an Objective-C method call. If so then it allocates and
2791// assembles a method call string with the values last seen and saved in
2792// the DisassembleInfo's class_name and selector_name fields. This is saved
2793// into the method field of the info and any previous string is free'ed.
2794// Then the class_name field in the info is set to nullptr. The method call
2795// string is set into ReferenceName and ReferenceType is set to
2796// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2797// then both ReferenceType and ReferenceName are left unchanged.
2798static void method_reference(struct DisassembleInfo *info,
2799 uint64_t *ReferenceType,
2800 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002801 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002802 if (*ReferenceName != nullptr) {
2803 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002804 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002805 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002806 info->method = llvm::make_unique<char[]>(
2807 5 + strlen(info->class_name) + strlen(info->selector_name));
2808 char *method = info->method.get();
2809 if (method != nullptr) {
2810 strcpy(method, "+[");
2811 strcat(method, info->class_name);
2812 strcat(method, " ");
2813 strcat(method, info->selector_name);
2814 strcat(method, "]");
2815 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002816 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2817 }
2818 } else {
David Blaikie0e550682018-02-20 18:48:51 +00002819 info->method =
2820 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
2821 char *method = info->method.get();
2822 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002823 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002824 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002825 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002826 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002827 else
David Blaikie0e550682018-02-20 18:48:51 +00002828 strcpy(method, "-[r? ");
2829 strcat(method, info->selector_name);
2830 strcat(method, "]");
2831 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002832 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2833 }
2834 }
2835 info->class_name = nullptr;
2836 }
2837 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002838 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002839 info->method =
2840 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
2841 char *method = info->method.get();
2842 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002843 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002844 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002845 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002846 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002847 else
David Blaikie0e550682018-02-20 18:48:51 +00002848 strcpy(method, "-[[r? super] ");
2849 strcat(method, info->selector_name);
2850 strcat(method, "]");
2851 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002852 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2853 }
2854 info->class_name = nullptr;
2855 }
2856 }
2857 }
2858}
2859
2860// GuessPointerPointer() is passed the address of what might be a pointer to
2861// a reference to an Objective-C class, selector, message ref or cfstring.
2862// If so the value of the pointer is returned and one of the booleans are set
2863// to true. If not zero is returned and all the booleans are set to false.
2864static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2865 struct DisassembleInfo *info,
2866 bool &classref, bool &selref, bool &msgref,
2867 bool &cfstring) {
2868 classref = false;
2869 selref = false;
2870 msgref = false;
2871 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002872 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002873 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2874 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2875 for (unsigned J = 0; J < Seg.nsects; ++J) {
2876 MachO::section_64 Sec = info->O->getSection64(Load, J);
2877 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2878 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2879 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2880 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2881 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2882 ReferenceValue >= Sec.addr &&
2883 ReferenceValue < Sec.addr + Sec.size) {
2884 uint64_t sect_offset = ReferenceValue - Sec.addr;
2885 uint64_t object_offset = Sec.offset + sect_offset;
2886 StringRef MachOContents = info->O->getData();
2887 uint64_t object_size = MachOContents.size();
2888 const char *object_addr = (const char *)MachOContents.data();
2889 if (object_offset < object_size) {
2890 uint64_t pointer_value;
2891 memcpy(&pointer_value, object_addr + object_offset,
2892 sizeof(uint64_t));
2893 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2894 sys::swapByteOrder(pointer_value);
2895 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2896 selref = true;
2897 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2898 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2899 classref = true;
2900 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2901 ReferenceValue + 8 < Sec.addr + Sec.size) {
2902 msgref = true;
2903 memcpy(&pointer_value, object_addr + object_offset + 8,
2904 sizeof(uint64_t));
2905 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2906 sys::swapByteOrder(pointer_value);
2907 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2908 cfstring = true;
2909 return pointer_value;
2910 } else {
2911 return 0;
2912 }
2913 }
2914 }
2915 }
2916 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002917 }
2918 return 0;
2919}
2920
2921// get_pointer_64 returns a pointer to the bytes in the object file at the
2922// Address from a section in the Mach-O file. And indirectly returns the
2923// offset into the section, number of bytes left in the section past the offset
2924// and which section is was being referenced. If the Address is not in a
2925// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002926static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2927 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002928 DisassembleInfo *info,
2929 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002930 offset = 0;
2931 left = 0;
2932 S = SectionRef();
2933 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2934 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2935 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002936 if (SectSize == 0)
2937 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002938 if (objc_only) {
2939 StringRef SectName;
2940 ((*(info->Sections))[SectIdx]).getName(SectName);
2941 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2942 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2943 if (SegName != "__OBJC" && SectName != "__cstring")
2944 continue;
2945 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002946 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2947 S = (*(info->Sections))[SectIdx];
2948 offset = Address - SectAddress;
2949 left = SectSize - offset;
2950 StringRef SectContents;
2951 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2952 return SectContents.data() + offset;
2953 }
2954 }
2955 return nullptr;
2956}
2957
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002958static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2959 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002960 DisassembleInfo *info,
2961 bool objc_only = false) {
2962 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002963}
2964
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002965// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2966// the symbol indirectly through n_value. Based on the relocation information
2967// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002968// If no relocation information is found and a non-zero ReferenceValue for the
2969// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002970static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2971 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002972 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002973 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002974 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002975 return nullptr;
2976
2977 // See if there is an external relocation entry at the sect_offset.
2978 bool reloc_found = false;
2979 DataRefImpl Rel;
2980 MachO::any_relocation_info RE;
2981 bool isExtern = false;
2982 SymbolRef Symbol;
2983 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002984 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002985 if (RelocOffset == sect_offset) {
2986 Rel = Reloc.getRawDataRefImpl();
2987 RE = info->O->getRelocation(Rel);
2988 if (info->O->isRelocationScattered(RE))
2989 continue;
2990 isExtern = info->O->getPlainRelocationExternal(RE);
2991 if (isExtern) {
2992 symbol_iterator RelocSym = Reloc.getSymbol();
2993 Symbol = *RelocSym;
2994 }
2995 reloc_found = true;
2996 break;
2997 }
2998 }
2999 // If there is an external relocation entry for a symbol in this section
3000 // at this section_offset then use that symbol's value for the n_value
3001 // and return its name.
3002 const char *SymbolName = nullptr;
3003 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003004 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003005 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003006 if (!NameOrError)
3007 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003008 StringRef Name = *NameOrError;
3009 if (!Name.empty()) {
3010 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003011 return SymbolName;
3012 }
3013 }
3014
3015 // TODO: For fully linked images, look through the external relocation
3016 // entries off the dynamic symtab command. For these the r_offset is from the
3017 // start of the first writeable segment in the Mach-O file. So the offset
3018 // to this section from that segment is passed to this routine by the caller,
3019 // as the database_offset. Which is the difference of the section's starting
3020 // address and the first writable segment.
3021 //
3022 // NOTE: need add passing the database_offset to this routine.
3023
Kevin Enderby0fc11822015-04-01 20:57:01 +00003024 // We did not find an external relocation entry so look up the ReferenceValue
3025 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003026 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003027
3028 return SymbolName;
3029}
3030
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003031static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3032 DisassembleInfo *info,
3033 uint32_t ReferenceValue) {
3034 uint64_t n_value64;
3035 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3036}
3037
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003038// These are structs in the Objective-C meta data and read to produce the
3039// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003040// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3041// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003042
3043// The cfstring object in a 64-bit Mach-O file.
3044struct cfstring64_t {
3045 uint64_t isa; // class64_t * (64-bit pointer)
3046 uint64_t flags; // flag bits
3047 uint64_t characters; // char * (64-bit pointer)
3048 uint64_t length; // number of non-NULL characters in above
3049};
3050
3051// The class object in a 64-bit Mach-O file.
3052struct class64_t {
3053 uint64_t isa; // class64_t * (64-bit pointer)
3054 uint64_t superclass; // class64_t * (64-bit pointer)
3055 uint64_t cache; // Cache (64-bit pointer)
3056 uint64_t vtable; // IMP * (64-bit pointer)
3057 uint64_t data; // class_ro64_t * (64-bit pointer)
3058};
3059
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003060struct class32_t {
3061 uint32_t isa; /* class32_t * (32-bit pointer) */
3062 uint32_t superclass; /* class32_t * (32-bit pointer) */
3063 uint32_t cache; /* Cache (32-bit pointer) */
3064 uint32_t vtable; /* IMP * (32-bit pointer) */
3065 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3066};
3067
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003068struct class_ro64_t {
3069 uint32_t flags;
3070 uint32_t instanceStart;
3071 uint32_t instanceSize;
3072 uint32_t reserved;
3073 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3074 uint64_t name; // const char * (64-bit pointer)
3075 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3076 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3077 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3078 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3079 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3080};
3081
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003082struct class_ro32_t {
3083 uint32_t flags;
3084 uint32_t instanceStart;
3085 uint32_t instanceSize;
3086 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3087 uint32_t name; /* const char * (32-bit pointer) */
3088 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3089 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3090 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3091 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3092 uint32_t baseProperties; /* const struct objc_property_list *
3093 (32-bit pointer) */
3094};
3095
3096/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003097#define RO_META (1 << 0)
3098#define RO_ROOT (1 << 1)
3099#define RO_HAS_CXX_STRUCTORS (1 << 2)
3100
3101struct method_list64_t {
3102 uint32_t entsize;
3103 uint32_t count;
3104 /* struct method64_t first; These structures follow inline */
3105};
3106
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003107struct method_list32_t {
3108 uint32_t entsize;
3109 uint32_t count;
3110 /* struct method32_t first; These structures follow inline */
3111};
3112
Kevin Enderby0fc11822015-04-01 20:57:01 +00003113struct method64_t {
3114 uint64_t name; /* SEL (64-bit pointer) */
3115 uint64_t types; /* const char * (64-bit pointer) */
3116 uint64_t imp; /* IMP (64-bit pointer) */
3117};
3118
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003119struct method32_t {
3120 uint32_t name; /* SEL (32-bit pointer) */
3121 uint32_t types; /* const char * (32-bit pointer) */
3122 uint32_t imp; /* IMP (32-bit pointer) */
3123};
3124
Kevin Enderby0fc11822015-04-01 20:57:01 +00003125struct protocol_list64_t {
3126 uint64_t count; /* uintptr_t (a 64-bit value) */
3127 /* struct protocol64_t * list[0]; These pointers follow inline */
3128};
3129
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003130struct protocol_list32_t {
3131 uint32_t count; /* uintptr_t (a 32-bit value) */
3132 /* struct protocol32_t * list[0]; These pointers follow inline */
3133};
3134
Kevin Enderby0fc11822015-04-01 20:57:01 +00003135struct protocol64_t {
3136 uint64_t isa; /* id * (64-bit pointer) */
3137 uint64_t name; /* const char * (64-bit pointer) */
3138 uint64_t protocols; /* struct protocol_list64_t *
3139 (64-bit pointer) */
3140 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3141 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3142 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3143 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3144 uint64_t instanceProperties; /* struct objc_property_list *
3145 (64-bit pointer) */
3146};
3147
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003148struct protocol32_t {
3149 uint32_t isa; /* id * (32-bit pointer) */
3150 uint32_t name; /* const char * (32-bit pointer) */
3151 uint32_t protocols; /* struct protocol_list_t *
3152 (32-bit pointer) */
3153 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3154 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3155 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3156 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3157 uint32_t instanceProperties; /* struct objc_property_list *
3158 (32-bit pointer) */
3159};
3160
Kevin Enderby0fc11822015-04-01 20:57:01 +00003161struct ivar_list64_t {
3162 uint32_t entsize;
3163 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003164 /* struct ivar64_t first; These structures follow inline */
3165};
3166
3167struct ivar_list32_t {
3168 uint32_t entsize;
3169 uint32_t count;
3170 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003171};
3172
3173struct ivar64_t {
3174 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3175 uint64_t name; /* const char * (64-bit pointer) */
3176 uint64_t type; /* const char * (64-bit pointer) */
3177 uint32_t alignment;
3178 uint32_t size;
3179};
3180
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003181struct ivar32_t {
3182 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3183 uint32_t name; /* const char * (32-bit pointer) */
3184 uint32_t type; /* const char * (32-bit pointer) */
3185 uint32_t alignment;
3186 uint32_t size;
3187};
3188
Kevin Enderby0fc11822015-04-01 20:57:01 +00003189struct objc_property_list64 {
3190 uint32_t entsize;
3191 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003192 /* struct objc_property64 first; These structures follow inline */
3193};
3194
3195struct objc_property_list32 {
3196 uint32_t entsize;
3197 uint32_t count;
3198 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003199};
3200
3201struct objc_property64 {
3202 uint64_t name; /* const char * (64-bit pointer) */
3203 uint64_t attributes; /* const char * (64-bit pointer) */
3204};
3205
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003206struct objc_property32 {
3207 uint32_t name; /* const char * (32-bit pointer) */
3208 uint32_t attributes; /* const char * (32-bit pointer) */
3209};
3210
Kevin Enderby0fc11822015-04-01 20:57:01 +00003211struct category64_t {
3212 uint64_t name; /* const char * (64-bit pointer) */
3213 uint64_t cls; /* struct class_t * (64-bit pointer) */
3214 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3215 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3216 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3217 uint64_t instanceProperties; /* struct objc_property_list *
3218 (64-bit pointer) */
3219};
3220
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003221struct category32_t {
3222 uint32_t name; /* const char * (32-bit pointer) */
3223 uint32_t cls; /* struct class_t * (32-bit pointer) */
3224 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3225 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3226 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3227 uint32_t instanceProperties; /* struct objc_property_list *
3228 (32-bit pointer) */
3229};
3230
Kevin Enderby0fc11822015-04-01 20:57:01 +00003231struct objc_image_info64 {
3232 uint32_t version;
3233 uint32_t flags;
3234};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003235struct objc_image_info32 {
3236 uint32_t version;
3237 uint32_t flags;
3238};
Kevin Enderby846c0002015-04-16 17:19:59 +00003239struct imageInfo_t {
3240 uint32_t version;
3241 uint32_t flags;
3242};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003243/* masks for objc_image_info.flags */
3244#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3245#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003246#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3247#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003248
3249struct message_ref64 {
3250 uint64_t imp; /* IMP (64-bit pointer) */
3251 uint64_t sel; /* SEL (64-bit pointer) */
3252};
3253
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003254struct message_ref32 {
3255 uint32_t imp; /* IMP (32-bit pointer) */
3256 uint32_t sel; /* SEL (32-bit pointer) */
3257};
3258
Kevin Enderby846c0002015-04-16 17:19:59 +00003259// Objective-C 1 (32-bit only) meta data structs.
3260
3261struct objc_module_t {
3262 uint32_t version;
3263 uint32_t size;
3264 uint32_t name; /* char * (32-bit pointer) */
3265 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3266};
3267
3268struct objc_symtab_t {
3269 uint32_t sel_ref_cnt;
3270 uint32_t refs; /* SEL * (32-bit pointer) */
3271 uint16_t cls_def_cnt;
3272 uint16_t cat_def_cnt;
3273 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3274};
3275
3276struct objc_class_t {
3277 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3278 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3279 uint32_t name; /* const char * (32-bit pointer) */
3280 int32_t version;
3281 int32_t info;
3282 int32_t instance_size;
3283 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3284 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3285 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3286 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3287};
3288
3289#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3290// class is not a metaclass
3291#define CLS_CLASS 0x1
3292// class is a metaclass
3293#define CLS_META 0x2
3294
3295struct objc_category_t {
3296 uint32_t category_name; /* char * (32-bit pointer) */
3297 uint32_t class_name; /* char * (32-bit pointer) */
3298 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3299 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3300 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3301};
3302
3303struct objc_ivar_t {
3304 uint32_t ivar_name; /* char * (32-bit pointer) */
3305 uint32_t ivar_type; /* char * (32-bit pointer) */
3306 int32_t ivar_offset;
3307};
3308
3309struct objc_ivar_list_t {
3310 int32_t ivar_count;
3311 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3312};
3313
3314struct objc_method_list_t {
3315 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3316 int32_t method_count;
3317 // struct objc_method_t method_list[1]; /* variable length structure */
3318};
3319
3320struct objc_method_t {
3321 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3322 uint32_t method_types; /* char * (32-bit pointer) */
3323 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3324 (32-bit pointer) */
3325};
3326
3327struct objc_protocol_list_t {
3328 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3329 int32_t count;
3330 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3331 // (32-bit pointer) */
3332};
3333
3334struct objc_protocol_t {
3335 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3336 uint32_t protocol_name; /* char * (32-bit pointer) */
3337 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3338 uint32_t instance_methods; /* struct objc_method_description_list *
3339 (32-bit pointer) */
3340 uint32_t class_methods; /* struct objc_method_description_list *
3341 (32-bit pointer) */
3342};
3343
3344struct objc_method_description_list_t {
3345 int32_t count;
3346 // struct objc_method_description_t list[1];
3347};
3348
3349struct objc_method_description_t {
3350 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3351 uint32_t types; /* char * (32-bit pointer) */
3352};
3353
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003354inline void swapStruct(struct cfstring64_t &cfs) {
3355 sys::swapByteOrder(cfs.isa);
3356 sys::swapByteOrder(cfs.flags);
3357 sys::swapByteOrder(cfs.characters);
3358 sys::swapByteOrder(cfs.length);
3359}
3360
3361inline void swapStruct(struct class64_t &c) {
3362 sys::swapByteOrder(c.isa);
3363 sys::swapByteOrder(c.superclass);
3364 sys::swapByteOrder(c.cache);
3365 sys::swapByteOrder(c.vtable);
3366 sys::swapByteOrder(c.data);
3367}
3368
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003369inline void swapStruct(struct class32_t &c) {
3370 sys::swapByteOrder(c.isa);
3371 sys::swapByteOrder(c.superclass);
3372 sys::swapByteOrder(c.cache);
3373 sys::swapByteOrder(c.vtable);
3374 sys::swapByteOrder(c.data);
3375}
3376
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003377inline void swapStruct(struct class_ro64_t &cro) {
3378 sys::swapByteOrder(cro.flags);
3379 sys::swapByteOrder(cro.instanceStart);
3380 sys::swapByteOrder(cro.instanceSize);
3381 sys::swapByteOrder(cro.reserved);
3382 sys::swapByteOrder(cro.ivarLayout);
3383 sys::swapByteOrder(cro.name);
3384 sys::swapByteOrder(cro.baseMethods);
3385 sys::swapByteOrder(cro.baseProtocols);
3386 sys::swapByteOrder(cro.ivars);
3387 sys::swapByteOrder(cro.weakIvarLayout);
3388 sys::swapByteOrder(cro.baseProperties);
3389}
3390
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003391inline void swapStruct(struct class_ro32_t &cro) {
3392 sys::swapByteOrder(cro.flags);
3393 sys::swapByteOrder(cro.instanceStart);
3394 sys::swapByteOrder(cro.instanceSize);
3395 sys::swapByteOrder(cro.ivarLayout);
3396 sys::swapByteOrder(cro.name);
3397 sys::swapByteOrder(cro.baseMethods);
3398 sys::swapByteOrder(cro.baseProtocols);
3399 sys::swapByteOrder(cro.ivars);
3400 sys::swapByteOrder(cro.weakIvarLayout);
3401 sys::swapByteOrder(cro.baseProperties);
3402}
3403
Kevin Enderby0fc11822015-04-01 20:57:01 +00003404inline void swapStruct(struct method_list64_t &ml) {
3405 sys::swapByteOrder(ml.entsize);
3406 sys::swapByteOrder(ml.count);
3407}
3408
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003409inline void swapStruct(struct method_list32_t &ml) {
3410 sys::swapByteOrder(ml.entsize);
3411 sys::swapByteOrder(ml.count);
3412}
3413
Kevin Enderby0fc11822015-04-01 20:57:01 +00003414inline void swapStruct(struct method64_t &m) {
3415 sys::swapByteOrder(m.name);
3416 sys::swapByteOrder(m.types);
3417 sys::swapByteOrder(m.imp);
3418}
3419
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003420inline void swapStruct(struct method32_t &m) {
3421 sys::swapByteOrder(m.name);
3422 sys::swapByteOrder(m.types);
3423 sys::swapByteOrder(m.imp);
3424}
3425
Kevin Enderby0fc11822015-04-01 20:57:01 +00003426inline void swapStruct(struct protocol_list64_t &pl) {
3427 sys::swapByteOrder(pl.count);
3428}
3429
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003430inline void swapStruct(struct protocol_list32_t &pl) {
3431 sys::swapByteOrder(pl.count);
3432}
3433
Kevin Enderby0fc11822015-04-01 20:57:01 +00003434inline void swapStruct(struct protocol64_t &p) {
3435 sys::swapByteOrder(p.isa);
3436 sys::swapByteOrder(p.name);
3437 sys::swapByteOrder(p.protocols);
3438 sys::swapByteOrder(p.instanceMethods);
3439 sys::swapByteOrder(p.classMethods);
3440 sys::swapByteOrder(p.optionalInstanceMethods);
3441 sys::swapByteOrder(p.optionalClassMethods);
3442 sys::swapByteOrder(p.instanceProperties);
3443}
3444
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003445inline void swapStruct(struct protocol32_t &p) {
3446 sys::swapByteOrder(p.isa);
3447 sys::swapByteOrder(p.name);
3448 sys::swapByteOrder(p.protocols);
3449 sys::swapByteOrder(p.instanceMethods);
3450 sys::swapByteOrder(p.classMethods);
3451 sys::swapByteOrder(p.optionalInstanceMethods);
3452 sys::swapByteOrder(p.optionalClassMethods);
3453 sys::swapByteOrder(p.instanceProperties);
3454}
3455
Kevin Enderby0fc11822015-04-01 20:57:01 +00003456inline void swapStruct(struct ivar_list64_t &il) {
3457 sys::swapByteOrder(il.entsize);
3458 sys::swapByteOrder(il.count);
3459}
3460
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003461inline void swapStruct(struct ivar_list32_t &il) {
3462 sys::swapByteOrder(il.entsize);
3463 sys::swapByteOrder(il.count);
3464}
3465
Kevin Enderby0fc11822015-04-01 20:57:01 +00003466inline void swapStruct(struct ivar64_t &i) {
3467 sys::swapByteOrder(i.offset);
3468 sys::swapByteOrder(i.name);
3469 sys::swapByteOrder(i.type);
3470 sys::swapByteOrder(i.alignment);
3471 sys::swapByteOrder(i.size);
3472}
3473
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003474inline void swapStruct(struct ivar32_t &i) {
3475 sys::swapByteOrder(i.offset);
3476 sys::swapByteOrder(i.name);
3477 sys::swapByteOrder(i.type);
3478 sys::swapByteOrder(i.alignment);
3479 sys::swapByteOrder(i.size);
3480}
3481
Kevin Enderby0fc11822015-04-01 20:57:01 +00003482inline void swapStruct(struct objc_property_list64 &pl) {
3483 sys::swapByteOrder(pl.entsize);
3484 sys::swapByteOrder(pl.count);
3485}
3486
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003487inline void swapStruct(struct objc_property_list32 &pl) {
3488 sys::swapByteOrder(pl.entsize);
3489 sys::swapByteOrder(pl.count);
3490}
3491
Kevin Enderby0fc11822015-04-01 20:57:01 +00003492inline void swapStruct(struct objc_property64 &op) {
3493 sys::swapByteOrder(op.name);
3494 sys::swapByteOrder(op.attributes);
3495}
3496
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003497inline void swapStruct(struct objc_property32 &op) {
3498 sys::swapByteOrder(op.name);
3499 sys::swapByteOrder(op.attributes);
3500}
3501
Kevin Enderby0fc11822015-04-01 20:57:01 +00003502inline void swapStruct(struct category64_t &c) {
3503 sys::swapByteOrder(c.name);
3504 sys::swapByteOrder(c.cls);
3505 sys::swapByteOrder(c.instanceMethods);
3506 sys::swapByteOrder(c.classMethods);
3507 sys::swapByteOrder(c.protocols);
3508 sys::swapByteOrder(c.instanceProperties);
3509}
3510
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003511inline void swapStruct(struct category32_t &c) {
3512 sys::swapByteOrder(c.name);
3513 sys::swapByteOrder(c.cls);
3514 sys::swapByteOrder(c.instanceMethods);
3515 sys::swapByteOrder(c.classMethods);
3516 sys::swapByteOrder(c.protocols);
3517 sys::swapByteOrder(c.instanceProperties);
3518}
3519
Kevin Enderby0fc11822015-04-01 20:57:01 +00003520inline void swapStruct(struct objc_image_info64 &o) {
3521 sys::swapByteOrder(o.version);
3522 sys::swapByteOrder(o.flags);
3523}
3524
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003525inline void swapStruct(struct objc_image_info32 &o) {
3526 sys::swapByteOrder(o.version);
3527 sys::swapByteOrder(o.flags);
3528}
3529
Kevin Enderby846c0002015-04-16 17:19:59 +00003530inline void swapStruct(struct imageInfo_t &o) {
3531 sys::swapByteOrder(o.version);
3532 sys::swapByteOrder(o.flags);
3533}
3534
Kevin Enderby0fc11822015-04-01 20:57:01 +00003535inline void swapStruct(struct message_ref64 &mr) {
3536 sys::swapByteOrder(mr.imp);
3537 sys::swapByteOrder(mr.sel);
3538}
3539
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003540inline void swapStruct(struct message_ref32 &mr) {
3541 sys::swapByteOrder(mr.imp);
3542 sys::swapByteOrder(mr.sel);
3543}
3544
Kevin Enderby846c0002015-04-16 17:19:59 +00003545inline void swapStruct(struct objc_module_t &module) {
3546 sys::swapByteOrder(module.version);
3547 sys::swapByteOrder(module.size);
3548 sys::swapByteOrder(module.name);
3549 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003550}
Kevin Enderby846c0002015-04-16 17:19:59 +00003551
3552inline void swapStruct(struct objc_symtab_t &symtab) {
3553 sys::swapByteOrder(symtab.sel_ref_cnt);
3554 sys::swapByteOrder(symtab.refs);
3555 sys::swapByteOrder(symtab.cls_def_cnt);
3556 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003557}
Kevin Enderby846c0002015-04-16 17:19:59 +00003558
3559inline void swapStruct(struct objc_class_t &objc_class) {
3560 sys::swapByteOrder(objc_class.isa);
3561 sys::swapByteOrder(objc_class.super_class);
3562 sys::swapByteOrder(objc_class.name);
3563 sys::swapByteOrder(objc_class.version);
3564 sys::swapByteOrder(objc_class.info);
3565 sys::swapByteOrder(objc_class.instance_size);
3566 sys::swapByteOrder(objc_class.ivars);
3567 sys::swapByteOrder(objc_class.methodLists);
3568 sys::swapByteOrder(objc_class.cache);
3569 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003570}
Kevin Enderby846c0002015-04-16 17:19:59 +00003571
3572inline void swapStruct(struct objc_category_t &objc_category) {
3573 sys::swapByteOrder(objc_category.category_name);
3574 sys::swapByteOrder(objc_category.class_name);
3575 sys::swapByteOrder(objc_category.instance_methods);
3576 sys::swapByteOrder(objc_category.class_methods);
3577 sys::swapByteOrder(objc_category.protocols);
3578}
3579
3580inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3581 sys::swapByteOrder(objc_ivar_list.ivar_count);
3582}
3583
3584inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3585 sys::swapByteOrder(objc_ivar.ivar_name);
3586 sys::swapByteOrder(objc_ivar.ivar_type);
3587 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003588}
Kevin Enderby846c0002015-04-16 17:19:59 +00003589
3590inline void swapStruct(struct objc_method_list_t &method_list) {
3591 sys::swapByteOrder(method_list.obsolete);
3592 sys::swapByteOrder(method_list.method_count);
3593}
3594
3595inline void swapStruct(struct objc_method_t &method) {
3596 sys::swapByteOrder(method.method_name);
3597 sys::swapByteOrder(method.method_types);
3598 sys::swapByteOrder(method.method_imp);
3599}
3600
3601inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3602 sys::swapByteOrder(protocol_list.next);
3603 sys::swapByteOrder(protocol_list.count);
3604}
3605
3606inline void swapStruct(struct objc_protocol_t &protocol) {
3607 sys::swapByteOrder(protocol.isa);
3608 sys::swapByteOrder(protocol.protocol_name);
3609 sys::swapByteOrder(protocol.protocol_list);
3610 sys::swapByteOrder(protocol.instance_methods);
3611 sys::swapByteOrder(protocol.class_methods);
3612}
3613
3614inline void swapStruct(struct objc_method_description_list_t &mdl) {
3615 sys::swapByteOrder(mdl.count);
3616}
3617
3618inline void swapStruct(struct objc_method_description_t &md) {
3619 sys::swapByteOrder(md.name);
3620 sys::swapByteOrder(md.types);
3621}
3622
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003623static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3624 struct DisassembleInfo *info);
3625
3626// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3627// to an Objective-C class and returns the class name. It is also passed the
3628// address of the pointer, so when the pointer is zero as it can be in an .o
3629// file, that is used to look for an external relocation entry with a symbol
3630// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003631static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3632 uint64_t ReferenceValue,
3633 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003634 const char *r;
3635 uint32_t offset, left;
3636 SectionRef S;
3637
3638 // The pointer_value can be 0 in an object file and have a relocation
3639 // entry for the class symbol at the ReferenceValue (the address of the
3640 // pointer).
3641 if (pointer_value == 0) {
3642 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3643 if (r == nullptr || left < sizeof(uint64_t))
3644 return nullptr;
3645 uint64_t n_value;
3646 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3647 if (symbol_name == nullptr)
3648 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003649 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003650 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3651 return class_name + 2;
3652 else
3653 return nullptr;
3654 }
3655
3656 // The case were the pointer_value is non-zero and points to a class defined
3657 // in this Mach-O file.
3658 r = get_pointer_64(pointer_value, offset, left, S, info);
3659 if (r == nullptr || left < sizeof(struct class64_t))
3660 return nullptr;
3661 struct class64_t c;
3662 memcpy(&c, r, sizeof(struct class64_t));
3663 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3664 swapStruct(c);
3665 if (c.data == 0)
3666 return nullptr;
3667 r = get_pointer_64(c.data, offset, left, S, info);
3668 if (r == nullptr || left < sizeof(struct class_ro64_t))
3669 return nullptr;
3670 struct class_ro64_t cro;
3671 memcpy(&cro, r, sizeof(struct class_ro64_t));
3672 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3673 swapStruct(cro);
3674 if (cro.name == 0)
3675 return nullptr;
3676 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3677 return name;
3678}
3679
3680// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3681// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003682static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3683 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003684 const char *r, *name;
3685 uint32_t offset, left;
3686 SectionRef S;
3687 struct cfstring64_t cfs;
3688 uint64_t cfs_characters;
3689
3690 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3691 if (r == nullptr || left < sizeof(struct cfstring64_t))
3692 return nullptr;
3693 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3694 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3695 swapStruct(cfs);
3696 if (cfs.characters == 0) {
3697 uint64_t n_value;
3698 const char *symbol_name = get_symbol_64(
3699 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3700 if (symbol_name == nullptr)
3701 return nullptr;
3702 cfs_characters = n_value;
3703 } else
3704 cfs_characters = cfs.characters;
3705 name = get_pointer_64(cfs_characters, offset, left, S, info);
3706
3707 return name;
3708}
3709
3710// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3711// of a pointer to an Objective-C selector reference when the pointer value is
3712// zero as in a .o file and is likely to have a external relocation entry with
3713// who's symbol's n_value is the real pointer to the selector name. If that is
3714// the case the real pointer to the selector name is returned else 0 is
3715// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003716static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3717 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003718 uint32_t offset, left;
3719 SectionRef S;
3720
3721 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3722 if (r == nullptr || left < sizeof(uint64_t))
3723 return 0;
3724 uint64_t n_value;
3725 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3726 if (symbol_name == nullptr)
3727 return 0;
3728 return n_value;
3729}
3730
Kevin Enderby0fc11822015-04-01 20:57:01 +00003731static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3732 const char *sectname) {
3733 for (const SectionRef &Section : O->sections()) {
3734 StringRef SectName;
3735 Section.getName(SectName);
3736 DataRefImpl Ref = Section.getRawDataRefImpl();
3737 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3738 if (SegName == segname && SectName == sectname)
3739 return Section;
3740 }
3741 return SectionRef();
3742}
3743
3744static void
3745walk_pointer_list_64(const char *listname, const SectionRef S,
3746 MachOObjectFile *O, struct DisassembleInfo *info,
3747 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3748 if (S == SectionRef())
3749 return;
3750
3751 StringRef SectName;
3752 S.getName(SectName);
3753 DataRefImpl Ref = S.getRawDataRefImpl();
3754 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3755 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3756
3757 StringRef BytesStr;
3758 S.getContents(BytesStr);
3759 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3760
3761 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3762 uint32_t left = S.getSize() - i;
3763 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3764 uint64_t p = 0;
3765 memcpy(&p, Contents + i, size);
3766 if (i + sizeof(uint64_t) > S.getSize())
3767 outs() << listname << " list pointer extends past end of (" << SegName
3768 << "," << SectName << ") section\n";
3769 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3770
3771 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3772 sys::swapByteOrder(p);
3773
3774 uint64_t n_value = 0;
3775 const char *name = get_symbol_64(i, S, info, n_value, p);
3776 if (name == nullptr)
3777 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3778
3779 if (n_value != 0) {
3780 outs() << format("0x%" PRIx64, n_value);
3781 if (p != 0)
3782 outs() << " + " << format("0x%" PRIx64, p);
3783 } else
3784 outs() << format("0x%" PRIx64, p);
3785 if (name != nullptr)
3786 outs() << " " << name;
3787 outs() << "\n";
3788
3789 p += n_value;
3790 if (func)
3791 func(p, info);
3792 }
3793}
3794
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003795static void
3796walk_pointer_list_32(const char *listname, const SectionRef S,
3797 MachOObjectFile *O, struct DisassembleInfo *info,
3798 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3799 if (S == SectionRef())
3800 return;
3801
3802 StringRef SectName;
3803 S.getName(SectName);
3804 DataRefImpl Ref = S.getRawDataRefImpl();
3805 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3806 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3807
3808 StringRef BytesStr;
3809 S.getContents(BytesStr);
3810 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3811
3812 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3813 uint32_t left = S.getSize() - i;
3814 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3815 uint32_t p = 0;
3816 memcpy(&p, Contents + i, size);
3817 if (i + sizeof(uint32_t) > S.getSize())
3818 outs() << listname << " list pointer extends past end of (" << SegName
3819 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003820 uint32_t Address = S.getAddress() + i;
3821 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003822
3823 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3824 sys::swapByteOrder(p);
3825 outs() << format("0x%" PRIx32, p);
3826
3827 const char *name = get_symbol_32(i, S, info, p);
3828 if (name != nullptr)
3829 outs() << " " << name;
3830 outs() << "\n";
3831
3832 if (func)
3833 func(p, info);
3834 }
3835}
3836
3837static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003838 if (layout_map == nullptr)
3839 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003840 outs() << " layout map: ";
3841 do {
3842 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3843 left--;
3844 layout_map++;
3845 } while (*layout_map != '\0' && left != 0);
3846 outs() << "\n";
3847}
3848
Kevin Enderby0fc11822015-04-01 20:57:01 +00003849static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3850 uint32_t offset, left;
3851 SectionRef S;
3852 const char *layout_map;
3853
3854 if (p == 0)
3855 return;
3856 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003857 print_layout_map(layout_map, left);
3858}
3859
3860static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3861 uint32_t offset, left;
3862 SectionRef S;
3863 const char *layout_map;
3864
3865 if (p == 0)
3866 return;
3867 layout_map = get_pointer_32(p, offset, left, S, info);
3868 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003869}
3870
3871static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3872 const char *indent) {
3873 struct method_list64_t ml;
3874 struct method64_t m;
3875 const char *r;
3876 uint32_t offset, xoffset, left, i;
3877 SectionRef S, xS;
3878 const char *name, *sym_name;
3879 uint64_t n_value;
3880
3881 r = get_pointer_64(p, offset, left, S, info);
3882 if (r == nullptr)
3883 return;
3884 memset(&ml, '\0', sizeof(struct method_list64_t));
3885 if (left < sizeof(struct method_list64_t)) {
3886 memcpy(&ml, r, left);
3887 outs() << " (method_list_t entends past the end of the section)\n";
3888 } else
3889 memcpy(&ml, r, sizeof(struct method_list64_t));
3890 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3891 swapStruct(ml);
3892 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3893 outs() << indent << "\t\t count " << ml.count << "\n";
3894
3895 p += sizeof(struct method_list64_t);
3896 offset += sizeof(struct method_list64_t);
3897 for (i = 0; i < ml.count; i++) {
3898 r = get_pointer_64(p, offset, left, S, info);
3899 if (r == nullptr)
3900 return;
3901 memset(&m, '\0', sizeof(struct method64_t));
3902 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003903 memcpy(&m, r, left);
3904 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003905 } else
3906 memcpy(&m, r, sizeof(struct method64_t));
3907 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3908 swapStruct(m);
3909
3910 outs() << indent << "\t\t name ";
3911 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3912 info, n_value, m.name);
3913 if (n_value != 0) {
3914 if (info->verbose && sym_name != nullptr)
3915 outs() << sym_name;
3916 else
3917 outs() << format("0x%" PRIx64, n_value);
3918 if (m.name != 0)
3919 outs() << " + " << format("0x%" PRIx64, m.name);
3920 } else
3921 outs() << format("0x%" PRIx64, m.name);
3922 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3923 if (name != nullptr)
3924 outs() << format(" %.*s", left, name);
3925 outs() << "\n";
3926
3927 outs() << indent << "\t\t types ";
3928 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3929 info, n_value, m.types);
3930 if (n_value != 0) {
3931 if (info->verbose && sym_name != nullptr)
3932 outs() << sym_name;
3933 else
3934 outs() << format("0x%" PRIx64, n_value);
3935 if (m.types != 0)
3936 outs() << " + " << format("0x%" PRIx64, m.types);
3937 } else
3938 outs() << format("0x%" PRIx64, m.types);
3939 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3940 if (name != nullptr)
3941 outs() << format(" %.*s", left, name);
3942 outs() << "\n";
3943
3944 outs() << indent << "\t\t imp ";
3945 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3946 n_value, m.imp);
3947 if (info->verbose && name == nullptr) {
3948 if (n_value != 0) {
3949 outs() << format("0x%" PRIx64, n_value) << " ";
3950 if (m.imp != 0)
3951 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3952 } else
3953 outs() << format("0x%" PRIx64, m.imp) << " ";
3954 }
3955 if (name != nullptr)
3956 outs() << name;
3957 outs() << "\n";
3958
3959 p += sizeof(struct method64_t);
3960 offset += sizeof(struct method64_t);
3961 }
3962}
3963
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003964static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3965 const char *indent) {
3966 struct method_list32_t ml;
3967 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003968 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003969 uint32_t offset, xoffset, left, i;
3970 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003971
3972 r = get_pointer_32(p, offset, left, S, info);
3973 if (r == nullptr)
3974 return;
3975 memset(&ml, '\0', sizeof(struct method_list32_t));
3976 if (left < sizeof(struct method_list32_t)) {
3977 memcpy(&ml, r, left);
3978 outs() << " (method_list_t entends past the end of the section)\n";
3979 } else
3980 memcpy(&ml, r, sizeof(struct method_list32_t));
3981 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3982 swapStruct(ml);
3983 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3984 outs() << indent << "\t\t count " << ml.count << "\n";
3985
3986 p += sizeof(struct method_list32_t);
3987 offset += sizeof(struct method_list32_t);
3988 for (i = 0; i < ml.count; i++) {
3989 r = get_pointer_32(p, offset, left, S, info);
3990 if (r == nullptr)
3991 return;
3992 memset(&m, '\0', sizeof(struct method32_t));
3993 if (left < sizeof(struct method32_t)) {
3994 memcpy(&ml, r, left);
3995 outs() << indent << " (method_t entends past the end of the section)\n";
3996 } else
3997 memcpy(&m, r, sizeof(struct method32_t));
3998 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3999 swapStruct(m);
4000
4001 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4002 name = get_pointer_32(m.name, xoffset, left, xS, info);
4003 if (name != nullptr)
4004 outs() << format(" %.*s", left, name);
4005 outs() << "\n";
4006
4007 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4008 name = get_pointer_32(m.types, xoffset, left, xS, info);
4009 if (name != nullptr)
4010 outs() << format(" %.*s", left, name);
4011 outs() << "\n";
4012
4013 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4014 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4015 m.imp);
4016 if (name != nullptr)
4017 outs() << " " << name;
4018 outs() << "\n";
4019
4020 p += sizeof(struct method32_t);
4021 offset += sizeof(struct method32_t);
4022 }
4023}
4024
Kevin Enderby846c0002015-04-16 17:19:59 +00004025static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4026 uint32_t offset, left, xleft;
4027 SectionRef S;
4028 struct objc_method_list_t method_list;
4029 struct objc_method_t method;
4030 const char *r, *methods, *name, *SymbolName;
4031 int32_t i;
4032
4033 r = get_pointer_32(p, offset, left, S, info, true);
4034 if (r == nullptr)
4035 return true;
4036
4037 outs() << "\n";
4038 if (left > sizeof(struct objc_method_list_t)) {
4039 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4040 } else {
4041 outs() << "\t\t objc_method_list extends past end of the section\n";
4042 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4043 memcpy(&method_list, r, left);
4044 }
4045 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4046 swapStruct(method_list);
4047
4048 outs() << "\t\t obsolete "
4049 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4050 outs() << "\t\t method_count " << method_list.method_count << "\n";
4051
4052 methods = r + sizeof(struct objc_method_list_t);
4053 for (i = 0; i < method_list.method_count; i++) {
4054 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4055 outs() << "\t\t remaining method's extend past the of the section\n";
4056 break;
4057 }
4058 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4059 sizeof(struct objc_method_t));
4060 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4061 swapStruct(method);
4062
4063 outs() << "\t\t method_name "
4064 << format("0x%08" PRIx32, method.method_name);
4065 if (info->verbose) {
4066 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4067 if (name != nullptr)
4068 outs() << format(" %.*s", xleft, name);
4069 else
4070 outs() << " (not in an __OBJC section)";
4071 }
4072 outs() << "\n";
4073
4074 outs() << "\t\t method_types "
4075 << format("0x%08" PRIx32, method.method_types);
4076 if (info->verbose) {
4077 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4078 if (name != nullptr)
4079 outs() << format(" %.*s", xleft, name);
4080 else
4081 outs() << " (not in an __OBJC section)";
4082 }
4083 outs() << "\n";
4084
4085 outs() << "\t\t method_imp "
4086 << format("0x%08" PRIx32, method.method_imp) << " ";
4087 if (info->verbose) {
4088 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4089 if (SymbolName != nullptr)
4090 outs() << SymbolName;
4091 }
4092 outs() << "\n";
4093 }
4094 return false;
4095}
4096
Kevin Enderby0fc11822015-04-01 20:57:01 +00004097static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4098 struct protocol_list64_t pl;
4099 uint64_t q, n_value;
4100 struct protocol64_t pc;
4101 const char *r;
4102 uint32_t offset, xoffset, left, i;
4103 SectionRef S, xS;
4104 const char *name, *sym_name;
4105
4106 r = get_pointer_64(p, offset, left, S, info);
4107 if (r == nullptr)
4108 return;
4109 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4110 if (left < sizeof(struct protocol_list64_t)) {
4111 memcpy(&pl, r, left);
4112 outs() << " (protocol_list_t entends past the end of the section)\n";
4113 } else
4114 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4115 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4116 swapStruct(pl);
4117 outs() << " count " << pl.count << "\n";
4118
4119 p += sizeof(struct protocol_list64_t);
4120 offset += sizeof(struct protocol_list64_t);
4121 for (i = 0; i < pl.count; i++) {
4122 r = get_pointer_64(p, offset, left, S, info);
4123 if (r == nullptr)
4124 return;
4125 q = 0;
4126 if (left < sizeof(uint64_t)) {
4127 memcpy(&q, r, left);
4128 outs() << " (protocol_t * entends past the end of the section)\n";
4129 } else
4130 memcpy(&q, r, sizeof(uint64_t));
4131 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4132 sys::swapByteOrder(q);
4133
4134 outs() << "\t\t list[" << i << "] ";
4135 sym_name = get_symbol_64(offset, S, info, n_value, q);
4136 if (n_value != 0) {
4137 if (info->verbose && sym_name != nullptr)
4138 outs() << sym_name;
4139 else
4140 outs() << format("0x%" PRIx64, n_value);
4141 if (q != 0)
4142 outs() << " + " << format("0x%" PRIx64, q);
4143 } else
4144 outs() << format("0x%" PRIx64, q);
4145 outs() << " (struct protocol_t *)\n";
4146
4147 r = get_pointer_64(q + n_value, offset, left, S, info);
4148 if (r == nullptr)
4149 return;
4150 memset(&pc, '\0', sizeof(struct protocol64_t));
4151 if (left < sizeof(struct protocol64_t)) {
4152 memcpy(&pc, r, left);
4153 outs() << " (protocol_t entends past the end of the section)\n";
4154 } else
4155 memcpy(&pc, r, sizeof(struct protocol64_t));
4156 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4157 swapStruct(pc);
4158
4159 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4160
4161 outs() << "\t\t\t name ";
4162 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4163 info, n_value, pc.name);
4164 if (n_value != 0) {
4165 if (info->verbose && sym_name != nullptr)
4166 outs() << sym_name;
4167 else
4168 outs() << format("0x%" PRIx64, n_value);
4169 if (pc.name != 0)
4170 outs() << " + " << format("0x%" PRIx64, pc.name);
4171 } else
4172 outs() << format("0x%" PRIx64, pc.name);
4173 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4174 if (name != nullptr)
4175 outs() << format(" %.*s", left, name);
4176 outs() << "\n";
4177
4178 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4179
4180 outs() << "\t\t instanceMethods ";
4181 sym_name =
4182 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4183 S, info, n_value, pc.instanceMethods);
4184 if (n_value != 0) {
4185 if (info->verbose && sym_name != nullptr)
4186 outs() << sym_name;
4187 else
4188 outs() << format("0x%" PRIx64, n_value);
4189 if (pc.instanceMethods != 0)
4190 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4191 } else
4192 outs() << format("0x%" PRIx64, pc.instanceMethods);
4193 outs() << " (struct method_list_t *)\n";
4194 if (pc.instanceMethods + n_value != 0)
4195 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4196
4197 outs() << "\t\t classMethods ";
4198 sym_name =
4199 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4200 info, n_value, pc.classMethods);
4201 if (n_value != 0) {
4202 if (info->verbose && sym_name != nullptr)
4203 outs() << sym_name;
4204 else
4205 outs() << format("0x%" PRIx64, n_value);
4206 if (pc.classMethods != 0)
4207 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4208 } else
4209 outs() << format("0x%" PRIx64, pc.classMethods);
4210 outs() << " (struct method_list_t *)\n";
4211 if (pc.classMethods + n_value != 0)
4212 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4213
4214 outs() << "\t optionalInstanceMethods "
4215 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4216 outs() << "\t optionalClassMethods "
4217 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4218 outs() << "\t instanceProperties "
4219 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4220
4221 p += sizeof(uint64_t);
4222 offset += sizeof(uint64_t);
4223 }
4224}
4225
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004226static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4227 struct protocol_list32_t pl;
4228 uint32_t q;
4229 struct protocol32_t pc;
4230 const char *r;
4231 uint32_t offset, xoffset, left, i;
4232 SectionRef S, xS;
4233 const char *name;
4234
4235 r = get_pointer_32(p, offset, left, S, info);
4236 if (r == nullptr)
4237 return;
4238 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4239 if (left < sizeof(struct protocol_list32_t)) {
4240 memcpy(&pl, r, left);
4241 outs() << " (protocol_list_t entends past the end of the section)\n";
4242 } else
4243 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4244 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4245 swapStruct(pl);
4246 outs() << " count " << pl.count << "\n";
4247
4248 p += sizeof(struct protocol_list32_t);
4249 offset += sizeof(struct protocol_list32_t);
4250 for (i = 0; i < pl.count; i++) {
4251 r = get_pointer_32(p, offset, left, S, info);
4252 if (r == nullptr)
4253 return;
4254 q = 0;
4255 if (left < sizeof(uint32_t)) {
4256 memcpy(&q, r, left);
4257 outs() << " (protocol_t * entends past the end of the section)\n";
4258 } else
4259 memcpy(&q, r, sizeof(uint32_t));
4260 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4261 sys::swapByteOrder(q);
4262 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4263 << " (struct protocol_t *)\n";
4264 r = get_pointer_32(q, offset, left, S, info);
4265 if (r == nullptr)
4266 return;
4267 memset(&pc, '\0', sizeof(struct protocol32_t));
4268 if (left < sizeof(struct protocol32_t)) {
4269 memcpy(&pc, r, left);
4270 outs() << " (protocol_t entends past the end of the section)\n";
4271 } else
4272 memcpy(&pc, r, sizeof(struct protocol32_t));
4273 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4274 swapStruct(pc);
4275 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4276 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4277 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4278 if (name != nullptr)
4279 outs() << format(" %.*s", left, name);
4280 outs() << "\n";
4281 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4282 outs() << "\t\t instanceMethods "
4283 << format("0x%" PRIx32, pc.instanceMethods)
4284 << " (struct method_list_t *)\n";
4285 if (pc.instanceMethods != 0)
4286 print_method_list32_t(pc.instanceMethods, info, "\t");
4287 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4288 << " (struct method_list_t *)\n";
4289 if (pc.classMethods != 0)
4290 print_method_list32_t(pc.classMethods, info, "\t");
4291 outs() << "\t optionalInstanceMethods "
4292 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4293 outs() << "\t optionalClassMethods "
4294 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4295 outs() << "\t instanceProperties "
4296 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4297 p += sizeof(uint32_t);
4298 offset += sizeof(uint32_t);
4299 }
4300}
4301
Kevin Enderby846c0002015-04-16 17:19:59 +00004302static void print_indent(uint32_t indent) {
4303 for (uint32_t i = 0; i < indent;) {
4304 if (indent - i >= 8) {
4305 outs() << "\t";
4306 i += 8;
4307 } else {
4308 for (uint32_t j = i; j < indent; j++)
4309 outs() << " ";
4310 return;
4311 }
4312 }
4313}
4314
4315static bool print_method_description_list(uint32_t p, uint32_t indent,
4316 struct DisassembleInfo *info) {
4317 uint32_t offset, left, xleft;
4318 SectionRef S;
4319 struct objc_method_description_list_t mdl;
4320 struct objc_method_description_t md;
4321 const char *r, *list, *name;
4322 int32_t i;
4323
4324 r = get_pointer_32(p, offset, left, S, info, true);
4325 if (r == nullptr)
4326 return true;
4327
4328 outs() << "\n";
4329 if (left > sizeof(struct objc_method_description_list_t)) {
4330 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4331 } else {
4332 print_indent(indent);
4333 outs() << " objc_method_description_list extends past end of the section\n";
4334 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4335 memcpy(&mdl, r, left);
4336 }
4337 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4338 swapStruct(mdl);
4339
4340 print_indent(indent);
4341 outs() << " count " << mdl.count << "\n";
4342
4343 list = r + sizeof(struct objc_method_description_list_t);
4344 for (i = 0; i < mdl.count; i++) {
4345 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4346 print_indent(indent);
4347 outs() << " remaining list entries extend past the of the section\n";
4348 break;
4349 }
4350 print_indent(indent);
4351 outs() << " list[" << i << "]\n";
4352 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4353 sizeof(struct objc_method_description_t));
4354 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4355 swapStruct(md);
4356
4357 print_indent(indent);
4358 outs() << " name " << format("0x%08" PRIx32, md.name);
4359 if (info->verbose) {
4360 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4361 if (name != nullptr)
4362 outs() << format(" %.*s", xleft, name);
4363 else
4364 outs() << " (not in an __OBJC section)";
4365 }
4366 outs() << "\n";
4367
4368 print_indent(indent);
4369 outs() << " types " << format("0x%08" PRIx32, md.types);
4370 if (info->verbose) {
4371 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4372 if (name != nullptr)
4373 outs() << format(" %.*s", xleft, name);
4374 else
4375 outs() << " (not in an __OBJC section)";
4376 }
4377 outs() << "\n";
4378 }
4379 return false;
4380}
4381
4382static bool print_protocol_list(uint32_t p, uint32_t indent,
4383 struct DisassembleInfo *info);
4384
4385static bool print_protocol(uint32_t p, uint32_t indent,
4386 struct DisassembleInfo *info) {
4387 uint32_t offset, left;
4388 SectionRef S;
4389 struct objc_protocol_t protocol;
4390 const char *r, *name;
4391
4392 r = get_pointer_32(p, offset, left, S, info, true);
4393 if (r == nullptr)
4394 return true;
4395
4396 outs() << "\n";
4397 if (left >= sizeof(struct objc_protocol_t)) {
4398 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4399 } else {
4400 print_indent(indent);
4401 outs() << " Protocol extends past end of the section\n";
4402 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4403 memcpy(&protocol, r, left);
4404 }
4405 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4406 swapStruct(protocol);
4407
4408 print_indent(indent);
4409 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4410 << "\n";
4411
4412 print_indent(indent);
4413 outs() << " protocol_name "
4414 << format("0x%08" PRIx32, protocol.protocol_name);
4415 if (info->verbose) {
4416 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4417 if (name != nullptr)
4418 outs() << format(" %.*s", left, name);
4419 else
4420 outs() << " (not in an __OBJC section)";
4421 }
4422 outs() << "\n";
4423
4424 print_indent(indent);
4425 outs() << " protocol_list "
4426 << format("0x%08" PRIx32, protocol.protocol_list);
4427 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4428 outs() << " (not in an __OBJC section)\n";
4429
4430 print_indent(indent);
4431 outs() << " instance_methods "
4432 << format("0x%08" PRIx32, protocol.instance_methods);
4433 if (print_method_description_list(protocol.instance_methods, indent, info))
4434 outs() << " (not in an __OBJC section)\n";
4435
4436 print_indent(indent);
4437 outs() << " class_methods "
4438 << format("0x%08" PRIx32, protocol.class_methods);
4439 if (print_method_description_list(protocol.class_methods, indent, info))
4440 outs() << " (not in an __OBJC section)\n";
4441
4442 return false;
4443}
4444
4445static bool print_protocol_list(uint32_t p, uint32_t indent,
4446 struct DisassembleInfo *info) {
4447 uint32_t offset, left, l;
4448 SectionRef S;
4449 struct objc_protocol_list_t protocol_list;
4450 const char *r, *list;
4451 int32_t i;
4452
4453 r = get_pointer_32(p, offset, left, S, info, true);
4454 if (r == nullptr)
4455 return true;
4456
4457 outs() << "\n";
4458 if (left > sizeof(struct objc_protocol_list_t)) {
4459 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4460 } else {
4461 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4462 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4463 memcpy(&protocol_list, r, left);
4464 }
4465 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4466 swapStruct(protocol_list);
4467
4468 print_indent(indent);
4469 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4470 << "\n";
4471 print_indent(indent);
4472 outs() << " count " << protocol_list.count << "\n";
4473
4474 list = r + sizeof(struct objc_protocol_list_t);
4475 for (i = 0; i < protocol_list.count; i++) {
4476 if ((i + 1) * sizeof(uint32_t) > left) {
4477 outs() << "\t\t remaining list entries extend past the of the section\n";
4478 break;
4479 }
4480 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4481 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4482 sys::swapByteOrder(l);
4483
4484 print_indent(indent);
4485 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4486 if (print_protocol(l, indent, info))
4487 outs() << "(not in an __OBJC section)\n";
4488 }
4489 return false;
4490}
4491
Kevin Enderby0fc11822015-04-01 20:57:01 +00004492static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4493 struct ivar_list64_t il;
4494 struct ivar64_t i;
4495 const char *r;
4496 uint32_t offset, xoffset, left, j;
4497 SectionRef S, xS;
4498 const char *name, *sym_name, *ivar_offset_p;
4499 uint64_t ivar_offset, n_value;
4500
4501 r = get_pointer_64(p, offset, left, S, info);
4502 if (r == nullptr)
4503 return;
4504 memset(&il, '\0', sizeof(struct ivar_list64_t));
4505 if (left < sizeof(struct ivar_list64_t)) {
4506 memcpy(&il, r, left);
4507 outs() << " (ivar_list_t entends past the end of the section)\n";
4508 } else
4509 memcpy(&il, r, sizeof(struct ivar_list64_t));
4510 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4511 swapStruct(il);
4512 outs() << " entsize " << il.entsize << "\n";
4513 outs() << " count " << il.count << "\n";
4514
4515 p += sizeof(struct ivar_list64_t);
4516 offset += sizeof(struct ivar_list64_t);
4517 for (j = 0; j < il.count; j++) {
4518 r = get_pointer_64(p, offset, left, S, info);
4519 if (r == nullptr)
4520 return;
4521 memset(&i, '\0', sizeof(struct ivar64_t));
4522 if (left < sizeof(struct ivar64_t)) {
4523 memcpy(&i, r, left);
4524 outs() << " (ivar_t entends past the end of the section)\n";
4525 } else
4526 memcpy(&i, r, sizeof(struct ivar64_t));
4527 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4528 swapStruct(i);
4529
4530 outs() << "\t\t\t offset ";
4531 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4532 info, n_value, i.offset);
4533 if (n_value != 0) {
4534 if (info->verbose && sym_name != nullptr)
4535 outs() << sym_name;
4536 else
4537 outs() << format("0x%" PRIx64, n_value);
4538 if (i.offset != 0)
4539 outs() << " + " << format("0x%" PRIx64, i.offset);
4540 } else
4541 outs() << format("0x%" PRIx64, i.offset);
4542 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4543 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4544 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4545 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4546 sys::swapByteOrder(ivar_offset);
4547 outs() << " " << ivar_offset << "\n";
4548 } else
4549 outs() << "\n";
4550
4551 outs() << "\t\t\t name ";
4552 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4553 n_value, i.name);
4554 if (n_value != 0) {
4555 if (info->verbose && sym_name != nullptr)
4556 outs() << sym_name;
4557 else
4558 outs() << format("0x%" PRIx64, n_value);
4559 if (i.name != 0)
4560 outs() << " + " << format("0x%" PRIx64, i.name);
4561 } else
4562 outs() << format("0x%" PRIx64, i.name);
4563 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4564 if (name != nullptr)
4565 outs() << format(" %.*s", left, name);
4566 outs() << "\n";
4567
4568 outs() << "\t\t\t type ";
4569 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4570 n_value, i.name);
4571 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4572 if (n_value != 0) {
4573 if (info->verbose && sym_name != nullptr)
4574 outs() << sym_name;
4575 else
4576 outs() << format("0x%" PRIx64, n_value);
4577 if (i.type != 0)
4578 outs() << " + " << format("0x%" PRIx64, i.type);
4579 } else
4580 outs() << format("0x%" PRIx64, i.type);
4581 if (name != nullptr)
4582 outs() << format(" %.*s", left, name);
4583 outs() << "\n";
4584
4585 outs() << "\t\t\talignment " << i.alignment << "\n";
4586 outs() << "\t\t\t size " << i.size << "\n";
4587
4588 p += sizeof(struct ivar64_t);
4589 offset += sizeof(struct ivar64_t);
4590 }
4591}
4592
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004593static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4594 struct ivar_list32_t il;
4595 struct ivar32_t i;
4596 const char *r;
4597 uint32_t offset, xoffset, left, j;
4598 SectionRef S, xS;
4599 const char *name, *ivar_offset_p;
4600 uint32_t ivar_offset;
4601
4602 r = get_pointer_32(p, offset, left, S, info);
4603 if (r == nullptr)
4604 return;
4605 memset(&il, '\0', sizeof(struct ivar_list32_t));
4606 if (left < sizeof(struct ivar_list32_t)) {
4607 memcpy(&il, r, left);
4608 outs() << " (ivar_list_t entends past the end of the section)\n";
4609 } else
4610 memcpy(&il, r, sizeof(struct ivar_list32_t));
4611 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4612 swapStruct(il);
4613 outs() << " entsize " << il.entsize << "\n";
4614 outs() << " count " << il.count << "\n";
4615
4616 p += sizeof(struct ivar_list32_t);
4617 offset += sizeof(struct ivar_list32_t);
4618 for (j = 0; j < il.count; j++) {
4619 r = get_pointer_32(p, offset, left, S, info);
4620 if (r == nullptr)
4621 return;
4622 memset(&i, '\0', sizeof(struct ivar32_t));
4623 if (left < sizeof(struct ivar32_t)) {
4624 memcpy(&i, r, left);
4625 outs() << " (ivar_t entends past the end of the section)\n";
4626 } else
4627 memcpy(&i, r, sizeof(struct ivar32_t));
4628 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4629 swapStruct(i);
4630
4631 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4632 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4633 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4634 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4635 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4636 sys::swapByteOrder(ivar_offset);
4637 outs() << " " << ivar_offset << "\n";
4638 } else
4639 outs() << "\n";
4640
4641 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4642 name = get_pointer_32(i.name, xoffset, left, xS, info);
4643 if (name != nullptr)
4644 outs() << format(" %.*s", left, name);
4645 outs() << "\n";
4646
4647 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4648 name = get_pointer_32(i.type, xoffset, left, xS, info);
4649 if (name != nullptr)
4650 outs() << format(" %.*s", left, name);
4651 outs() << "\n";
4652
4653 outs() << "\t\t\talignment " << i.alignment << "\n";
4654 outs() << "\t\t\t size " << i.size << "\n";
4655
4656 p += sizeof(struct ivar32_t);
4657 offset += sizeof(struct ivar32_t);
4658 }
4659}
4660
Kevin Enderby0fc11822015-04-01 20:57:01 +00004661static void print_objc_property_list64(uint64_t p,
4662 struct DisassembleInfo *info) {
4663 struct objc_property_list64 opl;
4664 struct objc_property64 op;
4665 const char *r;
4666 uint32_t offset, xoffset, left, j;
4667 SectionRef S, xS;
4668 const char *name, *sym_name;
4669 uint64_t n_value;
4670
4671 r = get_pointer_64(p, offset, left, S, info);
4672 if (r == nullptr)
4673 return;
4674 memset(&opl, '\0', sizeof(struct objc_property_list64));
4675 if (left < sizeof(struct objc_property_list64)) {
4676 memcpy(&opl, r, left);
4677 outs() << " (objc_property_list entends past the end of the section)\n";
4678 } else
4679 memcpy(&opl, r, sizeof(struct objc_property_list64));
4680 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4681 swapStruct(opl);
4682 outs() << " entsize " << opl.entsize << "\n";
4683 outs() << " count " << opl.count << "\n";
4684
4685 p += sizeof(struct objc_property_list64);
4686 offset += sizeof(struct objc_property_list64);
4687 for (j = 0; j < opl.count; j++) {
4688 r = get_pointer_64(p, offset, left, S, info);
4689 if (r == nullptr)
4690 return;
4691 memset(&op, '\0', sizeof(struct objc_property64));
4692 if (left < sizeof(struct objc_property64)) {
4693 memcpy(&op, r, left);
4694 outs() << " (objc_property entends past the end of the section)\n";
4695 } else
4696 memcpy(&op, r, sizeof(struct objc_property64));
4697 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4698 swapStruct(op);
4699
4700 outs() << "\t\t\t name ";
4701 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4702 info, n_value, op.name);
4703 if (n_value != 0) {
4704 if (info->verbose && sym_name != nullptr)
4705 outs() << sym_name;
4706 else
4707 outs() << format("0x%" PRIx64, n_value);
4708 if (op.name != 0)
4709 outs() << " + " << format("0x%" PRIx64, op.name);
4710 } else
4711 outs() << format("0x%" PRIx64, op.name);
4712 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4713 if (name != nullptr)
4714 outs() << format(" %.*s", left, name);
4715 outs() << "\n";
4716
4717 outs() << "\t\t\tattributes ";
4718 sym_name =
4719 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4720 info, n_value, op.attributes);
4721 if (n_value != 0) {
4722 if (info->verbose && sym_name != nullptr)
4723 outs() << sym_name;
4724 else
4725 outs() << format("0x%" PRIx64, n_value);
4726 if (op.attributes != 0)
4727 outs() << " + " << format("0x%" PRIx64, op.attributes);
4728 } else
4729 outs() << format("0x%" PRIx64, op.attributes);
4730 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4731 if (name != nullptr)
4732 outs() << format(" %.*s", left, name);
4733 outs() << "\n";
4734
4735 p += sizeof(struct objc_property64);
4736 offset += sizeof(struct objc_property64);
4737 }
4738}
4739
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004740static void print_objc_property_list32(uint32_t p,
4741 struct DisassembleInfo *info) {
4742 struct objc_property_list32 opl;
4743 struct objc_property32 op;
4744 const char *r;
4745 uint32_t offset, xoffset, left, j;
4746 SectionRef S, xS;
4747 const char *name;
4748
4749 r = get_pointer_32(p, offset, left, S, info);
4750 if (r == nullptr)
4751 return;
4752 memset(&opl, '\0', sizeof(struct objc_property_list32));
4753 if (left < sizeof(struct objc_property_list32)) {
4754 memcpy(&opl, r, left);
4755 outs() << " (objc_property_list entends past the end of the section)\n";
4756 } else
4757 memcpy(&opl, r, sizeof(struct objc_property_list32));
4758 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4759 swapStruct(opl);
4760 outs() << " entsize " << opl.entsize << "\n";
4761 outs() << " count " << opl.count << "\n";
4762
4763 p += sizeof(struct objc_property_list32);
4764 offset += sizeof(struct objc_property_list32);
4765 for (j = 0; j < opl.count; j++) {
4766 r = get_pointer_32(p, offset, left, S, info);
4767 if (r == nullptr)
4768 return;
4769 memset(&op, '\0', sizeof(struct objc_property32));
4770 if (left < sizeof(struct objc_property32)) {
4771 memcpy(&op, r, left);
4772 outs() << " (objc_property entends past the end of the section)\n";
4773 } else
4774 memcpy(&op, r, sizeof(struct objc_property32));
4775 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4776 swapStruct(op);
4777
4778 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4779 name = get_pointer_32(op.name, xoffset, left, xS, info);
4780 if (name != nullptr)
4781 outs() << format(" %.*s", left, name);
4782 outs() << "\n";
4783
4784 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4785 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4786 if (name != nullptr)
4787 outs() << format(" %.*s", left, name);
4788 outs() << "\n";
4789
4790 p += sizeof(struct objc_property32);
4791 offset += sizeof(struct objc_property32);
4792 }
4793}
4794
Richard Smith81ff44d2015-10-09 22:09:56 +00004795static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004796 bool &is_meta_class) {
4797 struct class_ro64_t cro;
4798 const char *r;
4799 uint32_t offset, xoffset, left;
4800 SectionRef S, xS;
4801 const char *name, *sym_name;
4802 uint64_t n_value;
4803
4804 r = get_pointer_64(p, offset, left, S, info);
4805 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004806 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004807 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004808 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4809 swapStruct(cro);
4810 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4811 if (cro.flags & RO_META)
4812 outs() << " RO_META";
4813 if (cro.flags & RO_ROOT)
4814 outs() << " RO_ROOT";
4815 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4816 outs() << " RO_HAS_CXX_STRUCTORS";
4817 outs() << "\n";
4818 outs() << " instanceStart " << cro.instanceStart << "\n";
4819 outs() << " instanceSize " << cro.instanceSize << "\n";
4820 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4821 << "\n";
4822 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4823 << "\n";
4824 print_layout_map64(cro.ivarLayout, info);
4825
4826 outs() << " name ";
4827 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4828 info, n_value, cro.name);
4829 if (n_value != 0) {
4830 if (info->verbose && sym_name != nullptr)
4831 outs() << sym_name;
4832 else
4833 outs() << format("0x%" PRIx64, n_value);
4834 if (cro.name != 0)
4835 outs() << " + " << format("0x%" PRIx64, cro.name);
4836 } else
4837 outs() << format("0x%" PRIx64, cro.name);
4838 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4839 if (name != nullptr)
4840 outs() << format(" %.*s", left, name);
4841 outs() << "\n";
4842
4843 outs() << " baseMethods ";
4844 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4845 S, info, n_value, cro.baseMethods);
4846 if (n_value != 0) {
4847 if (info->verbose && sym_name != nullptr)
4848 outs() << sym_name;
4849 else
4850 outs() << format("0x%" PRIx64, n_value);
4851 if (cro.baseMethods != 0)
4852 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4853 } else
4854 outs() << format("0x%" PRIx64, cro.baseMethods);
4855 outs() << " (struct method_list_t *)\n";
4856 if (cro.baseMethods + n_value != 0)
4857 print_method_list64_t(cro.baseMethods + n_value, info, "");
4858
4859 outs() << " baseProtocols ";
4860 sym_name =
4861 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4862 info, n_value, cro.baseProtocols);
4863 if (n_value != 0) {
4864 if (info->verbose && sym_name != nullptr)
4865 outs() << sym_name;
4866 else
4867 outs() << format("0x%" PRIx64, n_value);
4868 if (cro.baseProtocols != 0)
4869 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4870 } else
4871 outs() << format("0x%" PRIx64, cro.baseProtocols);
4872 outs() << "\n";
4873 if (cro.baseProtocols + n_value != 0)
4874 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4875
4876 outs() << " ivars ";
4877 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004878 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004879 if (n_value != 0) {
4880 if (info->verbose && sym_name != nullptr)
4881 outs() << sym_name;
4882 else
4883 outs() << format("0x%" PRIx64, n_value);
4884 if (cro.ivars != 0)
4885 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4886 } else
4887 outs() << format("0x%" PRIx64, cro.ivars);
4888 outs() << "\n";
4889 if (cro.ivars + n_value != 0)
4890 print_ivar_list64_t(cro.ivars + n_value, info);
4891
4892 outs() << " weakIvarLayout ";
4893 sym_name =
4894 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4895 info, n_value, cro.weakIvarLayout);
4896 if (n_value != 0) {
4897 if (info->verbose && sym_name != nullptr)
4898 outs() << sym_name;
4899 else
4900 outs() << format("0x%" PRIx64, n_value);
4901 if (cro.weakIvarLayout != 0)
4902 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4903 } else
4904 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4905 outs() << "\n";
4906 print_layout_map64(cro.weakIvarLayout + n_value, info);
4907
4908 outs() << " baseProperties ";
4909 sym_name =
4910 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4911 info, n_value, cro.baseProperties);
4912 if (n_value != 0) {
4913 if (info->verbose && sym_name != nullptr)
4914 outs() << sym_name;
4915 else
4916 outs() << format("0x%" PRIx64, n_value);
4917 if (cro.baseProperties != 0)
4918 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4919 } else
4920 outs() << format("0x%" PRIx64, cro.baseProperties);
4921 outs() << "\n";
4922 if (cro.baseProperties + n_value != 0)
4923 print_objc_property_list64(cro.baseProperties + n_value, info);
4924
Rafael Espindolab9091322015-10-24 23:19:10 +00004925 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004926 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004927}
4928
Richard Smith81ff44d2015-10-09 22:09:56 +00004929static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004930 bool &is_meta_class) {
4931 struct class_ro32_t cro;
4932 const char *r;
4933 uint32_t offset, xoffset, left;
4934 SectionRef S, xS;
4935 const char *name;
4936
4937 r = get_pointer_32(p, offset, left, S, info);
4938 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004939 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004940 memset(&cro, '\0', sizeof(struct class_ro32_t));
4941 if (left < sizeof(struct class_ro32_t)) {
4942 memcpy(&cro, r, left);
4943 outs() << " (class_ro_t entends past the end of the section)\n";
4944 } else
4945 memcpy(&cro, r, sizeof(struct class_ro32_t));
4946 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4947 swapStruct(cro);
4948 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4949 if (cro.flags & RO_META)
4950 outs() << " RO_META";
4951 if (cro.flags & RO_ROOT)
4952 outs() << " RO_ROOT";
4953 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4954 outs() << " RO_HAS_CXX_STRUCTORS";
4955 outs() << "\n";
4956 outs() << " instanceStart " << cro.instanceStart << "\n";
4957 outs() << " instanceSize " << cro.instanceSize << "\n";
4958 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4959 << "\n";
4960 print_layout_map32(cro.ivarLayout, info);
4961
4962 outs() << " name " << format("0x%" PRIx32, cro.name);
4963 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4964 if (name != nullptr)
4965 outs() << format(" %.*s", left, name);
4966 outs() << "\n";
4967
4968 outs() << " baseMethods "
4969 << format("0x%" PRIx32, cro.baseMethods)
4970 << " (struct method_list_t *)\n";
4971 if (cro.baseMethods != 0)
4972 print_method_list32_t(cro.baseMethods, info, "");
4973
4974 outs() << " baseProtocols "
4975 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4976 if (cro.baseProtocols != 0)
4977 print_protocol_list32_t(cro.baseProtocols, info);
4978 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4979 << "\n";
4980 if (cro.ivars != 0)
4981 print_ivar_list32_t(cro.ivars, info);
4982 outs() << " weakIvarLayout "
4983 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4984 print_layout_map32(cro.weakIvarLayout, info);
4985 outs() << " baseProperties "
4986 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4987 if (cro.baseProperties != 0)
4988 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004989 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004990 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004991}
4992
Kevin Enderby0fc11822015-04-01 20:57:01 +00004993static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4994 struct class64_t c;
4995 const char *r;
4996 uint32_t offset, left;
4997 SectionRef S;
4998 const char *name;
4999 uint64_t isa_n_value, n_value;
5000
5001 r = get_pointer_64(p, offset, left, S, info);
5002 if (r == nullptr || left < sizeof(struct class64_t))
5003 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005004 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005005 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5006 swapStruct(c);
5007
5008 outs() << " isa " << format("0x%" PRIx64, c.isa);
5009 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5010 isa_n_value, c.isa);
5011 if (name != nullptr)
5012 outs() << " " << name;
5013 outs() << "\n";
5014
5015 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5016 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5017 n_value, c.superclass);
5018 if (name != nullptr)
5019 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005020 else {
5021 name = get_dyld_bind_info_symbolname(S.getAddress() +
5022 offset + offsetof(struct class64_t, superclass), info);
5023 if (name != nullptr)
5024 outs() << " " << name;
5025 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005026 outs() << "\n";
5027
5028 outs() << " cache " << format("0x%" PRIx64, c.cache);
5029 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5030 n_value, c.cache);
5031 if (name != nullptr)
5032 outs() << " " << name;
5033 outs() << "\n";
5034
5035 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5036 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5037 n_value, c.vtable);
5038 if (name != nullptr)
5039 outs() << " " << name;
5040 outs() << "\n";
5041
5042 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5043 n_value, c.data);
5044 outs() << " data ";
5045 if (n_value != 0) {
5046 if (info->verbose && name != nullptr)
5047 outs() << name;
5048 else
5049 outs() << format("0x%" PRIx64, n_value);
5050 if (c.data != 0)
5051 outs() << " + " << format("0x%" PRIx64, c.data);
5052 } else
5053 outs() << format("0x%" PRIx64, c.data);
5054 outs() << " (struct class_ro_t *)";
5055
5056 // This is a Swift class if some of the low bits of the pointer are set.
5057 if ((c.data + n_value) & 0x7)
5058 outs() << " Swift class";
5059 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005060 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005061 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5062 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005063
Kevin Enderbyaac75382015-10-08 16:56:35 +00005064 if (!is_meta_class &&
5065 c.isa + isa_n_value != p &&
5066 c.isa + isa_n_value != 0 &&
5067 info->depth < 100) {
5068 info->depth++;
5069 outs() << "Meta Class\n";
5070 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005071 }
5072}
5073
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005074static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5075 struct class32_t c;
5076 const char *r;
5077 uint32_t offset, left;
5078 SectionRef S;
5079 const char *name;
5080
5081 r = get_pointer_32(p, offset, left, S, info);
5082 if (r == nullptr)
5083 return;
5084 memset(&c, '\0', sizeof(struct class32_t));
5085 if (left < sizeof(struct class32_t)) {
5086 memcpy(&c, r, left);
5087 outs() << " (class_t entends past the end of the section)\n";
5088 } else
5089 memcpy(&c, r, sizeof(struct class32_t));
5090 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5091 swapStruct(c);
5092
5093 outs() << " isa " << format("0x%" PRIx32, c.isa);
5094 name =
5095 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5096 if (name != nullptr)
5097 outs() << " " << name;
5098 outs() << "\n";
5099
5100 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5101 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5102 c.superclass);
5103 if (name != nullptr)
5104 outs() << " " << name;
5105 outs() << "\n";
5106
5107 outs() << " cache " << format("0x%" PRIx32, c.cache);
5108 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5109 c.cache);
5110 if (name != nullptr)
5111 outs() << " " << name;
5112 outs() << "\n";
5113
5114 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5115 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5116 c.vtable);
5117 if (name != nullptr)
5118 outs() << " " << name;
5119 outs() << "\n";
5120
5121 name =
5122 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5123 outs() << " data " << format("0x%" PRIx32, c.data)
5124 << " (struct class_ro_t *)";
5125
5126 // This is a Swift class if some of the low bits of the pointer are set.
5127 if (c.data & 0x3)
5128 outs() << " Swift class";
5129 outs() << "\n";
5130 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005131 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5132 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005133
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005134 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005135 outs() << "Meta Class\n";
5136 print_class32_t(c.isa, info);
5137 }
5138}
5139
Kevin Enderby846c0002015-04-16 17:19:59 +00005140static void print_objc_class_t(struct objc_class_t *objc_class,
5141 struct DisassembleInfo *info) {
5142 uint32_t offset, left, xleft;
5143 const char *name, *p, *ivar_list;
5144 SectionRef S;
5145 int32_t i;
5146 struct objc_ivar_list_t objc_ivar_list;
5147 struct objc_ivar_t ivar;
5148
5149 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5150 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5151 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5152 if (name != nullptr)
5153 outs() << format(" %.*s", left, name);
5154 else
5155 outs() << " (not in an __OBJC section)";
5156 }
5157 outs() << "\n";
5158
5159 outs() << "\t super_class "
5160 << format("0x%08" PRIx32, objc_class->super_class);
5161 if (info->verbose) {
5162 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5163 if (name != nullptr)
5164 outs() << format(" %.*s", left, name);
5165 else
5166 outs() << " (not in an __OBJC section)";
5167 }
5168 outs() << "\n";
5169
5170 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5171 if (info->verbose) {
5172 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5173 if (name != nullptr)
5174 outs() << format(" %.*s", left, name);
5175 else
5176 outs() << " (not in an __OBJC section)";
5177 }
5178 outs() << "\n";
5179
5180 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5181 << "\n";
5182
5183 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5184 if (info->verbose) {
5185 if (CLS_GETINFO(objc_class, CLS_CLASS))
5186 outs() << " CLS_CLASS";
5187 else if (CLS_GETINFO(objc_class, CLS_META))
5188 outs() << " CLS_META";
5189 }
5190 outs() << "\n";
5191
5192 outs() << "\t instance_size "
5193 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5194
5195 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5196 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5197 if (p != nullptr) {
5198 if (left > sizeof(struct objc_ivar_list_t)) {
5199 outs() << "\n";
5200 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5201 } else {
5202 outs() << " (entends past the end of the section)\n";
5203 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5204 memcpy(&objc_ivar_list, p, left);
5205 }
5206 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5207 swapStruct(objc_ivar_list);
5208 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5209 ivar_list = p + sizeof(struct objc_ivar_list_t);
5210 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5211 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5212 outs() << "\t\t remaining ivar's extend past the of the section\n";
5213 break;
5214 }
5215 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5216 sizeof(struct objc_ivar_t));
5217 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5218 swapStruct(ivar);
5219
5220 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5221 if (info->verbose) {
5222 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5223 if (name != nullptr)
5224 outs() << format(" %.*s", xleft, name);
5225 else
5226 outs() << " (not in an __OBJC section)";
5227 }
5228 outs() << "\n";
5229
5230 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5231 if (info->verbose) {
5232 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5233 if (name != nullptr)
5234 outs() << format(" %.*s", xleft, name);
5235 else
5236 outs() << " (not in an __OBJC section)";
5237 }
5238 outs() << "\n";
5239
5240 outs() << "\t\t ivar_offset "
5241 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5242 }
5243 } else {
5244 outs() << " (not in an __OBJC section)\n";
5245 }
5246
5247 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5248 if (print_method_list(objc_class->methodLists, info))
5249 outs() << " (not in an __OBJC section)\n";
5250
5251 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5252 << "\n";
5253
5254 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5255 if (print_protocol_list(objc_class->protocols, 16, info))
5256 outs() << " (not in an __OBJC section)\n";
5257}
5258
5259static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5260 struct DisassembleInfo *info) {
5261 uint32_t offset, left;
5262 const char *name;
5263 SectionRef S;
5264
5265 outs() << "\t category name "
5266 << format("0x%08" PRIx32, objc_category->category_name);
5267 if (info->verbose) {
5268 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5269 true);
5270 if (name != nullptr)
5271 outs() << format(" %.*s", left, name);
5272 else
5273 outs() << " (not in an __OBJC section)";
5274 }
5275 outs() << "\n";
5276
5277 outs() << "\t\t class name "
5278 << format("0x%08" PRIx32, objc_category->class_name);
5279 if (info->verbose) {
5280 name =
5281 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5282 if (name != nullptr)
5283 outs() << format(" %.*s", left, name);
5284 else
5285 outs() << " (not in an __OBJC section)";
5286 }
5287 outs() << "\n";
5288
5289 outs() << "\t instance methods "
5290 << format("0x%08" PRIx32, objc_category->instance_methods);
5291 if (print_method_list(objc_category->instance_methods, info))
5292 outs() << " (not in an __OBJC section)\n";
5293
5294 outs() << "\t class methods "
5295 << format("0x%08" PRIx32, objc_category->class_methods);
5296 if (print_method_list(objc_category->class_methods, info))
5297 outs() << " (not in an __OBJC section)\n";
5298}
5299
Kevin Enderby0fc11822015-04-01 20:57:01 +00005300static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5301 struct category64_t c;
5302 const char *r;
5303 uint32_t offset, xoffset, left;
5304 SectionRef S, xS;
5305 const char *name, *sym_name;
5306 uint64_t n_value;
5307
5308 r = get_pointer_64(p, offset, left, S, info);
5309 if (r == nullptr)
5310 return;
5311 memset(&c, '\0', sizeof(struct category64_t));
5312 if (left < sizeof(struct category64_t)) {
5313 memcpy(&c, r, left);
5314 outs() << " (category_t entends past the end of the section)\n";
5315 } else
5316 memcpy(&c, r, sizeof(struct category64_t));
5317 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5318 swapStruct(c);
5319
5320 outs() << " name ";
5321 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5322 info, n_value, c.name);
5323 if (n_value != 0) {
5324 if (info->verbose && sym_name != nullptr)
5325 outs() << sym_name;
5326 else
5327 outs() << format("0x%" PRIx64, n_value);
5328 if (c.name != 0)
5329 outs() << " + " << format("0x%" PRIx64, c.name);
5330 } else
5331 outs() << format("0x%" PRIx64, c.name);
5332 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5333 if (name != nullptr)
5334 outs() << format(" %.*s", left, name);
5335 outs() << "\n";
5336
5337 outs() << " cls ";
5338 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5339 n_value, c.cls);
5340 if (n_value != 0) {
5341 if (info->verbose && sym_name != nullptr)
5342 outs() << sym_name;
5343 else
5344 outs() << format("0x%" PRIx64, n_value);
5345 if (c.cls != 0)
5346 outs() << " + " << format("0x%" PRIx64, c.cls);
5347 } else
5348 outs() << format("0x%" PRIx64, c.cls);
5349 outs() << "\n";
5350 if (c.cls + n_value != 0)
5351 print_class64_t(c.cls + n_value, info);
5352
5353 outs() << " instanceMethods ";
5354 sym_name =
5355 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5356 info, n_value, c.instanceMethods);
5357 if (n_value != 0) {
5358 if (info->verbose && sym_name != nullptr)
5359 outs() << sym_name;
5360 else
5361 outs() << format("0x%" PRIx64, n_value);
5362 if (c.instanceMethods != 0)
5363 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5364 } else
5365 outs() << format("0x%" PRIx64, c.instanceMethods);
5366 outs() << "\n";
5367 if (c.instanceMethods + n_value != 0)
5368 print_method_list64_t(c.instanceMethods + n_value, info, "");
5369
5370 outs() << " classMethods ";
5371 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5372 S, info, n_value, c.classMethods);
5373 if (n_value != 0) {
5374 if (info->verbose && sym_name != nullptr)
5375 outs() << sym_name;
5376 else
5377 outs() << format("0x%" PRIx64, n_value);
5378 if (c.classMethods != 0)
5379 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5380 } else
5381 outs() << format("0x%" PRIx64, c.classMethods);
5382 outs() << "\n";
5383 if (c.classMethods + n_value != 0)
5384 print_method_list64_t(c.classMethods + n_value, info, "");
5385
5386 outs() << " protocols ";
5387 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5388 info, n_value, c.protocols);
5389 if (n_value != 0) {
5390 if (info->verbose && sym_name != nullptr)
5391 outs() << sym_name;
5392 else
5393 outs() << format("0x%" PRIx64, n_value);
5394 if (c.protocols != 0)
5395 outs() << " + " << format("0x%" PRIx64, c.protocols);
5396 } else
5397 outs() << format("0x%" PRIx64, c.protocols);
5398 outs() << "\n";
5399 if (c.protocols + n_value != 0)
5400 print_protocol_list64_t(c.protocols + n_value, info);
5401
5402 outs() << "instanceProperties ";
5403 sym_name =
5404 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5405 S, info, n_value, c.instanceProperties);
5406 if (n_value != 0) {
5407 if (info->verbose && sym_name != nullptr)
5408 outs() << sym_name;
5409 else
5410 outs() << format("0x%" PRIx64, n_value);
5411 if (c.instanceProperties != 0)
5412 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5413 } else
5414 outs() << format("0x%" PRIx64, c.instanceProperties);
5415 outs() << "\n";
5416 if (c.instanceProperties + n_value != 0)
5417 print_objc_property_list64(c.instanceProperties + n_value, info);
5418}
5419
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005420static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5421 struct category32_t c;
5422 const char *r;
5423 uint32_t offset, left;
5424 SectionRef S, xS;
5425 const char *name;
5426
5427 r = get_pointer_32(p, offset, left, S, info);
5428 if (r == nullptr)
5429 return;
5430 memset(&c, '\0', sizeof(struct category32_t));
5431 if (left < sizeof(struct category32_t)) {
5432 memcpy(&c, r, left);
5433 outs() << " (category_t entends past the end of the section)\n";
5434 } else
5435 memcpy(&c, r, sizeof(struct category32_t));
5436 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5437 swapStruct(c);
5438
5439 outs() << " name " << format("0x%" PRIx32, c.name);
5440 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5441 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005442 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005443 outs() << " " << name;
5444 outs() << "\n";
5445
5446 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5447 if (c.cls != 0)
5448 print_class32_t(c.cls, info);
5449 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5450 << "\n";
5451 if (c.instanceMethods != 0)
5452 print_method_list32_t(c.instanceMethods, info, "");
5453 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5454 << "\n";
5455 if (c.classMethods != 0)
5456 print_method_list32_t(c.classMethods, info, "");
5457 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5458 if (c.protocols != 0)
5459 print_protocol_list32_t(c.protocols, info);
5460 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5461 << "\n";
5462 if (c.instanceProperties != 0)
5463 print_objc_property_list32(c.instanceProperties, info);
5464}
5465
Kevin Enderby0fc11822015-04-01 20:57:01 +00005466static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5467 uint32_t i, left, offset, xoffset;
5468 uint64_t p, n_value;
5469 struct message_ref64 mr;
5470 const char *name, *sym_name;
5471 const char *r;
5472 SectionRef xS;
5473
5474 if (S == SectionRef())
5475 return;
5476
5477 StringRef SectName;
5478 S.getName(SectName);
5479 DataRefImpl Ref = S.getRawDataRefImpl();
5480 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5481 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5482 offset = 0;
5483 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5484 p = S.getAddress() + i;
5485 r = get_pointer_64(p, offset, left, S, info);
5486 if (r == nullptr)
5487 return;
5488 memset(&mr, '\0', sizeof(struct message_ref64));
5489 if (left < sizeof(struct message_ref64)) {
5490 memcpy(&mr, r, left);
5491 outs() << " (message_ref entends past the end of the section)\n";
5492 } else
5493 memcpy(&mr, r, sizeof(struct message_ref64));
5494 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5495 swapStruct(mr);
5496
5497 outs() << " imp ";
5498 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5499 n_value, mr.imp);
5500 if (n_value != 0) {
5501 outs() << format("0x%" PRIx64, n_value) << " ";
5502 if (mr.imp != 0)
5503 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5504 } else
5505 outs() << format("0x%" PRIx64, mr.imp) << " ";
5506 if (name != nullptr)
5507 outs() << " " << name;
5508 outs() << "\n";
5509
5510 outs() << " sel ";
5511 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5512 info, n_value, mr.sel);
5513 if (n_value != 0) {
5514 if (info->verbose && sym_name != nullptr)
5515 outs() << sym_name;
5516 else
5517 outs() << format("0x%" PRIx64, n_value);
5518 if (mr.sel != 0)
5519 outs() << " + " << format("0x%" PRIx64, mr.sel);
5520 } else
5521 outs() << format("0x%" PRIx64, mr.sel);
5522 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5523 if (name != nullptr)
5524 outs() << format(" %.*s", left, name);
5525 outs() << "\n";
5526
5527 offset += sizeof(struct message_ref64);
5528 }
5529}
5530
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005531static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5532 uint32_t i, left, offset, xoffset, p;
5533 struct message_ref32 mr;
5534 const char *name, *r;
5535 SectionRef xS;
5536
5537 if (S == SectionRef())
5538 return;
5539
5540 StringRef SectName;
5541 S.getName(SectName);
5542 DataRefImpl Ref = S.getRawDataRefImpl();
5543 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5544 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5545 offset = 0;
5546 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5547 p = S.getAddress() + i;
5548 r = get_pointer_32(p, offset, left, S, info);
5549 if (r == nullptr)
5550 return;
5551 memset(&mr, '\0', sizeof(struct message_ref32));
5552 if (left < sizeof(struct message_ref32)) {
5553 memcpy(&mr, r, left);
5554 outs() << " (message_ref entends past the end of the section)\n";
5555 } else
5556 memcpy(&mr, r, sizeof(struct message_ref32));
5557 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5558 swapStruct(mr);
5559
5560 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5561 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5562 mr.imp);
5563 if (name != nullptr)
5564 outs() << " " << name;
5565 outs() << "\n";
5566
5567 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5568 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5569 if (name != nullptr)
5570 outs() << " " << name;
5571 outs() << "\n";
5572
5573 offset += sizeof(struct message_ref32);
5574 }
5575}
5576
Kevin Enderby0fc11822015-04-01 20:57:01 +00005577static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5578 uint32_t left, offset, swift_version;
5579 uint64_t p;
5580 struct objc_image_info64 o;
5581 const char *r;
5582
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005583 if (S == SectionRef())
5584 return;
5585
Kevin Enderby0fc11822015-04-01 20:57:01 +00005586 StringRef SectName;
5587 S.getName(SectName);
5588 DataRefImpl Ref = S.getRawDataRefImpl();
5589 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5590 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5591 p = S.getAddress();
5592 r = get_pointer_64(p, offset, left, S, info);
5593 if (r == nullptr)
5594 return;
5595 memset(&o, '\0', sizeof(struct objc_image_info64));
5596 if (left < sizeof(struct objc_image_info64)) {
5597 memcpy(&o, r, left);
5598 outs() << " (objc_image_info entends past the end of the section)\n";
5599 } else
5600 memcpy(&o, r, sizeof(struct objc_image_info64));
5601 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5602 swapStruct(o);
5603 outs() << " version " << o.version << "\n";
5604 outs() << " flags " << format("0x%" PRIx32, o.flags);
5605 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5606 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5607 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5608 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005609 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5610 outs() << " OBJC_IMAGE_IS_SIMULATED";
5611 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5612 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005613 swift_version = (o.flags >> 8) & 0xff;
5614 if (swift_version != 0) {
5615 if (swift_version == 1)
5616 outs() << " Swift 1.0";
5617 else if (swift_version == 2)
5618 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005619 else if(swift_version == 3)
5620 outs() << " Swift 2.0";
5621 else if(swift_version == 4)
5622 outs() << " Swift 3.0";
5623 else if(swift_version == 5)
5624 outs() << " Swift 4.0";
5625 else if(swift_version == 6)
5626 outs() << " Swift 4.1";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005627 else
5628 outs() << " unknown future Swift version (" << swift_version << ")";
5629 }
5630 outs() << "\n";
5631}
5632
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005633static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5634 uint32_t left, offset, swift_version, p;
5635 struct objc_image_info32 o;
5636 const char *r;
5637
Kevin Enderby19be2512016-04-21 19:49:29 +00005638 if (S == SectionRef())
5639 return;
5640
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005641 StringRef SectName;
5642 S.getName(SectName);
5643 DataRefImpl Ref = S.getRawDataRefImpl();
5644 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5645 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5646 p = S.getAddress();
5647 r = get_pointer_32(p, offset, left, S, info);
5648 if (r == nullptr)
5649 return;
5650 memset(&o, '\0', sizeof(struct objc_image_info32));
5651 if (left < sizeof(struct objc_image_info32)) {
5652 memcpy(&o, r, left);
5653 outs() << " (objc_image_info entends past the end of the section)\n";
5654 } else
5655 memcpy(&o, r, sizeof(struct objc_image_info32));
5656 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5657 swapStruct(o);
5658 outs() << " version " << o.version << "\n";
5659 outs() << " flags " << format("0x%" PRIx32, o.flags);
5660 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5661 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5662 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5663 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5664 swift_version = (o.flags >> 8) & 0xff;
5665 if (swift_version != 0) {
5666 if (swift_version == 1)
5667 outs() << " Swift 1.0";
5668 else if (swift_version == 2)
5669 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005670 else if(swift_version == 3)
5671 outs() << " Swift 2.0";
5672 else if(swift_version == 4)
5673 outs() << " Swift 3.0";
5674 else if(swift_version == 5)
5675 outs() << " Swift 4.0";
5676 else if(swift_version == 6)
5677 outs() << " Swift 4.1";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005678 else
5679 outs() << " unknown future Swift version (" << swift_version << ")";
5680 }
5681 outs() << "\n";
5682}
5683
Kevin Enderby846c0002015-04-16 17:19:59 +00005684static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5685 uint32_t left, offset, p;
5686 struct imageInfo_t o;
5687 const char *r;
5688
5689 StringRef SectName;
5690 S.getName(SectName);
5691 DataRefImpl Ref = S.getRawDataRefImpl();
5692 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5693 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5694 p = S.getAddress();
5695 r = get_pointer_32(p, offset, left, S, info);
5696 if (r == nullptr)
5697 return;
5698 memset(&o, '\0', sizeof(struct imageInfo_t));
5699 if (left < sizeof(struct imageInfo_t)) {
5700 memcpy(&o, r, left);
5701 outs() << " (imageInfo entends past the end of the section)\n";
5702 } else
5703 memcpy(&o, r, sizeof(struct imageInfo_t));
5704 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5705 swapStruct(o);
5706 outs() << " version " << o.version << "\n";
5707 outs() << " flags " << format("0x%" PRIx32, o.flags);
5708 if (o.flags & 0x1)
5709 outs() << " F&C";
5710 if (o.flags & 0x2)
5711 outs() << " GC";
5712 if (o.flags & 0x4)
5713 outs() << " GC-only";
5714 else
5715 outs() << " RR";
5716 outs() << "\n";
5717}
5718
Kevin Enderby0fc11822015-04-01 20:57:01 +00005719static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5720 SymbolAddressMap AddrMap;
5721 if (verbose)
5722 CreateSymbolAddressMap(O, &AddrMap);
5723
5724 std::vector<SectionRef> Sections;
5725 for (const SectionRef &Section : O->sections()) {
5726 StringRef SectName;
5727 Section.getName(SectName);
5728 Sections.push_back(Section);
5729 }
5730
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005731 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005732
Davide Italiano62507042015-12-11 22:27:59 +00005733 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5734 if (CL == SectionRef())
5735 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005736 if (CL == SectionRef())
5737 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5738 if (CL == SectionRef())
5739 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005740 info.S = CL;
5741 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005742
Davide Italiano62507042015-12-11 22:27:59 +00005743 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5744 if (CR == SectionRef())
5745 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005746 if (CR == SectionRef())
5747 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5748 if (CR == SectionRef())
5749 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005750 info.S = CR;
5751 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005752
Davide Italiano62507042015-12-11 22:27:59 +00005753 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5754 if (SR == SectionRef())
5755 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005756 if (SR == SectionRef())
5757 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5758 if (SR == SectionRef())
5759 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005760 info.S = SR;
5761 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005762
Davide Italiano62507042015-12-11 22:27:59 +00005763 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5764 if (CA == SectionRef())
5765 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005766 if (CA == SectionRef())
5767 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5768 if (CA == SectionRef())
5769 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005770 info.S = CA;
5771 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005772
Davide Italiano62507042015-12-11 22:27:59 +00005773 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5774 if (PL == SectionRef())
5775 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005776 if (PL == SectionRef())
5777 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5778 if (PL == SectionRef())
5779 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005780 info.S = PL;
5781 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005782
Davide Italiano62507042015-12-11 22:27:59 +00005783 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5784 if (MR == SectionRef())
5785 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005786 if (MR == SectionRef())
5787 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5788 if (MR == SectionRef())
5789 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005790 info.S = MR;
5791 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005792
Davide Italiano62507042015-12-11 22:27:59 +00005793 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5794 if (II == SectionRef())
5795 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005796 if (II == SectionRef())
5797 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5798 if (II == SectionRef())
5799 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005800 info.S = II;
5801 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005802}
5803
5804static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005805 SymbolAddressMap AddrMap;
5806 if (verbose)
5807 CreateSymbolAddressMap(O, &AddrMap);
5808
5809 std::vector<SectionRef> Sections;
5810 for (const SectionRef &Section : O->sections()) {
5811 StringRef SectName;
5812 Section.getName(SectName);
5813 Sections.push_back(Section);
5814 }
5815
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005816 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005817
Kevin Enderby5879a482017-02-09 17:56:26 +00005818 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5819 if (CL == SectionRef())
5820 CL = get_section(O, "__DATA", "__objc_classlist");
5821 if (CL == SectionRef())
5822 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5823 if (CL == SectionRef())
5824 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5825 info.S = CL;
5826 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005827
Kevin Enderby5879a482017-02-09 17:56:26 +00005828 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5829 if (CR == SectionRef())
5830 CR = get_section(O, "__DATA", "__objc_classrefs");
5831 if (CR == SectionRef())
5832 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5833 if (CR == SectionRef())
5834 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5835 info.S = CR;
5836 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005837
Kevin Enderby5879a482017-02-09 17:56:26 +00005838 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5839 if (SR == SectionRef())
5840 SR = get_section(O, "__DATA", "__objc_superrefs");
5841 if (SR == SectionRef())
5842 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5843 if (SR == SectionRef())
5844 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5845 info.S = SR;
5846 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005847
Kevin Enderby5879a482017-02-09 17:56:26 +00005848 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5849 if (CA == SectionRef())
5850 CA = get_section(O, "__DATA", "__objc_catlist");
5851 if (CA == SectionRef())
5852 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5853 if (CA == SectionRef())
5854 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5855 info.S = CA;
5856 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005857
Kevin Enderby5879a482017-02-09 17:56:26 +00005858 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5859 if (PL == SectionRef())
5860 PL = get_section(O, "__DATA", "__objc_protolist");
5861 if (PL == SectionRef())
5862 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5863 if (PL == SectionRef())
5864 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5865 info.S = PL;
5866 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005867
Kevin Enderby5879a482017-02-09 17:56:26 +00005868 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5869 if (MR == SectionRef())
5870 MR = get_section(O, "__DATA", "__objc_msgrefs");
5871 if (MR == SectionRef())
5872 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5873 if (MR == SectionRef())
5874 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5875 info.S = MR;
5876 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005877
Kevin Enderby5879a482017-02-09 17:56:26 +00005878 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5879 if (II == SectionRef())
5880 II = get_section(O, "__DATA", "__objc_imageinfo");
5881 if (II == SectionRef())
5882 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5883 if (II == SectionRef())
5884 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5885 info.S = II;
5886 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005887}
5888
5889static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005890 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5891 const char *r, *name, *defs;
5892 struct objc_module_t module;
5893 SectionRef S, xS;
5894 struct objc_symtab_t symtab;
5895 struct objc_class_t objc_class;
5896 struct objc_category_t objc_category;
5897
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005898 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005899 S = get_section(O, "__OBJC", "__module_info");
5900 if (S == SectionRef())
5901 return false;
5902
5903 SymbolAddressMap AddrMap;
5904 if (verbose)
5905 CreateSymbolAddressMap(O, &AddrMap);
5906
5907 std::vector<SectionRef> Sections;
5908 for (const SectionRef &Section : O->sections()) {
5909 StringRef SectName;
5910 Section.getName(SectName);
5911 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005912 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005913
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005914 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00005915
5916 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5917 p = S.getAddress() + i;
5918 r = get_pointer_32(p, offset, left, S, &info, true);
5919 if (r == nullptr)
5920 return true;
5921 memset(&module, '\0', sizeof(struct objc_module_t));
5922 if (left < sizeof(struct objc_module_t)) {
5923 memcpy(&module, r, left);
5924 outs() << " (module extends past end of __module_info section)\n";
5925 } else
5926 memcpy(&module, r, sizeof(struct objc_module_t));
5927 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5928 swapStruct(module);
5929
5930 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5931 outs() << " version " << module.version << "\n";
5932 outs() << " size " << module.size << "\n";
5933 outs() << " name ";
5934 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5935 if (name != nullptr)
5936 outs() << format("%.*s", left, name);
5937 else
5938 outs() << format("0x%08" PRIx32, module.name)
5939 << "(not in an __OBJC section)";
5940 outs() << "\n";
5941
5942 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5943 if (module.symtab == 0 || r == nullptr) {
5944 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5945 << " (not in an __OBJC section)\n";
5946 continue;
5947 }
5948 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5949 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5950 defs_left = 0;
5951 defs = nullptr;
5952 if (left < sizeof(struct objc_symtab_t)) {
5953 memcpy(&symtab, r, left);
5954 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5955 } else {
5956 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5957 if (left > sizeof(struct objc_symtab_t)) {
5958 defs_left = left - sizeof(struct objc_symtab_t);
5959 defs = r + sizeof(struct objc_symtab_t);
5960 }
5961 }
5962 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5963 swapStruct(symtab);
5964
5965 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5966 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5967 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5968 if (r == nullptr)
5969 outs() << " (not in an __OBJC section)";
5970 outs() << "\n";
5971 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5972 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5973 if (symtab.cls_def_cnt > 0)
5974 outs() << "\tClass Definitions\n";
5975 for (j = 0; j < symtab.cls_def_cnt; j++) {
5976 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5977 outs() << "\t(remaining class defs entries entends past the end of the "
5978 << "section)\n";
5979 break;
5980 }
5981 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5982 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5983 sys::swapByteOrder(def);
5984
5985 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5986 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5987 if (r != nullptr) {
5988 if (left > sizeof(struct objc_class_t)) {
5989 outs() << "\n";
5990 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5991 } else {
5992 outs() << " (entends past the end of the section)\n";
5993 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5994 memcpy(&objc_class, r, left);
5995 }
5996 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5997 swapStruct(objc_class);
5998 print_objc_class_t(&objc_class, &info);
5999 } else {
6000 outs() << "(not in an __OBJC section)\n";
6001 }
6002
6003 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6004 outs() << "\tMeta Class";
6005 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6006 if (r != nullptr) {
6007 if (left > sizeof(struct objc_class_t)) {
6008 outs() << "\n";
6009 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6010 } else {
6011 outs() << " (entends past the end of the section)\n";
6012 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6013 memcpy(&objc_class, r, left);
6014 }
6015 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6016 swapStruct(objc_class);
6017 print_objc_class_t(&objc_class, &info);
6018 } else {
6019 outs() << "(not in an __OBJC section)\n";
6020 }
6021 }
6022 }
6023 if (symtab.cat_def_cnt > 0)
6024 outs() << "\tCategory Definitions\n";
6025 for (j = 0; j < symtab.cat_def_cnt; j++) {
6026 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6027 outs() << "\t(remaining category defs entries entends past the end of "
6028 << "the section)\n";
6029 break;
6030 }
6031 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6032 sizeof(uint32_t));
6033 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6034 sys::swapByteOrder(def);
6035
6036 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6037 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6038 << format("0x%08" PRIx32, def);
6039 if (r != nullptr) {
6040 if (left > sizeof(struct objc_category_t)) {
6041 outs() << "\n";
6042 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6043 } else {
6044 outs() << " (entends past the end of the section)\n";
6045 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6046 memcpy(&objc_category, r, left);
6047 }
6048 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6049 swapStruct(objc_category);
6050 print_objc_objc_category_t(&objc_category, &info);
6051 } else {
6052 outs() << "(not in an __OBJC section)\n";
6053 }
6054 }
6055 }
6056 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6057 if (II != SectionRef())
6058 print_image_info(II, &info);
6059
6060 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006061}
6062
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006063static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6064 uint32_t size, uint32_t addr) {
6065 SymbolAddressMap AddrMap;
6066 CreateSymbolAddressMap(O, &AddrMap);
6067
6068 std::vector<SectionRef> Sections;
6069 for (const SectionRef &Section : O->sections()) {
6070 StringRef SectName;
6071 Section.getName(SectName);
6072 Sections.push_back(Section);
6073 }
6074
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006075 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006076
6077 const char *p;
6078 struct objc_protocol_t protocol;
6079 uint32_t left, paddr;
6080 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6081 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6082 left = size - (p - sect);
6083 if (left < sizeof(struct objc_protocol_t)) {
6084 outs() << "Protocol extends past end of __protocol section\n";
6085 memcpy(&protocol, p, left);
6086 } else
6087 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6088 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6089 swapStruct(protocol);
6090 paddr = addr + (p - sect);
6091 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6092 if (print_protocol(paddr, 0, &info))
6093 outs() << "(not in an __OBJC section)\n";
6094 }
6095}
6096
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006097#ifdef HAVE_LIBXAR
6098inline void swapStruct(struct xar_header &xar) {
6099 sys::swapByteOrder(xar.magic);
6100 sys::swapByteOrder(xar.size);
6101 sys::swapByteOrder(xar.version);
6102 sys::swapByteOrder(xar.toc_length_compressed);
6103 sys::swapByteOrder(xar.toc_length_uncompressed);
6104 sys::swapByteOrder(xar.cksum_alg);
6105}
6106
6107static void PrintModeVerbose(uint32_t mode) {
6108 switch(mode & S_IFMT){
6109 case S_IFDIR:
6110 outs() << "d";
6111 break;
6112 case S_IFCHR:
6113 outs() << "c";
6114 break;
6115 case S_IFBLK:
6116 outs() << "b";
6117 break;
6118 case S_IFREG:
6119 outs() << "-";
6120 break;
6121 case S_IFLNK:
6122 outs() << "l";
6123 break;
6124 case S_IFSOCK:
6125 outs() << "s";
6126 break;
6127 default:
6128 outs() << "?";
6129 break;
6130 }
6131
6132 /* owner permissions */
6133 if(mode & S_IREAD)
6134 outs() << "r";
6135 else
6136 outs() << "-";
6137 if(mode & S_IWRITE)
6138 outs() << "w";
6139 else
6140 outs() << "-";
6141 if(mode & S_ISUID)
6142 outs() << "s";
6143 else if(mode & S_IEXEC)
6144 outs() << "x";
6145 else
6146 outs() << "-";
6147
6148 /* group permissions */
6149 if(mode & (S_IREAD >> 3))
6150 outs() << "r";
6151 else
6152 outs() << "-";
6153 if(mode & (S_IWRITE >> 3))
6154 outs() << "w";
6155 else
6156 outs() << "-";
6157 if(mode & S_ISGID)
6158 outs() << "s";
6159 else if(mode & (S_IEXEC >> 3))
6160 outs() << "x";
6161 else
6162 outs() << "-";
6163
6164 /* other permissions */
6165 if(mode & (S_IREAD >> 6))
6166 outs() << "r";
6167 else
6168 outs() << "-";
6169 if(mode & (S_IWRITE >> 6))
6170 outs() << "w";
6171 else
6172 outs() << "-";
6173 if(mode & S_ISVTX)
6174 outs() << "t";
6175 else if(mode & (S_IEXEC >> 6))
6176 outs() << "x";
6177 else
6178 outs() << "-";
6179}
6180
6181static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006182 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006183 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6184 char *endp;
6185 uint32_t mode_value;
6186
Francis Ricci6f942972017-10-06 15:33:28 +00006187 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006188 if (!xi) {
6189 errs() << "Can't obtain an xar iterator for xar archive "
6190 << XarFilename << "\n";
6191 return;
6192 }
6193
6194 // Go through the xar's files.
6195 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006196 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006197 if(!xp){
6198 errs() << "Can't obtain an xar iterator for xar archive "
6199 << XarFilename << "\n";
6200 return;
6201 }
6202 type = nullptr;
6203 mode = nullptr;
6204 user = nullptr;
6205 group = nullptr;
6206 size = nullptr;
6207 mtime = nullptr;
6208 name = nullptr;
6209 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006210 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006211 xar_prop_get(xf, key, &val);
6212#if 0 // Useful for debugging.
6213 outs() << "key: " << key << " value: " << val << "\n";
6214#endif
6215 if(strcmp(key, "type") == 0)
6216 type = val;
6217 if(strcmp(key, "mode") == 0)
6218 mode = val;
6219 if(strcmp(key, "user") == 0)
6220 user = val;
6221 if(strcmp(key, "group") == 0)
6222 group = val;
6223 if(strcmp(key, "data/size") == 0)
6224 size = val;
6225 if(strcmp(key, "mtime") == 0)
6226 mtime = val;
6227 if(strcmp(key, "name") == 0)
6228 name = val;
6229 }
6230 if(mode != nullptr){
6231 mode_value = strtoul(mode, &endp, 8);
6232 if(*endp != '\0')
6233 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6234 if(strcmp(type, "file") == 0)
6235 mode_value |= S_IFREG;
6236 PrintModeVerbose(mode_value);
6237 outs() << " ";
6238 }
6239 if(user != nullptr)
6240 outs() << format("%10s/", user);
6241 if(group != nullptr)
6242 outs() << format("%-10s ", group);
6243 if(size != nullptr)
6244 outs() << format("%7s ", size);
6245 if(mtime != nullptr){
6246 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6247 outs() << *m;
6248 if(*m == 'T')
6249 m++;
6250 outs() << " ";
6251 for( ; *m != 'Z' && *m != '\0'; m++)
6252 outs() << *m;
6253 outs() << " ";
6254 }
6255 if(name != nullptr)
6256 outs() << name;
6257 outs() << "\n";
6258 }
6259}
6260
6261static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6262 uint32_t size, bool verbose,
6263 bool PrintXarHeader, bool PrintXarFileHeaders,
6264 std::string XarMemberName) {
6265 if(size < sizeof(struct xar_header)) {
6266 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6267 "of struct xar_header)\n";
6268 return;
6269 }
6270 struct xar_header XarHeader;
6271 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6272 if (sys::IsLittleEndianHost)
6273 swapStruct(XarHeader);
6274 if (PrintXarHeader) {
6275 if (!XarMemberName.empty())
6276 outs() << "In xar member " << XarMemberName << ": ";
6277 else
6278 outs() << "For (__LLVM,__bundle) section: ";
6279 outs() << "xar header\n";
6280 if (XarHeader.magic == XAR_HEADER_MAGIC)
6281 outs() << " magic XAR_HEADER_MAGIC\n";
6282 else
6283 outs() << " magic "
6284 << format_hex(XarHeader.magic, 10, true)
6285 << " (not XAR_HEADER_MAGIC)\n";
6286 outs() << " size " << XarHeader.size << "\n";
6287 outs() << " version " << XarHeader.version << "\n";
6288 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6289 << "\n";
6290 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6291 << "\n";
6292 outs() << " cksum_alg ";
6293 switch (XarHeader.cksum_alg) {
6294 case XAR_CKSUM_NONE:
6295 outs() << "XAR_CKSUM_NONE\n";
6296 break;
6297 case XAR_CKSUM_SHA1:
6298 outs() << "XAR_CKSUM_SHA1\n";
6299 break;
6300 case XAR_CKSUM_MD5:
6301 outs() << "XAR_CKSUM_MD5\n";
6302 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006303#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006304 case XAR_CKSUM_SHA256:
6305 outs() << "XAR_CKSUM_SHA256\n";
6306 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006307#endif
6308#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006309 case XAR_CKSUM_SHA512:
6310 outs() << "XAR_CKSUM_SHA512\n";
6311 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006312#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006313 default:
6314 outs() << XarHeader.cksum_alg << "\n";
6315 }
6316 }
6317
6318 SmallString<128> XarFilename;
6319 int FD;
6320 std::error_code XarEC =
6321 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6322 if (XarEC) {
6323 errs() << XarEC.message() << "\n";
6324 return;
6325 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006326 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006327 raw_fd_ostream &XarOut = XarFile.os();
6328 StringRef XarContents(sect, size);
6329 XarOut << XarContents;
6330 XarOut.close();
6331 if (XarOut.has_error())
6332 return;
6333
Francis Ricci6f942972017-10-06 15:33:28 +00006334 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006335 if (!xar) {
6336 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
6337 return;
6338 }
6339
6340 SmallString<128> TocFilename;
6341 std::error_code TocEC =
6342 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6343 if (TocEC) {
6344 errs() << TocEC.message() << "\n";
6345 return;
6346 }
6347 xar_serialize(xar, TocFilename.c_str());
6348
6349 if (PrintXarFileHeaders) {
6350 if (!XarMemberName.empty())
6351 outs() << "In xar member " << XarMemberName << ": ";
6352 else
6353 outs() << "For (__LLVM,__bundle) section: ";
6354 outs() << "xar archive files:\n";
6355 PrintXarFilesSummary(XarFilename.c_str(), xar);
6356 }
6357
6358 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6359 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6360 if (std::error_code EC = FileOrErr.getError()) {
6361 errs() << EC.message() << "\n";
6362 return;
6363 }
6364 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6365
6366 if (!XarMemberName.empty())
6367 outs() << "In xar member " << XarMemberName << ": ";
6368 else
6369 outs() << "For (__LLVM,__bundle) section: ";
6370 outs() << "xar table of contents:\n";
6371 outs() << Buffer->getBuffer() << "\n";
6372
6373 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006374 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006375 if(!xi){
6376 errs() << "Can't obtain an xar iterator for xar archive "
6377 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006378 return;
6379 }
6380 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6381 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006382 const char *member_name, *member_type, *member_size_string;
6383 size_t member_size;
6384
Francis Ricci6f942972017-10-06 15:33:28 +00006385 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006386 if(!xp){
6387 errs() << "Can't obtain an xar iterator for xar archive "
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006388 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006389 return;
6390 }
6391 member_name = NULL;
6392 member_type = NULL;
6393 member_size_string = NULL;
6394 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006395 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006396 xar_prop_get(xf, key, &val);
6397#if 0 // Useful for debugging.
6398 outs() << "key: " << key << " value: " << val << "\n";
6399#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006400 if (strcmp(key, "name") == 0)
6401 member_name = val;
6402 if (strcmp(key, "type") == 0)
6403 member_type = val;
6404 if (strcmp(key, "data/size") == 0)
6405 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006406 }
6407 /*
6408 * If we find a file with a name, date/size and type properties
6409 * and with the type being "file" see if that is a xar file.
6410 */
6411 if (member_name != NULL && member_type != NULL &&
6412 strcmp(member_type, "file") == 0 &&
6413 member_size_string != NULL){
6414 // Extract the file into a buffer.
6415 char *endptr;
6416 member_size = strtoul(member_size_string, &endptr, 10);
6417 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006418 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006419 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006420#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006421 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006422#endif
6423 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006424 std::string OldXarMemberName;
6425 // If XarMemberName is already set this is nested. So
6426 // save the old name and create the nested name.
6427 if (!XarMemberName.empty()) {
6428 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006429 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006430 (Twine("[") + XarMemberName + "]" + member_name).str();
6431 } else {
6432 OldXarMemberName = "";
6433 XarMemberName = member_name;
6434 }
6435 // See if this is could be a xar file (nested).
6436 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006437#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006438 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006439#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006440 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006441 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006442 swapStruct(XarHeader);
6443 if (XarHeader.magic == XAR_HEADER_MAGIC)
6444 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006445 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006446 XarMemberName);
6447 }
6448 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006449 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006450 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006451 }
6452 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006453 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006454}
6455#endif // defined(HAVE_LIBXAR)
6456
Kevin Enderby0fc11822015-04-01 20:57:01 +00006457static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6458 if (O->is64Bit())
6459 printObjc2_64bit_MetaData(O, verbose);
6460 else {
6461 MachO::mach_header H;
6462 H = O->getHeader();
6463 if (H.cputype == MachO::CPU_TYPE_ARM)
6464 printObjc2_32bit_MetaData(O, verbose);
6465 else {
6466 // This is the 32-bit non-arm cputype case. Which is normally
6467 // the first Objective-C ABI. But it may be the case of a
6468 // binary for the iOS simulator which is the second Objective-C
6469 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6470 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006471 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006472 printObjc2_32bit_MetaData(O, verbose);
6473 }
6474 }
6475}
6476
Kevin Enderbybf246f52014-09-24 23:08:22 +00006477// GuessLiteralPointer returns a string which for the item in the Mach-O file
6478// for the address passed in as ReferenceValue for printing as a comment with
6479// the instruction and also returns the corresponding type of that item
6480// indirectly through ReferenceType.
6481//
6482// If ReferenceValue is an address of literal cstring then a pointer to the
6483// cstring is returned and ReferenceType is set to
6484// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6485//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006486// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6487// Class ref that name is returned and the ReferenceType is set accordingly.
6488//
6489// Lastly, literals which are Symbol address in a literal pool are looked for
6490// and if found the symbol name is returned and ReferenceType is set to
6491// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6492//
6493// If there is no item in the Mach-O file for the address passed in as
6494// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006495static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6496 uint64_t ReferencePC,
6497 uint64_t *ReferenceType,
6498 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006499 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006500 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6501 uint64_t sect_addr = info->S.getAddress();
6502 uint64_t sect_offset = ReferencePC - sect_addr;
6503 bool reloc_found = false;
6504 DataRefImpl Rel;
6505 MachO::any_relocation_info RE;
6506 bool isExtern = false;
6507 SymbolRef Symbol;
6508 for (const RelocationRef &Reloc : info->S.relocations()) {
6509 uint64_t RelocOffset = Reloc.getOffset();
6510 if (RelocOffset == sect_offset) {
6511 Rel = Reloc.getRawDataRefImpl();
6512 RE = info->O->getRelocation(Rel);
6513 if (info->O->isRelocationScattered(RE))
6514 continue;
6515 isExtern = info->O->getPlainRelocationExternal(RE);
6516 if (isExtern) {
6517 symbol_iterator RelocSym = Reloc.getSymbol();
6518 Symbol = *RelocSym;
6519 }
6520 reloc_found = true;
6521 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006522 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006523 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006524 // If there is an external relocation entry for a symbol in a section
6525 // then used that symbol's value for the value of the reference.
6526 if (reloc_found && isExtern) {
6527 if (info->O->getAnyRelocationPCRel(RE)) {
6528 unsigned Type = info->O->getAnyRelocationType(RE);
6529 if (Type == MachO::X86_64_RELOC_SIGNED) {
6530 ReferenceValue = Symbol.getValue();
6531 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006532 }
6533 }
6534 }
6535
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006536 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6537 // Message refs and Class refs.
6538 bool classref, selref, msgref, cfstring;
6539 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6540 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006541 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006542 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6543 // And the pointer_value in that section is typically zero as it will be
6544 // set by dyld as part of the "bind information".
6545 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6546 if (name != nullptr) {
6547 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006548 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006549 if (class_name != nullptr && class_name[1] == '_' &&
6550 class_name[2] != '\0') {
6551 info->class_name = class_name + 2;
6552 return name;
6553 }
6554 }
6555 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006556
David Blaikie33dd45d02015-03-23 18:39:02 +00006557 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006558 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6559 const char *name =
6560 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6561 if (name != nullptr)
6562 info->class_name = name;
6563 else
6564 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006565 return name;
6566 }
6567
David Blaikie33dd45d02015-03-23 18:39:02 +00006568 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006569 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6570 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6571 return name;
6572 }
6573
David Blaikie33dd45d02015-03-23 18:39:02 +00006574 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006575 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6576
6577 if (pointer_value != 0)
6578 ReferenceValue = pointer_value;
6579
6580 const char *name = GuessCstringPointer(ReferenceValue, info);
6581 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006582 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006583 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6584 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006585 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006586 info->class_name = nullptr;
6587 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6588 info->selector_name = name;
6589 } else
6590 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6591 return name;
6592 }
6593
6594 // Lastly look for an indirect symbol with this ReferenceValue which is in
6595 // a literal pool. If found return that symbol name.
6596 name = GuessIndirectSymbol(ReferenceValue, info);
6597 if (name) {
6598 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6599 return name;
6600 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006601
6602 return nullptr;
6603}
6604
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006605// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006606// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006607// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6608// is created and returns the symbol name that matches the ReferenceValue or
6609// nullptr if none. The ReferenceType is passed in for the IN type of
6610// reference the instruction is making from the values in defined in the header
6611// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6612// Out type and the ReferenceName will also be set which is added as a comment
6613// to the disassembled instruction.
6614//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006615// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006616// returned through ReferenceName and ReferenceType is set to
6617// LLVMDisassembler_ReferenceType_DeMangled_Name .
6618//
6619// When this is called to get a symbol name for a branch target then the
6620// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6621// SymbolValue will be looked for in the indirect symbol table to determine if
6622// it is an address for a symbol stub. If so then the symbol name for that
6623// stub is returned indirectly through ReferenceName and then ReferenceType is
6624// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6625//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006626// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006627// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6628// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6629// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006630// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006631static const char *SymbolizerSymbolLookUp(void *DisInfo,
6632 uint64_t ReferenceValue,
6633 uint64_t *ReferenceType,
6634 uint64_t ReferencePC,
6635 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006636 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006637 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006638 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006639 *ReferenceName = nullptr;
6640 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006641 return nullptr;
6642 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006643
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006644 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006645
Kevin Enderby85974882014-09-26 22:20:44 +00006646 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6647 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006648 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006649 method_reference(info, ReferenceType, ReferenceName);
6650 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6651 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006652 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006653 if (info->demangled_name != nullptr)
6654 free(info->demangled_name);
6655 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006656 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006657 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006658 if (info->demangled_name != nullptr) {
6659 *ReferenceName = info->demangled_name;
6660 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6661 } else
6662 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6663 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006664 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6665 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6666 *ReferenceName =
6667 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006668 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006669 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006670 else
6671 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006672 // If this is arm64 and the reference is an adrp instruction save the
6673 // instruction, passed in ReferenceValue and the address of the instruction
6674 // for use later if we see and add immediate instruction.
6675 } else if (info->O->getArch() == Triple::aarch64 &&
6676 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6677 info->adrp_inst = ReferenceValue;
6678 info->adrp_addr = ReferencePC;
6679 SymbolName = nullptr;
6680 *ReferenceName = nullptr;
6681 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6682 // If this is arm64 and reference is an add immediate instruction and we
6683 // have
6684 // seen an adrp instruction just before it and the adrp's Xd register
6685 // matches
6686 // this add's Xn register reconstruct the value being referenced and look to
6687 // see if it is a literal pointer. Note the add immediate instruction is
6688 // passed in ReferenceValue.
6689 } else if (info->O->getArch() == Triple::aarch64 &&
6690 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6691 ReferencePC - 4 == info->adrp_addr &&
6692 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6693 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6694 uint32_t addxri_inst;
6695 uint64_t adrp_imm, addxri_imm;
6696
6697 adrp_imm =
6698 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6699 if (info->adrp_inst & 0x0200000)
6700 adrp_imm |= 0xfffffffffc000000LL;
6701
6702 addxri_inst = ReferenceValue;
6703 addxri_imm = (addxri_inst >> 10) & 0xfff;
6704 if (((addxri_inst >> 22) & 0x3) == 1)
6705 addxri_imm <<= 12;
6706
6707 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6708 (adrp_imm << 12) + addxri_imm;
6709
6710 *ReferenceName =
6711 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6712 if (*ReferenceName == nullptr)
6713 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6714 // If this is arm64 and the reference is a load register instruction and we
6715 // have seen an adrp instruction just before it and the adrp's Xd register
6716 // matches this add's Xn register reconstruct the value being referenced and
6717 // look to see if it is a literal pointer. Note the load register
6718 // instruction is passed in ReferenceValue.
6719 } else if (info->O->getArch() == Triple::aarch64 &&
6720 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6721 ReferencePC - 4 == info->adrp_addr &&
6722 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6723 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6724 uint32_t ldrxui_inst;
6725 uint64_t adrp_imm, ldrxui_imm;
6726
6727 adrp_imm =
6728 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6729 if (info->adrp_inst & 0x0200000)
6730 adrp_imm |= 0xfffffffffc000000LL;
6731
6732 ldrxui_inst = ReferenceValue;
6733 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6734
6735 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6736 (adrp_imm << 12) + (ldrxui_imm << 3);
6737
6738 *ReferenceName =
6739 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6740 if (*ReferenceName == nullptr)
6741 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6742 }
6743 // If this arm64 and is an load register (PC-relative) instruction the
6744 // ReferenceValue is the PC plus the immediate value.
6745 else if (info->O->getArch() == Triple::aarch64 &&
6746 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6747 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6748 *ReferenceName =
6749 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6750 if (*ReferenceName == nullptr)
6751 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006752 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006753 if (info->demangled_name != nullptr)
6754 free(info->demangled_name);
6755 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006756 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006757 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006758 if (info->demangled_name != nullptr) {
6759 *ReferenceName = info->demangled_name;
6760 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6761 }
6762 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006763 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006764 *ReferenceName = nullptr;
6765 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6766 }
6767
6768 return SymbolName;
6769}
6770
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006771/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006772/// Each comment in the CommentStream must end with a newline.
6773static void emitComments(raw_svector_ostream &CommentStream,
6774 SmallString<128> &CommentsToEmit,
6775 formatted_raw_ostream &FormattedOS,
6776 const MCAsmInfo &MAI) {
6777 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006778 StringRef Comments = CommentsToEmit.str();
6779 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006780 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006781 unsigned CommentColumn = MAI.getCommentColumn();
6782 bool IsFirst = true;
6783 while (!Comments.empty()) {
6784 if (!IsFirst)
6785 FormattedOS << '\n';
6786 // Emit a line of comments.
6787 FormattedOS.PadToColumn(CommentColumn);
6788 size_t Position = Comments.find('\n');
6789 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6790 // Move after the newline character.
6791 Comments = Comments.substr(Position + 1);
6792 IsFirst = false;
6793 }
6794 FormattedOS.flush();
6795
6796 // Tell the comment stream that the vector changed underneath it.
6797 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006798}
6799
Kevin Enderby95df54c2015-02-04 01:01:38 +00006800static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6801 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006802 const char *McpuDefault = nullptr;
6803 const Target *ThumbTarget = nullptr;
6804 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006805 if (!TheTarget) {
6806 // GetTarget prints out stuff.
6807 return;
6808 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00006809 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006810 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00006811 MachOMCPU = McpuDefault;
6812 else
6813 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006814
Ahmed Charles56440fd2014-03-06 05:51:42 +00006815 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006816 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006817 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006818 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006819
Kevin Enderbyc9595622014-08-06 23:24:41 +00006820 // Package up features to be passed to target/subtarget
6821 std::string FeaturesStr;
6822 if (MAttrs.size()) {
6823 SubtargetFeatures Features;
6824 for (unsigned i = 0; i != MAttrs.size(); ++i)
6825 Features.AddFeature(MAttrs[i]);
6826 FeaturesStr = Features.getString();
6827 }
6828
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006829 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006830 std::unique_ptr<const MCRegisterInfo> MRI(
6831 TheTarget->createMCRegInfo(TripleName));
6832 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006833 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006834 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006835 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006836 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006837 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006838 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006839 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006840 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006841 std::unique_ptr<MCRelocationInfo> RelInfo(
6842 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6843 if (RelInfo) {
6844 Symbolizer.reset(TheTarget->createMCSymbolizer(
6845 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006846 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006847 DisAsm->setSymbolizer(std::move(Symbolizer));
6848 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006849 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006850 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006851 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006852 // Set the display preference for hex vs. decimal immediates.
6853 IP->setPrintImmHex(PrintImmHex);
6854 // Comment stream and backing vector.
6855 SmallString<128> CommentsToEmit;
6856 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006857 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6858 // if it is done then arm64 comments for string literals don't get printed
6859 // and some constant get printed instead and not setting it causes intel
6860 // (32-bit and 64-bit) comments printed with different spacing before the
6861 // comment causing different diffs with the 'C' disassembler library API.
6862 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006863
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006864 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006865 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006866 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006867 return;
6868 }
6869
Tim Northover09ca33e2016-04-22 23:23:31 +00006870 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006871 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6872 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6873 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006874 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006875 std::unique_ptr<MCInstPrinter> ThumbIP;
6876 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006877 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006878 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006879 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006880 if (ThumbTarget) {
6881 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6882 ThumbAsmInfo.reset(
6883 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6884 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006885 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6886 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006887 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6888 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006889 MCContext *PtrThumbCtx = ThumbCtx.get();
6890 ThumbRelInfo.reset(
6891 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6892 if (ThumbRelInfo) {
6893 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6894 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006895 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006896 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6897 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006898 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6899 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006900 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6901 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006902 // Set the display preference for hex vs. decimal immediates.
6903 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006904 }
6905
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006906 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006907 errs() << "error: couldn't initialize disassembler for target "
6908 << ThumbTripleName << '\n';
6909 return;
6910 }
6911
Charles Davis8bdfafd2013-09-01 04:28:48 +00006912 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006913
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006914 // FIXME: Using the -cfg command line option, this code used to be able to
6915 // annotate relocations with the referenced symbol's name, and if this was
6916 // inside a __[cf]string section, the data it points to. This is now replaced
6917 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006918 std::vector<SectionRef> Sections;
6919 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006920 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006921 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006922
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006923 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006924 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006925
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006926 // Sort the symbols by address, just in case they didn't come in that way.
Mandeep Singh Grang8db564e2018-04-01 21:24:53 +00006927 llvm::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006928
Kevin Enderby273ae012013-06-06 17:20:50 +00006929 // Build a data in code table that is sorted on by the address of each entry.
6930 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006931 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006932 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006933 else
6934 BaseAddress = BaseSegmentAddress;
6935 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006936 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006937 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006938 uint32_t Offset;
6939 DI->getOffset(Offset);
6940 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6941 }
6942 array_pod_sort(Dices.begin(), Dices.end());
6943
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006944#ifndef NDEBUG
6945 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6946#else
6947 raw_ostream &DebugOut = nulls();
6948#endif
6949
Ahmed Charles56440fd2014-03-06 05:51:42 +00006950 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006951 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006952 // Try to find debug info and set up the DIContext for it.
6953 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006954 // A separate DSym file path was specified, parse it as a macho file,
6955 // get the sections and supply it to the section name parsing machinery.
6956 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006957 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006958 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006959 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006960 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006961 return;
6962 }
Gerolf Hoflehnerbf26d542018-04-19 20:48:35 +00006963 Expected<std::unique_ptr<MachOObjectFile>> DbgObjCheck =
6964 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef());
6965
6966 if (DbgObjCheck.takeError())
6967 report_error(MachOOF->getFileName(), DbgObjCheck.takeError());
6968 DbgObj = DbgObjCheck.get().release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006969 }
6970
Eric Christopher7370b552012-11-12 21:40:38 +00006971 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00006972 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00006973 }
6974
Colin LeMahieufcc32762015-07-29 19:08:10 +00006975 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006976 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006977
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006978 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006979 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006980 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6981 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006982
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006983 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006984
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006985 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006986 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006987 continue;
6988
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006989 StringRef BytesStr;
6990 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006991 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6992 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006993 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006994
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006995 bool symbolTableWorked = false;
6996
Kevin Enderbybf246f52014-09-24 23:08:22 +00006997 // Create a map of symbol addresses to symbol names for use by
6998 // the SymbolizerSymbolLookUp() routine.
6999 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007000 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007001 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007002 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007003 if (!STOrErr)
7004 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007005 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007006 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7007 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007008 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007009 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007010 if (!SymNameOrErr)
7011 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007012 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007013 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007014 if (!DisSymName.empty() && DisSymName == SymName)
7015 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007016 }
7017 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007018 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007019 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7020 return;
7021 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007022 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007023 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007024 SymbolizerInfo.O = MachOOF;
7025 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007026 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007027 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007028 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007029 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007030 ThumbSymbolizerInfo.O = MachOOF;
7031 ThumbSymbolizerInfo.S = Sections[SectIdx];
7032 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7033 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007034
Kevin Enderby4b627be2016-04-28 20:14:13 +00007035 unsigned int Arch = MachOOF->getArch();
7036
Tim Northoverf203ab52016-07-14 22:13:32 +00007037 // Skip all symbols if this is a stubs file.
7038 if (Bytes.size() == 0)
7039 return;
7040
Kevin Enderbyc138da32017-02-06 18:43:18 +00007041 // If the section has symbols but no symbol at the start of the section
7042 // these are used to make sure the bytes before the first symbol are
7043 // disassembled.
7044 bool FirstSymbol = true;
7045 bool FirstSymbolAtSectionStart = true;
7046
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007047 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007048 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007049 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007050 if (!SymNameOrErr)
7051 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007052 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007053
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007054 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007055 if (!STOrErr)
7056 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007057 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007058 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007059 continue;
7060
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007061 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007062 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007063 if (!containsSym) {
7064 if (!DisSymName.empty() && DisSymName == SymName) {
7065 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7066 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007067 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007068 continue;
7069 }
7070 // The __mh_execute_header is special and we need to deal with that fact
7071 // this symbol is before the start of the (__TEXT,__text) section and at the
7072 // address of the start of the __TEXT segment. This is because this symbol
7073 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7074 // start of the section in a standard MH_EXECUTE filetype.
7075 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7076 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7077 return;
7078 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007079 // When this code is trying to disassemble a symbol at a time and in the
7080 // case there is only the __mh_execute_header symbol left as in a stripped
7081 // executable, we need to deal with this by ignoring this symbol so the
7082 // whole section is disassembled and this symbol is then not displayed.
7083 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7084 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7085 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007086 continue;
7087
Kevin Enderby6a221752015-03-17 17:10:57 +00007088 // If we are only disassembling one symbol see if this is that symbol.
7089 if (!DisSymName.empty() && DisSymName != SymName)
7090 continue;
7091
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007092 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007093 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007094 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007095 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007096 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007097
Tim Northoverf203ab52016-07-14 22:13:32 +00007098 if (Start > SectSize) {
7099 outs() << "section data ends, " << SymName
7100 << " lies outside valid range\n";
7101 return;
7102 }
7103
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007104 // Stop disassembling either at the beginning of the next symbol or at
7105 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007106 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007107 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007108 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007109 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007110 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007111 if (!STOrErr)
7112 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007113 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007114 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007115 containsNextSym =
7116 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007117 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007118 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007119 break;
7120 }
7121 ++NextSymIdx;
7122 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007123
Tim Northoverf203ab52016-07-14 22:13:32 +00007124 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007125 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007126
7127 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007128
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007129 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007130 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7131
7132 // We only need the dedicated Thumb target if there's a real choice
7133 // (i.e. we're not targeting M-class) and the function is Thumb.
7134 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007135
Kevin Enderbyc138da32017-02-06 18:43:18 +00007136 // If we are not specifying a symbol to start disassembly with and this
7137 // is the first symbol in the section but not at the start of the section
7138 // then move the disassembly index to the start of the section and
7139 // don't print the symbol name just yet. This is so the bytes before the
7140 // first symbol are disassembled.
7141 uint64_t SymbolStart = Start;
7142 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7143 FirstSymbolAtSectionStart = false;
7144 Start = 0;
7145 }
7146 else
7147 outs() << SymName << ":\n";
7148
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007149 DILineInfo lastLine;
7150 for (uint64_t Index = Start; Index < End; Index += Size) {
7151 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007152
Kevin Enderbyc138da32017-02-06 18:43:18 +00007153 // If this is the first symbol in the section and it was not at the
7154 // start of the section, see if we are at its Index now and if so print
7155 // the symbol name.
7156 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7157 outs() << SymName << ":\n";
7158
Kevin Enderbybf246f52014-09-24 23:08:22 +00007159 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007160 if (!NoLeadingAddr) {
7161 if (FullLeadingAddr) {
7162 if (MachOOF->is64Bit())
7163 outs() << format("%016" PRIx64, PC);
7164 else
7165 outs() << format("%08" PRIx64, PC);
7166 } else {
7167 outs() << format("%8" PRIx64 ":", PC);
7168 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007169 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007170 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007171 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007172
7173 // Check the data in code table here to see if this is data not an
7174 // instruction to be disassembled.
7175 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007176 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007177 dice_table_iterator DTI =
7178 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7179 compareDiceTableEntries);
7180 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007181 uint16_t Length;
7182 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007183 uint16_t Kind;
7184 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007185 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007186 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7187 (PC == (DTI->first + Length - 1)) && (Length & 1))
7188 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007189 continue;
7190 }
7191
Kevin Enderbybf246f52014-09-24 23:08:22 +00007192 SmallVector<char, 64> AnnotationsBytes;
7193 raw_svector_ostream Annotations(AnnotationsBytes);
7194
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007195 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007196 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007197 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007198 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007199 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007200 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007201 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007202 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007203 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007204 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007205 }
7206 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007207 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007208 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007209 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007210 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007211 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007212 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007213
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007214 // Print debug info.
7215 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007216 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007217 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007218 if (dli != lastLine && dli.Line != 0)
7219 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7220 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007221 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007222 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007223 outs() << "\n";
7224 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007225 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007226 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007227 outs() << format("\t.byte 0x%02x #bad opcode\n",
7228 *(Bytes.data() + Index) & 0xff);
7229 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007230 } else if (Arch == Triple::aarch64 ||
7231 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007232 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7233 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7234 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7235 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7236 outs() << format("\t.long\t0x%08x\n", opcode);
7237 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007238 } else if (Arch == Triple::arm) {
7239 assert(IsThumb && "ARM mode should have been dealt with above");
7240 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7241 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7242 outs() << format("\t.short\t0x%04x\n", opcode);
7243 Size = 2;
7244 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007245 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7246 if (Size == 0)
7247 Size = 1; // skip illegible bytes
7248 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007249 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007250 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007251 // Now that we are done disassembled the first symbol set the bool that
7252 // were doing this to false.
7253 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007254 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007255 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007256 // Reading the symbol table didn't work, disassemble the whole section.
7257 uint64_t SectAddress = Sections[SectIdx].getAddress();
7258 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007259 uint64_t InstSize;
7260 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007261 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007262
Kevin Enderbybf246f52014-09-24 23:08:22 +00007263 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007264 SmallVector<char, 64> AnnotationsBytes;
7265 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007266 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007267 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007268 if (!NoLeadingAddr) {
7269 if (FullLeadingAddr) {
7270 if (MachOOF->is64Bit())
7271 outs() << format("%016" PRIx64, PC);
7272 else
7273 outs() << format("%08" PRIx64, PC);
7274 } else {
7275 outs() << format("%8" PRIx64 ":", PC);
7276 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007277 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007278 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007279 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007280 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007281 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007282 StringRef AnnotationsStr = Annotations.str();
7283 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007284 outs() << "\n";
7285 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007286 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007287 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007288 outs() << format("\t.byte 0x%02x #bad opcode\n",
7289 *(Bytes.data() + Index) & 0xff);
7290 InstSize = 1; // skip exactly one illegible byte and move on.
7291 } else {
7292 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7293 if (InstSize == 0)
7294 InstSize = 1; // skip illegible bytes
7295 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007296 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007297 }
7298 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007299 // The TripleName's need to be reset if we are called again for a different
7300 // archtecture.
7301 TripleName = "";
7302 ThumbTripleName = "";
7303
Kevin Enderby04bf6932014-10-28 23:39:46 +00007304 if (SymbolizerInfo.demangled_name != nullptr)
7305 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007306 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7307 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007308 }
7309}
Tim Northover4bd286a2014-08-01 13:07:19 +00007310
Tim Northover39c70bb2014-08-12 11:52:59 +00007311//===----------------------------------------------------------------------===//
7312// __compact_unwind section dumping
7313//===----------------------------------------------------------------------===//
7314
Tim Northover4bd286a2014-08-01 13:07:19 +00007315namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007316
Tim Northover3a4e1c72018-01-23 13:51:57 +00007317template <typename T>
7318static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007319 using llvm::support::little;
7320 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007321
Tim Northover3a4e1c72018-01-23 13:51:57 +00007322 if (Offset + sizeof(T) > Contents.size()) {
7323 outs() << "warning: attempt to read past end of buffer\n";
7324 return T();
7325 }
7326
7327 uint64_t Val =
7328 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7329 return Val;
7330}
7331
7332template <typename T>
7333static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7334 T Val = read<T>(Contents, Offset);
7335 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007336 return Val;
7337}
Tim Northover39c70bb2014-08-12 11:52:59 +00007338
Tim Northover4bd286a2014-08-01 13:07:19 +00007339struct CompactUnwindEntry {
7340 uint32_t OffsetInSection;
7341
7342 uint64_t FunctionAddr;
7343 uint32_t Length;
7344 uint32_t CompactEncoding;
7345 uint64_t PersonalityAddr;
7346 uint64_t LSDAAddr;
7347
7348 RelocationRef FunctionReloc;
7349 RelocationRef PersonalityReloc;
7350 RelocationRef LSDAReloc;
7351
7352 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007353 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007354 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007355 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007356 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007357 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007358 }
7359
7360private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007361 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7362 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7363 Length = readNext<uint32_t>(Contents, Offset);
7364 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7365 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7366 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007367 }
7368};
7369}
7370
7371/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7372/// and data being relocated, determine the best base Name and Addend to use for
7373/// display purposes.
7374///
7375/// 1. An Extern relocation will directly reference a symbol (and the data is
7376/// then already an addend), so use that.
7377/// 2. Otherwise the data is an offset in the object file's layout; try to find
7378// a symbol before it in the same section, and use the offset from there.
7379/// 3. Finally, if all that fails, fall back to an offset from the start of the
7380/// referenced section.
7381static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7382 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007383 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007384 StringRef &Name, uint64_t &Addend) {
7385 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007386 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007387 if (!NameOrErr)
7388 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007389 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007390 Addend = Addr;
7391 return;
7392 }
7393
7394 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007395 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007396
Rafael Espindola80291272014-10-08 15:28:58 +00007397 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007398
7399 auto Sym = Symbols.upper_bound(Addr);
7400 if (Sym == Symbols.begin()) {
7401 // The first symbol in the object is after this reference, the best we can
7402 // do is section-relative notation.
7403 RelocSection.getName(Name);
7404 Addend = Addr - SectionAddr;
7405 return;
7406 }
7407
7408 // Go back one so that SymbolAddress <= Addr.
7409 --Sym;
7410
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007411 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007412 if (!SectOrErr)
7413 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007414 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007415 if (RelocSection == *SymSection) {
7416 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007417 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007418 if (!NameOrErr)
7419 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007420 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007421 Addend = Addr - Sym->first;
7422 return;
7423 }
7424
7425 // There is a symbol before this reference, but it's in a different
7426 // section. Probably not helpful to mention it, so use the section name.
7427 RelocSection.getName(Name);
7428 Addend = Addr - SectionAddr;
7429}
7430
7431static void printUnwindRelocDest(const MachOObjectFile *Obj,
7432 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007433 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007434 StringRef Name;
7435 uint64_t Addend;
7436
Rafael Espindola854038e2015-06-26 14:51:16 +00007437 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007438 return;
7439
Tim Northover4bd286a2014-08-01 13:07:19 +00007440 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7441
7442 outs() << Name;
7443 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007444 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007445}
7446
7447static void
7448printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7449 std::map<uint64_t, SymbolRef> &Symbols,
7450 const SectionRef &CompactUnwind) {
7451
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007452 if (!Obj->isLittleEndian()) {
7453 outs() << "Skipping big-endian __compact_unwind section\n";
7454 return;
7455 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007456
7457 bool Is64 = Obj->is64Bit();
7458 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7459 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7460
7461 StringRef Contents;
7462 CompactUnwind.getContents(Contents);
7463
7464 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7465
7466 // First populate the initial raw offsets, encodings and so on from the entry.
7467 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007468 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007469 CompactUnwinds.push_back(Entry);
7470 }
7471
7472 // Next we need to look at the relocations to find out what objects are
7473 // actually being referred to.
7474 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007475 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007476
7477 uint32_t EntryIdx = RelocAddress / EntrySize;
7478 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7479 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7480
7481 if (OffsetInEntry == 0)
7482 Entry.FunctionReloc = Reloc;
7483 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7484 Entry.PersonalityReloc = Reloc;
7485 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7486 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007487 else {
7488 outs() << "Invalid relocation in __compact_unwind section\n";
7489 return;
7490 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007491 }
7492
7493 // Finally, we're ready to print the data we've gathered.
7494 outs() << "Contents of __compact_unwind section:\n";
7495 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007496 outs() << " Entry at offset "
7497 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007498
7499 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007500 outs() << " start: " << format("0x%" PRIx64,
7501 Entry.FunctionAddr) << ' ';
7502 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007503 outs() << '\n';
7504
7505 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007506 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7507 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007508 // 3. The 32-bit compact encoding.
7509 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007510 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007511
7512 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007513 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007514 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007515 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007516 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7517 Entry.PersonalityAddr);
7518 outs() << '\n';
7519 }
7520
7521 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007522 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007523 outs() << " LSDA: " << format("0x%" PRIx64,
7524 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007525 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7526 outs() << '\n';
7527 }
7528 }
7529}
7530
Tim Northover39c70bb2014-08-12 11:52:59 +00007531//===----------------------------------------------------------------------===//
7532// __unwind_info section dumping
7533//===----------------------------------------------------------------------===//
7534
Tim Northover3a4e1c72018-01-23 13:51:57 +00007535static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7536 ptrdiff_t Pos = 0;
7537 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007538 (void)Kind;
7539 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7540
Tim Northover3a4e1c72018-01-23 13:51:57 +00007541 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7542 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007543
Tim Northover3a4e1c72018-01-23 13:51:57 +00007544 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007545 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007546 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7547 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007548
7549 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007550 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7551 << ", "
7552 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007553 }
7554}
7555
7556static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007557 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007558 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007559 ptrdiff_t Pos = 0;
7560 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007561 (void)Kind;
7562 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7563
Tim Northover3a4e1c72018-01-23 13:51:57 +00007564 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7565 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007566
Tim Northover3a4e1c72018-01-23 13:51:57 +00007567 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7568 readNext<uint16_t>(PageData, Pos);
7569 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007570
Tim Northover3a4e1c72018-01-23 13:51:57 +00007571 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007572 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007573 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007574 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7575 uint32_t EncodingIdx = Entry >> 24;
7576
7577 uint32_t Encoding;
7578 if (EncodingIdx < CommonEncodings.size())
7579 Encoding = CommonEncodings[EncodingIdx];
7580 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007581 Encoding = read<uint32_t>(PageEncodings,
7582 sizeof(uint32_t) *
7583 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007584
7585 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007586 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7587 << ", "
7588 << "encoding[" << EncodingIdx
7589 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007590 }
7591}
7592
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007593static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7594 std::map<uint64_t, SymbolRef> &Symbols,
7595 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007596
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007597 if (!Obj->isLittleEndian()) {
7598 outs() << "Skipping big-endian __unwind_info section\n";
7599 return;
7600 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007601
7602 outs() << "Contents of __unwind_info section:\n";
7603
7604 StringRef Contents;
7605 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007606 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007607
7608 //===----------------------------------
7609 // Section header
7610 //===----------------------------------
7611
Tim Northover3a4e1c72018-01-23 13:51:57 +00007612 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007613 outs() << " Version: "
7614 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007615 if (Version != 1) {
7616 outs() << " Skipping section with unknown version\n";
7617 return;
7618 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007619
Tim Northover3a4e1c72018-01-23 13:51:57 +00007620 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007621 outs() << " Common encodings array section offset: "
7622 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007623 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007624 outs() << " Number of common encodings in array: "
7625 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7626
Tim Northover3a4e1c72018-01-23 13:51:57 +00007627 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007628 outs() << " Personality function array section offset: "
7629 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007630 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007631 outs() << " Number of personality functions in array: "
7632 << format("0x%" PRIx32, NumPersonalities) << '\n';
7633
Tim Northover3a4e1c72018-01-23 13:51:57 +00007634 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007635 outs() << " Index array section offset: "
7636 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007637 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007638 outs() << " Number of indices in array: "
7639 << format("0x%" PRIx32, NumIndices) << '\n';
7640
7641 //===----------------------------------
7642 // A shared list of common encodings
7643 //===----------------------------------
7644
7645 // These occupy indices in the range [0, N] whenever an encoding is referenced
7646 // from a compressed 2nd level index table. In practice the linker only
7647 // creates ~128 of these, so that indices are available to embed encodings in
7648 // the 2nd level index.
7649
7650 SmallVector<uint32_t, 64> CommonEncodings;
7651 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007652 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007653 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007654 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007655 CommonEncodings.push_back(Encoding);
7656
7657 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7658 << '\n';
7659 }
7660
Tim Northover39c70bb2014-08-12 11:52:59 +00007661 //===----------------------------------
7662 // Personality functions used in this executable
7663 //===----------------------------------
7664
7665 // There should be only a handful of these (one per source language,
7666 // roughly). Particularly since they only get 2 bits in the compact encoding.
7667
7668 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007669 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007670 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007671 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007672 outs() << " personality[" << i + 1
7673 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7674 }
7675
7676 //===----------------------------------
7677 // The level 1 index entries
7678 //===----------------------------------
7679
7680 // These specify an approximate place to start searching for the more detailed
7681 // information, sorted by PC.
7682
7683 struct IndexEntry {
7684 uint32_t FunctionOffset;
7685 uint32_t SecondLevelPageStart;
7686 uint32_t LSDAStart;
7687 };
7688
7689 SmallVector<IndexEntry, 4> IndexEntries;
7690
7691 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007692 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007693 for (unsigned i = 0; i < NumIndices; ++i) {
7694 IndexEntry Entry;
7695
Tim Northover3a4e1c72018-01-23 13:51:57 +00007696 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7697 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7698 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007699 IndexEntries.push_back(Entry);
7700
7701 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007702 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7703 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007704 << "2nd level page offset="
7705 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007706 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007707 }
7708
Tim Northover39c70bb2014-08-12 11:52:59 +00007709 //===----------------------------------
7710 // Next come the LSDA tables
7711 //===----------------------------------
7712
7713 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7714 // the first top-level index's LSDAOffset to the last (sentinel).
7715
7716 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007717 Pos = IndexEntries[0].LSDAStart;
7718 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7719 int NumLSDAs =
7720 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7721
Tim Northover39c70bb2014-08-12 11:52:59 +00007722 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007723 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7724 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007725 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007726 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7727 << ", "
7728 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007729 }
7730
7731 //===----------------------------------
7732 // Finally, the 2nd level indices
7733 //===----------------------------------
7734
7735 // Generally these are 4K in size, and have 2 possible forms:
7736 // + Regular stores up to 511 entries with disparate encodings
7737 // + Compressed stores up to 1021 entries if few enough compact encoding
7738 // values are used.
7739 outs() << " Second level indices:\n";
7740 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7741 // The final sentinel top-level index has no associated 2nd level page
7742 if (IndexEntries[i].SecondLevelPageStart == 0)
7743 break;
7744
7745 outs() << " Second level index[" << i << "]: "
7746 << "offset in section="
7747 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7748 << ", "
7749 << "base function offset="
7750 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7751
Tim Northover3a4e1c72018-01-23 13:51:57 +00007752 Pos = IndexEntries[i].SecondLevelPageStart;
7753 if (Pos + sizeof(uint32_t) > Contents.size()) {
7754 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7755 continue;
7756 }
7757
7758 uint32_t Kind =
7759 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007760 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007761 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007762 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007763 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7764 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007765 CommonEncodings);
7766 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007767 outs() << " Skipping 2nd level page with unknown kind " << Kind
7768 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007769 }
7770}
7771
Tim Northover4bd286a2014-08-01 13:07:19 +00007772void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7773 std::map<uint64_t, SymbolRef> Symbols;
7774 for (const SymbolRef &SymRef : Obj->symbols()) {
7775 // Discard any undefined or absolute symbols. They're not going to take part
7776 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007777 auto SectOrErr = SymRef.getSection();
7778 if (!SectOrErr) {
7779 // TODO: Actually report errors helpfully.
7780 consumeError(SectOrErr.takeError());
7781 continue;
7782 }
7783 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007784 if (Section == Obj->section_end())
7785 continue;
7786
Rafael Espindoladea00162015-07-03 17:44:18 +00007787 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007788 Symbols.insert(std::make_pair(Addr, SymRef));
7789 }
7790
7791 for (const SectionRef &Section : Obj->sections()) {
7792 StringRef SectName;
7793 Section.getName(SectName);
7794 if (SectName == "__compact_unwind")
7795 printMachOCompactUnwindSection(Obj, Symbols, Section);
7796 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007797 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007798 }
7799}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007800
7801static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7802 uint32_t cpusubtype, uint32_t filetype,
7803 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7804 bool verbose) {
7805 outs() << "Mach header\n";
7806 outs() << " magic cputype cpusubtype caps filetype ncmds "
7807 "sizeofcmds flags\n";
7808 if (verbose) {
7809 if (magic == MachO::MH_MAGIC)
7810 outs() << " MH_MAGIC";
7811 else if (magic == MachO::MH_MAGIC_64)
7812 outs() << "MH_MAGIC_64";
7813 else
7814 outs() << format(" 0x%08" PRIx32, magic);
7815 switch (cputype) {
7816 case MachO::CPU_TYPE_I386:
7817 outs() << " I386";
7818 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7819 case MachO::CPU_SUBTYPE_I386_ALL:
7820 outs() << " ALL";
7821 break;
7822 default:
7823 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7824 break;
7825 }
7826 break;
7827 case MachO::CPU_TYPE_X86_64:
7828 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007829 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7830 case MachO::CPU_SUBTYPE_X86_64_ALL:
7831 outs() << " ALL";
7832 break;
7833 case MachO::CPU_SUBTYPE_X86_64_H:
7834 outs() << " Haswell";
7835 break;
7836 default:
7837 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7838 break;
7839 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007840 break;
7841 case MachO::CPU_TYPE_ARM:
7842 outs() << " ARM";
7843 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7844 case MachO::CPU_SUBTYPE_ARM_ALL:
7845 outs() << " ALL";
7846 break;
7847 case MachO::CPU_SUBTYPE_ARM_V4T:
7848 outs() << " V4T";
7849 break;
7850 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7851 outs() << " V5TEJ";
7852 break;
7853 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7854 outs() << " XSCALE";
7855 break;
7856 case MachO::CPU_SUBTYPE_ARM_V6:
7857 outs() << " V6";
7858 break;
7859 case MachO::CPU_SUBTYPE_ARM_V6M:
7860 outs() << " V6M";
7861 break;
7862 case MachO::CPU_SUBTYPE_ARM_V7:
7863 outs() << " V7";
7864 break;
7865 case MachO::CPU_SUBTYPE_ARM_V7EM:
7866 outs() << " V7EM";
7867 break;
7868 case MachO::CPU_SUBTYPE_ARM_V7K:
7869 outs() << " V7K";
7870 break;
7871 case MachO::CPU_SUBTYPE_ARM_V7M:
7872 outs() << " V7M";
7873 break;
7874 case MachO::CPU_SUBTYPE_ARM_V7S:
7875 outs() << " V7S";
7876 break;
7877 default:
7878 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7879 break;
7880 }
7881 break;
7882 case MachO::CPU_TYPE_ARM64:
7883 outs() << " ARM64";
7884 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7885 case MachO::CPU_SUBTYPE_ARM64_ALL:
7886 outs() << " ALL";
7887 break;
7888 default:
7889 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7890 break;
7891 }
7892 break;
7893 case MachO::CPU_TYPE_POWERPC:
7894 outs() << " PPC";
7895 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7896 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7897 outs() << " ALL";
7898 break;
7899 default:
7900 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7901 break;
7902 }
7903 break;
7904 case MachO::CPU_TYPE_POWERPC64:
7905 outs() << " PPC64";
7906 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7907 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7908 outs() << " ALL";
7909 break;
7910 default:
7911 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7912 break;
7913 }
7914 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007915 default:
7916 outs() << format(" %7d", cputype);
7917 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7918 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007919 }
7920 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007921 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007922 } else {
7923 outs() << format(" 0x%02" PRIx32,
7924 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7925 }
7926 switch (filetype) {
7927 case MachO::MH_OBJECT:
7928 outs() << " OBJECT";
7929 break;
7930 case MachO::MH_EXECUTE:
7931 outs() << " EXECUTE";
7932 break;
7933 case MachO::MH_FVMLIB:
7934 outs() << " FVMLIB";
7935 break;
7936 case MachO::MH_CORE:
7937 outs() << " CORE";
7938 break;
7939 case MachO::MH_PRELOAD:
7940 outs() << " PRELOAD";
7941 break;
7942 case MachO::MH_DYLIB:
7943 outs() << " DYLIB";
7944 break;
7945 case MachO::MH_DYLIB_STUB:
7946 outs() << " DYLIB_STUB";
7947 break;
7948 case MachO::MH_DYLINKER:
7949 outs() << " DYLINKER";
7950 break;
7951 case MachO::MH_BUNDLE:
7952 outs() << " BUNDLE";
7953 break;
7954 case MachO::MH_DSYM:
7955 outs() << " DSYM";
7956 break;
7957 case MachO::MH_KEXT_BUNDLE:
7958 outs() << " KEXTBUNDLE";
7959 break;
7960 default:
7961 outs() << format(" %10u", filetype);
7962 break;
7963 }
7964 outs() << format(" %5u", ncmds);
7965 outs() << format(" %10u", sizeofcmds);
7966 uint32_t f = flags;
7967 if (f & MachO::MH_NOUNDEFS) {
7968 outs() << " NOUNDEFS";
7969 f &= ~MachO::MH_NOUNDEFS;
7970 }
7971 if (f & MachO::MH_INCRLINK) {
7972 outs() << " INCRLINK";
7973 f &= ~MachO::MH_INCRLINK;
7974 }
7975 if (f & MachO::MH_DYLDLINK) {
7976 outs() << " DYLDLINK";
7977 f &= ~MachO::MH_DYLDLINK;
7978 }
7979 if (f & MachO::MH_BINDATLOAD) {
7980 outs() << " BINDATLOAD";
7981 f &= ~MachO::MH_BINDATLOAD;
7982 }
7983 if (f & MachO::MH_PREBOUND) {
7984 outs() << " PREBOUND";
7985 f &= ~MachO::MH_PREBOUND;
7986 }
7987 if (f & MachO::MH_SPLIT_SEGS) {
7988 outs() << " SPLIT_SEGS";
7989 f &= ~MachO::MH_SPLIT_SEGS;
7990 }
7991 if (f & MachO::MH_LAZY_INIT) {
7992 outs() << " LAZY_INIT";
7993 f &= ~MachO::MH_LAZY_INIT;
7994 }
7995 if (f & MachO::MH_TWOLEVEL) {
7996 outs() << " TWOLEVEL";
7997 f &= ~MachO::MH_TWOLEVEL;
7998 }
7999 if (f & MachO::MH_FORCE_FLAT) {
8000 outs() << " FORCE_FLAT";
8001 f &= ~MachO::MH_FORCE_FLAT;
8002 }
8003 if (f & MachO::MH_NOMULTIDEFS) {
8004 outs() << " NOMULTIDEFS";
8005 f &= ~MachO::MH_NOMULTIDEFS;
8006 }
8007 if (f & MachO::MH_NOFIXPREBINDING) {
8008 outs() << " NOFIXPREBINDING";
8009 f &= ~MachO::MH_NOFIXPREBINDING;
8010 }
8011 if (f & MachO::MH_PREBINDABLE) {
8012 outs() << " PREBINDABLE";
8013 f &= ~MachO::MH_PREBINDABLE;
8014 }
8015 if (f & MachO::MH_ALLMODSBOUND) {
8016 outs() << " ALLMODSBOUND";
8017 f &= ~MachO::MH_ALLMODSBOUND;
8018 }
8019 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8020 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8021 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8022 }
8023 if (f & MachO::MH_CANONICAL) {
8024 outs() << " CANONICAL";
8025 f &= ~MachO::MH_CANONICAL;
8026 }
8027 if (f & MachO::MH_WEAK_DEFINES) {
8028 outs() << " WEAK_DEFINES";
8029 f &= ~MachO::MH_WEAK_DEFINES;
8030 }
8031 if (f & MachO::MH_BINDS_TO_WEAK) {
8032 outs() << " BINDS_TO_WEAK";
8033 f &= ~MachO::MH_BINDS_TO_WEAK;
8034 }
8035 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8036 outs() << " ALLOW_STACK_EXECUTION";
8037 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8038 }
8039 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8040 outs() << " DEAD_STRIPPABLE_DYLIB";
8041 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8042 }
8043 if (f & MachO::MH_PIE) {
8044 outs() << " PIE";
8045 f &= ~MachO::MH_PIE;
8046 }
8047 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8048 outs() << " NO_REEXPORTED_DYLIBS";
8049 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8050 }
8051 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8052 outs() << " MH_HAS_TLV_DESCRIPTORS";
8053 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8054 }
8055 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8056 outs() << " MH_NO_HEAP_EXECUTION";
8057 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8058 }
8059 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8060 outs() << " APP_EXTENSION_SAFE";
8061 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8062 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008063 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8064 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8065 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8066 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008067 if (f != 0 || flags == 0)
8068 outs() << format(" 0x%08" PRIx32, f);
8069 } else {
8070 outs() << format(" 0x%08" PRIx32, magic);
8071 outs() << format(" %7d", cputype);
8072 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8073 outs() << format(" 0x%02" PRIx32,
8074 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8075 outs() << format(" %10u", filetype);
8076 outs() << format(" %5u", ncmds);
8077 outs() << format(" %10u", sizeofcmds);
8078 outs() << format(" 0x%08" PRIx32, flags);
8079 }
8080 outs() << "\n";
8081}
8082
Kevin Enderby956366c2014-08-29 22:30:52 +00008083static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8084 StringRef SegName, uint64_t vmaddr,
8085 uint64_t vmsize, uint64_t fileoff,
8086 uint64_t filesize, uint32_t maxprot,
8087 uint32_t initprot, uint32_t nsects,
8088 uint32_t flags, uint32_t object_size,
8089 bool verbose) {
8090 uint64_t expected_cmdsize;
8091 if (cmd == MachO::LC_SEGMENT) {
8092 outs() << " cmd LC_SEGMENT\n";
8093 expected_cmdsize = nsects;
8094 expected_cmdsize *= sizeof(struct MachO::section);
8095 expected_cmdsize += sizeof(struct MachO::segment_command);
8096 } else {
8097 outs() << " cmd LC_SEGMENT_64\n";
8098 expected_cmdsize = nsects;
8099 expected_cmdsize *= sizeof(struct MachO::section_64);
8100 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8101 }
8102 outs() << " cmdsize " << cmdsize;
8103 if (cmdsize != expected_cmdsize)
8104 outs() << " Inconsistent size\n";
8105 else
8106 outs() << "\n";
8107 outs() << " segname " << SegName << "\n";
8108 if (cmd == MachO::LC_SEGMENT_64) {
8109 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8110 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8111 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008112 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8113 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008114 }
8115 outs() << " fileoff " << fileoff;
8116 if (fileoff > object_size)
8117 outs() << " (past end of file)\n";
8118 else
8119 outs() << "\n";
8120 outs() << " filesize " << filesize;
8121 if (fileoff + filesize > object_size)
8122 outs() << " (past end of file)\n";
8123 else
8124 outs() << "\n";
8125 if (verbose) {
8126 if ((maxprot &
8127 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8128 MachO::VM_PROT_EXECUTE)) != 0)
8129 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8130 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008131 outs() << " maxprot ";
8132 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8133 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8134 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008135 }
8136 if ((initprot &
8137 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8138 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008139 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008140 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008141 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008142 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8143 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8144 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008145 }
8146 } else {
8147 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8148 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8149 }
8150 outs() << " nsects " << nsects << "\n";
8151 if (verbose) {
8152 outs() << " flags";
8153 if (flags == 0)
8154 outs() << " (none)\n";
8155 else {
8156 if (flags & MachO::SG_HIGHVM) {
8157 outs() << " HIGHVM";
8158 flags &= ~MachO::SG_HIGHVM;
8159 }
8160 if (flags & MachO::SG_FVMLIB) {
8161 outs() << " FVMLIB";
8162 flags &= ~MachO::SG_FVMLIB;
8163 }
8164 if (flags & MachO::SG_NORELOC) {
8165 outs() << " NORELOC";
8166 flags &= ~MachO::SG_NORELOC;
8167 }
8168 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8169 outs() << " PROTECTED_VERSION_1";
8170 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8171 }
8172 if (flags)
8173 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8174 else
8175 outs() << "\n";
8176 }
8177 } else {
8178 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8179 }
8180}
8181
8182static void PrintSection(const char *sectname, const char *segname,
8183 uint64_t addr, uint64_t size, uint32_t offset,
8184 uint32_t align, uint32_t reloff, uint32_t nreloc,
8185 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8186 uint32_t cmd, const char *sg_segname,
8187 uint32_t filetype, uint32_t object_size,
8188 bool verbose) {
8189 outs() << "Section\n";
8190 outs() << " sectname " << format("%.16s\n", sectname);
8191 outs() << " segname " << format("%.16s", segname);
8192 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8193 outs() << " (does not match segment)\n";
8194 else
8195 outs() << "\n";
8196 if (cmd == MachO::LC_SEGMENT_64) {
8197 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8198 outs() << " size " << format("0x%016" PRIx64, size);
8199 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008200 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8201 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008202 }
8203 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8204 outs() << " (past end of file)\n";
8205 else
8206 outs() << "\n";
8207 outs() << " offset " << offset;
8208 if (offset > object_size)
8209 outs() << " (past end of file)\n";
8210 else
8211 outs() << "\n";
8212 uint32_t align_shifted = 1 << align;
8213 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8214 outs() << " reloff " << reloff;
8215 if (reloff > object_size)
8216 outs() << " (past end of file)\n";
8217 else
8218 outs() << "\n";
8219 outs() << " nreloc " << nreloc;
8220 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8221 outs() << " (past end of file)\n";
8222 else
8223 outs() << "\n";
8224 uint32_t section_type = flags & MachO::SECTION_TYPE;
8225 if (verbose) {
8226 outs() << " type";
8227 if (section_type == MachO::S_REGULAR)
8228 outs() << " S_REGULAR\n";
8229 else if (section_type == MachO::S_ZEROFILL)
8230 outs() << " S_ZEROFILL\n";
8231 else if (section_type == MachO::S_CSTRING_LITERALS)
8232 outs() << " S_CSTRING_LITERALS\n";
8233 else if (section_type == MachO::S_4BYTE_LITERALS)
8234 outs() << " S_4BYTE_LITERALS\n";
8235 else if (section_type == MachO::S_8BYTE_LITERALS)
8236 outs() << " S_8BYTE_LITERALS\n";
8237 else if (section_type == MachO::S_16BYTE_LITERALS)
8238 outs() << " S_16BYTE_LITERALS\n";
8239 else if (section_type == MachO::S_LITERAL_POINTERS)
8240 outs() << " S_LITERAL_POINTERS\n";
8241 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8242 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8243 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8244 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8245 else if (section_type == MachO::S_SYMBOL_STUBS)
8246 outs() << " S_SYMBOL_STUBS\n";
8247 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8248 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8249 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8250 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8251 else if (section_type == MachO::S_COALESCED)
8252 outs() << " S_COALESCED\n";
8253 else if (section_type == MachO::S_INTERPOSING)
8254 outs() << " S_INTERPOSING\n";
8255 else if (section_type == MachO::S_DTRACE_DOF)
8256 outs() << " S_DTRACE_DOF\n";
8257 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8258 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8259 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8260 outs() << " S_THREAD_LOCAL_REGULAR\n";
8261 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8262 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8263 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8264 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8265 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8266 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8267 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8268 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8269 else
8270 outs() << format("0x%08" PRIx32, section_type) << "\n";
8271 outs() << "attributes";
8272 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8273 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8274 outs() << " PURE_INSTRUCTIONS";
8275 if (section_attributes & MachO::S_ATTR_NO_TOC)
8276 outs() << " NO_TOC";
8277 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8278 outs() << " STRIP_STATIC_SYMS";
8279 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8280 outs() << " NO_DEAD_STRIP";
8281 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8282 outs() << " LIVE_SUPPORT";
8283 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8284 outs() << " SELF_MODIFYING_CODE";
8285 if (section_attributes & MachO::S_ATTR_DEBUG)
8286 outs() << " DEBUG";
8287 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8288 outs() << " SOME_INSTRUCTIONS";
8289 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8290 outs() << " EXT_RELOC";
8291 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8292 outs() << " LOC_RELOC";
8293 if (section_attributes == 0)
8294 outs() << " (none)";
8295 outs() << "\n";
8296 } else
8297 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8298 outs() << " reserved1 " << reserved1;
8299 if (section_type == MachO::S_SYMBOL_STUBS ||
8300 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8301 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8302 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8303 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8304 outs() << " (index into indirect symbol table)\n";
8305 else
8306 outs() << "\n";
8307 outs() << " reserved2 " << reserved2;
8308 if (section_type == MachO::S_SYMBOL_STUBS)
8309 outs() << " (size of stubs)\n";
8310 else
8311 outs() << "\n";
8312}
8313
David Majnemer73cc6ff2014-11-13 19:48:56 +00008314static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008315 uint32_t object_size) {
8316 outs() << " cmd LC_SYMTAB\n";
8317 outs() << " cmdsize " << st.cmdsize;
8318 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8319 outs() << " Incorrect size\n";
8320 else
8321 outs() << "\n";
8322 outs() << " symoff " << st.symoff;
8323 if (st.symoff > object_size)
8324 outs() << " (past end of file)\n";
8325 else
8326 outs() << "\n";
8327 outs() << " nsyms " << st.nsyms;
8328 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008329 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008330 big_size = st.nsyms;
8331 big_size *= sizeof(struct MachO::nlist_64);
8332 big_size += st.symoff;
8333 if (big_size > object_size)
8334 outs() << " (past end of file)\n";
8335 else
8336 outs() << "\n";
8337 } else {
8338 big_size = st.nsyms;
8339 big_size *= sizeof(struct MachO::nlist);
8340 big_size += st.symoff;
8341 if (big_size > object_size)
8342 outs() << " (past end of file)\n";
8343 else
8344 outs() << "\n";
8345 }
8346 outs() << " stroff " << st.stroff;
8347 if (st.stroff > object_size)
8348 outs() << " (past end of file)\n";
8349 else
8350 outs() << "\n";
8351 outs() << " strsize " << st.strsize;
8352 big_size = st.stroff;
8353 big_size += st.strsize;
8354 if (big_size > object_size)
8355 outs() << " (past end of file)\n";
8356 else
8357 outs() << "\n";
8358}
8359
8360static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8361 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008362 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008363 outs() << " cmd LC_DYSYMTAB\n";
8364 outs() << " cmdsize " << dyst.cmdsize;
8365 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8366 outs() << " Incorrect size\n";
8367 else
8368 outs() << "\n";
8369 outs() << " ilocalsym " << dyst.ilocalsym;
8370 if (dyst.ilocalsym > nsyms)
8371 outs() << " (greater than the number of symbols)\n";
8372 else
8373 outs() << "\n";
8374 outs() << " nlocalsym " << dyst.nlocalsym;
8375 uint64_t big_size;
8376 big_size = dyst.ilocalsym;
8377 big_size += dyst.nlocalsym;
8378 if (big_size > nsyms)
8379 outs() << " (past the end of the symbol table)\n";
8380 else
8381 outs() << "\n";
8382 outs() << " iextdefsym " << dyst.iextdefsym;
8383 if (dyst.iextdefsym > nsyms)
8384 outs() << " (greater than the number of symbols)\n";
8385 else
8386 outs() << "\n";
8387 outs() << " nextdefsym " << dyst.nextdefsym;
8388 big_size = dyst.iextdefsym;
8389 big_size += dyst.nextdefsym;
8390 if (big_size > nsyms)
8391 outs() << " (past the end of the symbol table)\n";
8392 else
8393 outs() << "\n";
8394 outs() << " iundefsym " << dyst.iundefsym;
8395 if (dyst.iundefsym > nsyms)
8396 outs() << " (greater than the number of symbols)\n";
8397 else
8398 outs() << "\n";
8399 outs() << " nundefsym " << dyst.nundefsym;
8400 big_size = dyst.iundefsym;
8401 big_size += dyst.nundefsym;
8402 if (big_size > nsyms)
8403 outs() << " (past the end of the symbol table)\n";
8404 else
8405 outs() << "\n";
8406 outs() << " tocoff " << dyst.tocoff;
8407 if (dyst.tocoff > object_size)
8408 outs() << " (past end of file)\n";
8409 else
8410 outs() << "\n";
8411 outs() << " ntoc " << dyst.ntoc;
8412 big_size = dyst.ntoc;
8413 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8414 big_size += dyst.tocoff;
8415 if (big_size > object_size)
8416 outs() << " (past end of file)\n";
8417 else
8418 outs() << "\n";
8419 outs() << " modtaboff " << dyst.modtaboff;
8420 if (dyst.modtaboff > object_size)
8421 outs() << " (past end of file)\n";
8422 else
8423 outs() << "\n";
8424 outs() << " nmodtab " << dyst.nmodtab;
8425 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008426 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008427 modtabend = dyst.nmodtab;
8428 modtabend *= sizeof(struct MachO::dylib_module_64);
8429 modtabend += dyst.modtaboff;
8430 } else {
8431 modtabend = dyst.nmodtab;
8432 modtabend *= sizeof(struct MachO::dylib_module);
8433 modtabend += dyst.modtaboff;
8434 }
8435 if (modtabend > object_size)
8436 outs() << " (past end of file)\n";
8437 else
8438 outs() << "\n";
8439 outs() << " extrefsymoff " << dyst.extrefsymoff;
8440 if (dyst.extrefsymoff > object_size)
8441 outs() << " (past end of file)\n";
8442 else
8443 outs() << "\n";
8444 outs() << " nextrefsyms " << dyst.nextrefsyms;
8445 big_size = dyst.nextrefsyms;
8446 big_size *= sizeof(struct MachO::dylib_reference);
8447 big_size += dyst.extrefsymoff;
8448 if (big_size > object_size)
8449 outs() << " (past end of file)\n";
8450 else
8451 outs() << "\n";
8452 outs() << " indirectsymoff " << dyst.indirectsymoff;
8453 if (dyst.indirectsymoff > object_size)
8454 outs() << " (past end of file)\n";
8455 else
8456 outs() << "\n";
8457 outs() << " nindirectsyms " << dyst.nindirectsyms;
8458 big_size = dyst.nindirectsyms;
8459 big_size *= sizeof(uint32_t);
8460 big_size += dyst.indirectsymoff;
8461 if (big_size > object_size)
8462 outs() << " (past end of file)\n";
8463 else
8464 outs() << "\n";
8465 outs() << " extreloff " << dyst.extreloff;
8466 if (dyst.extreloff > object_size)
8467 outs() << " (past end of file)\n";
8468 else
8469 outs() << "\n";
8470 outs() << " nextrel " << dyst.nextrel;
8471 big_size = dyst.nextrel;
8472 big_size *= sizeof(struct MachO::relocation_info);
8473 big_size += dyst.extreloff;
8474 if (big_size > object_size)
8475 outs() << " (past end of file)\n";
8476 else
8477 outs() << "\n";
8478 outs() << " locreloff " << dyst.locreloff;
8479 if (dyst.locreloff > object_size)
8480 outs() << " (past end of file)\n";
8481 else
8482 outs() << "\n";
8483 outs() << " nlocrel " << dyst.nlocrel;
8484 big_size = dyst.nlocrel;
8485 big_size *= sizeof(struct MachO::relocation_info);
8486 big_size += dyst.locreloff;
8487 if (big_size > object_size)
8488 outs() << " (past end of file)\n";
8489 else
8490 outs() << "\n";
8491}
8492
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008493static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8494 uint32_t object_size) {
8495 if (dc.cmd == MachO::LC_DYLD_INFO)
8496 outs() << " cmd LC_DYLD_INFO\n";
8497 else
8498 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8499 outs() << " cmdsize " << dc.cmdsize;
8500 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8501 outs() << " Incorrect size\n";
8502 else
8503 outs() << "\n";
8504 outs() << " rebase_off " << dc.rebase_off;
8505 if (dc.rebase_off > object_size)
8506 outs() << " (past end of file)\n";
8507 else
8508 outs() << "\n";
8509 outs() << " rebase_size " << dc.rebase_size;
8510 uint64_t big_size;
8511 big_size = dc.rebase_off;
8512 big_size += dc.rebase_size;
8513 if (big_size > object_size)
8514 outs() << " (past end of file)\n";
8515 else
8516 outs() << "\n";
8517 outs() << " bind_off " << dc.bind_off;
8518 if (dc.bind_off > object_size)
8519 outs() << " (past end of file)\n";
8520 else
8521 outs() << "\n";
8522 outs() << " bind_size " << dc.bind_size;
8523 big_size = dc.bind_off;
8524 big_size += dc.bind_size;
8525 if (big_size > object_size)
8526 outs() << " (past end of file)\n";
8527 else
8528 outs() << "\n";
8529 outs() << " weak_bind_off " << dc.weak_bind_off;
8530 if (dc.weak_bind_off > object_size)
8531 outs() << " (past end of file)\n";
8532 else
8533 outs() << "\n";
8534 outs() << " weak_bind_size " << dc.weak_bind_size;
8535 big_size = dc.weak_bind_off;
8536 big_size += dc.weak_bind_size;
8537 if (big_size > object_size)
8538 outs() << " (past end of file)\n";
8539 else
8540 outs() << "\n";
8541 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8542 if (dc.lazy_bind_off > object_size)
8543 outs() << " (past end of file)\n";
8544 else
8545 outs() << "\n";
8546 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8547 big_size = dc.lazy_bind_off;
8548 big_size += dc.lazy_bind_size;
8549 if (big_size > object_size)
8550 outs() << " (past end of file)\n";
8551 else
8552 outs() << "\n";
8553 outs() << " export_off " << dc.export_off;
8554 if (dc.export_off > object_size)
8555 outs() << " (past end of file)\n";
8556 else
8557 outs() << "\n";
8558 outs() << " export_size " << dc.export_size;
8559 big_size = dc.export_off;
8560 big_size += dc.export_size;
8561 if (big_size > object_size)
8562 outs() << " (past end of file)\n";
8563 else
8564 outs() << "\n";
8565}
8566
8567static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8568 const char *Ptr) {
8569 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8570 outs() << " cmd LC_ID_DYLINKER\n";
8571 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8572 outs() << " cmd LC_LOAD_DYLINKER\n";
8573 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8574 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8575 else
8576 outs() << " cmd ?(" << dyld.cmd << ")\n";
8577 outs() << " cmdsize " << dyld.cmdsize;
8578 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8579 outs() << " Incorrect size\n";
8580 else
8581 outs() << "\n";
8582 if (dyld.name >= dyld.cmdsize)
8583 outs() << " name ?(bad offset " << dyld.name << ")\n";
8584 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008585 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008586 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8587 }
8588}
8589
8590static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8591 outs() << " cmd LC_UUID\n";
8592 outs() << " cmdsize " << uuid.cmdsize;
8593 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8594 outs() << " Incorrect size\n";
8595 else
8596 outs() << "\n";
8597 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008598 for (int i = 0; i < 16; ++i) {
8599 outs() << format("%02" PRIX32, uuid.uuid[i]);
8600 if (i == 3 || i == 5 || i == 7 || i == 9)
8601 outs() << "-";
8602 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008603 outs() << "\n";
8604}
8605
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008606static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008607 outs() << " cmd LC_RPATH\n";
8608 outs() << " cmdsize " << rpath.cmdsize;
8609 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8610 outs() << " Incorrect size\n";
8611 else
8612 outs() << "\n";
8613 if (rpath.path >= rpath.cmdsize)
8614 outs() << " path ?(bad offset " << rpath.path << ")\n";
8615 else {
8616 const char *P = (const char *)(Ptr) + rpath.path;
8617 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8618 }
8619}
8620
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008621static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008622 StringRef LoadCmdName;
8623 switch (vd.cmd) {
8624 case MachO::LC_VERSION_MIN_MACOSX:
8625 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8626 break;
8627 case MachO::LC_VERSION_MIN_IPHONEOS:
8628 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8629 break;
8630 case MachO::LC_VERSION_MIN_TVOS:
8631 LoadCmdName = "LC_VERSION_MIN_TVOS";
8632 break;
8633 case MachO::LC_VERSION_MIN_WATCHOS:
8634 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8635 break;
8636 default:
8637 llvm_unreachable("Unknown version min load command");
8638 }
8639
8640 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008641 outs() << " cmdsize " << vd.cmdsize;
8642 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8643 outs() << " Incorrect size\n";
8644 else
8645 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008646 outs() << " version "
8647 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8648 << MachOObjectFile::getVersionMinMinor(vd, false);
8649 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8650 if (Update != 0)
8651 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008652 outs() << "\n";
8653 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008654 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008655 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008656 outs() << " sdk "
8657 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8658 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008659 }
Davide Italiano56baef32015-08-26 12:26:11 +00008660 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8661 if (Update != 0)
8662 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008663 outs() << "\n";
8664}
8665
Kevin Enderbya4579c42017-01-19 17:36:31 +00008666static void PrintNoteLoadCommand(MachO::note_command Nt) {
8667 outs() << " cmd LC_NOTE\n";
8668 outs() << " cmdsize " << Nt.cmdsize;
8669 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8670 outs() << " Incorrect size\n";
8671 else
8672 outs() << "\n";
8673 const char *d = Nt.data_owner;
8674 outs() << "data_owner " << format("%.16s\n", d);
8675 outs() << " offset " << Nt.offset << "\n";
8676 outs() << " size " << Nt.size << "\n";
8677}
8678
Steven Wu5b54a422017-01-23 20:07:55 +00008679static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8680 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8681 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8682 << "\n";
8683}
8684
8685static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8686 MachO::build_version_command bd) {
8687 outs() << " cmd LC_BUILD_VERSION\n";
8688 outs() << " cmdsize " << bd.cmdsize;
8689 if (bd.cmdsize !=
8690 sizeof(struct MachO::build_version_command) +
8691 bd.ntools * sizeof(struct MachO::build_tool_version))
8692 outs() << " Incorrect size\n";
8693 else
8694 outs() << "\n";
8695 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8696 << "\n";
8697 if (bd.sdk)
8698 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8699 << "\n";
8700 else
8701 outs() << " sdk n/a\n";
8702 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8703 << "\n";
8704 outs() << " ntools " << bd.ntools << "\n";
8705 for (unsigned i = 0; i < bd.ntools; ++i) {
8706 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8707 PrintBuildToolVersion(bv);
8708 }
8709}
8710
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008711static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8712 outs() << " cmd LC_SOURCE_VERSION\n";
8713 outs() << " cmdsize " << sd.cmdsize;
8714 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8715 outs() << " Incorrect size\n";
8716 else
8717 outs() << "\n";
8718 uint64_t a = (sd.version >> 40) & 0xffffff;
8719 uint64_t b = (sd.version >> 30) & 0x3ff;
8720 uint64_t c = (sd.version >> 20) & 0x3ff;
8721 uint64_t d = (sd.version >> 10) & 0x3ff;
8722 uint64_t e = sd.version & 0x3ff;
8723 outs() << " version " << a << "." << b;
8724 if (e != 0)
8725 outs() << "." << c << "." << d << "." << e;
8726 else if (d != 0)
8727 outs() << "." << c << "." << d;
8728 else if (c != 0)
8729 outs() << "." << c;
8730 outs() << "\n";
8731}
8732
8733static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8734 outs() << " cmd LC_MAIN\n";
8735 outs() << " cmdsize " << ep.cmdsize;
8736 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8737 outs() << " Incorrect size\n";
8738 else
8739 outs() << "\n";
8740 outs() << " entryoff " << ep.entryoff << "\n";
8741 outs() << " stacksize " << ep.stacksize << "\n";
8742}
8743
Kevin Enderby0804f4672014-12-16 23:25:52 +00008744static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8745 uint32_t object_size) {
8746 outs() << " cmd LC_ENCRYPTION_INFO\n";
8747 outs() << " cmdsize " << ec.cmdsize;
8748 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8749 outs() << " Incorrect size\n";
8750 else
8751 outs() << "\n";
8752 outs() << " cryptoff " << ec.cryptoff;
8753 if (ec.cryptoff > object_size)
8754 outs() << " (past end of file)\n";
8755 else
8756 outs() << "\n";
8757 outs() << " cryptsize " << ec.cryptsize;
8758 if (ec.cryptsize > object_size)
8759 outs() << " (past end of file)\n";
8760 else
8761 outs() << "\n";
8762 outs() << " cryptid " << ec.cryptid << "\n";
8763}
8764
Kevin Enderby57538292014-12-17 01:01:30 +00008765static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008766 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008767 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8768 outs() << " cmdsize " << ec.cmdsize;
8769 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8770 outs() << " Incorrect size\n";
8771 else
8772 outs() << "\n";
8773 outs() << " cryptoff " << ec.cryptoff;
8774 if (ec.cryptoff > object_size)
8775 outs() << " (past end of file)\n";
8776 else
8777 outs() << "\n";
8778 outs() << " cryptsize " << ec.cryptsize;
8779 if (ec.cryptsize > object_size)
8780 outs() << " (past end of file)\n";
8781 else
8782 outs() << "\n";
8783 outs() << " cryptid " << ec.cryptid << "\n";
8784 outs() << " pad " << ec.pad << "\n";
8785}
8786
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008787static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8788 const char *Ptr) {
8789 outs() << " cmd LC_LINKER_OPTION\n";
8790 outs() << " cmdsize " << lo.cmdsize;
8791 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8792 outs() << " Incorrect size\n";
8793 else
8794 outs() << "\n";
8795 outs() << " count " << lo.count << "\n";
8796 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8797 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8798 uint32_t i = 0;
8799 while (left > 0) {
8800 while (*string == '\0' && left > 0) {
8801 string++;
8802 left--;
8803 }
8804 if (left > 0) {
8805 i++;
8806 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008807 uint32_t NullPos = StringRef(string, left).find('\0');
8808 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008809 string += len;
8810 left -= len;
8811 }
8812 }
8813 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008814 outs() << " count " << lo.count << " does not match number of strings "
8815 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008816}
8817
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008818static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8819 const char *Ptr) {
8820 outs() << " cmd LC_SUB_FRAMEWORK\n";
8821 outs() << " cmdsize " << sub.cmdsize;
8822 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8823 outs() << " Incorrect size\n";
8824 else
8825 outs() << "\n";
8826 if (sub.umbrella < sub.cmdsize) {
8827 const char *P = Ptr + sub.umbrella;
8828 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8829 } else {
8830 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8831 }
8832}
8833
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008834static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8835 const char *Ptr) {
8836 outs() << " cmd LC_SUB_UMBRELLA\n";
8837 outs() << " cmdsize " << sub.cmdsize;
8838 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8839 outs() << " Incorrect size\n";
8840 else
8841 outs() << "\n";
8842 if (sub.sub_umbrella < sub.cmdsize) {
8843 const char *P = Ptr + sub.sub_umbrella;
8844 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8845 } else {
8846 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8847 }
8848}
8849
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008850static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008851 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008852 outs() << " cmd LC_SUB_LIBRARY\n";
8853 outs() << " cmdsize " << sub.cmdsize;
8854 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8855 outs() << " Incorrect size\n";
8856 else
8857 outs() << "\n";
8858 if (sub.sub_library < sub.cmdsize) {
8859 const char *P = Ptr + sub.sub_library;
8860 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8861 } else {
8862 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8863 }
8864}
8865
Kevin Enderby186eac32014-12-19 21:06:24 +00008866static void PrintSubClientCommand(MachO::sub_client_command sub,
8867 const char *Ptr) {
8868 outs() << " cmd LC_SUB_CLIENT\n";
8869 outs() << " cmdsize " << sub.cmdsize;
8870 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8871 outs() << " Incorrect size\n";
8872 else
8873 outs() << "\n";
8874 if (sub.client < sub.cmdsize) {
8875 const char *P = Ptr + sub.client;
8876 outs() << " client " << P << " (offset " << sub.client << ")\n";
8877 } else {
8878 outs() << " client ?(bad offset " << sub.client << ")\n";
8879 }
8880}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008881
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008882static void PrintRoutinesCommand(MachO::routines_command r) {
8883 outs() << " cmd LC_ROUTINES\n";
8884 outs() << " cmdsize " << r.cmdsize;
8885 if (r.cmdsize != sizeof(struct MachO::routines_command))
8886 outs() << " Incorrect size\n";
8887 else
8888 outs() << "\n";
8889 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8890 outs() << " init_module " << r.init_module << "\n";
8891 outs() << " reserved1 " << r.reserved1 << "\n";
8892 outs() << " reserved2 " << r.reserved2 << "\n";
8893 outs() << " reserved3 " << r.reserved3 << "\n";
8894 outs() << " reserved4 " << r.reserved4 << "\n";
8895 outs() << " reserved5 " << r.reserved5 << "\n";
8896 outs() << " reserved6 " << r.reserved6 << "\n";
8897}
8898
8899static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8900 outs() << " cmd LC_ROUTINES_64\n";
8901 outs() << " cmdsize " << r.cmdsize;
8902 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8903 outs() << " Incorrect size\n";
8904 else
8905 outs() << "\n";
8906 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8907 outs() << " init_module " << r.init_module << "\n";
8908 outs() << " reserved1 " << r.reserved1 << "\n";
8909 outs() << " reserved2 " << r.reserved2 << "\n";
8910 outs() << " reserved3 " << r.reserved3 << "\n";
8911 outs() << " reserved4 " << r.reserved4 << "\n";
8912 outs() << " reserved5 " << r.reserved5 << "\n";
8913 outs() << " reserved6 " << r.reserved6 << "\n";
8914}
8915
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008916static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8917 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8918 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8919 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8920 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8921 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8922 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8923 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8924 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8925 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8926 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8927 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8928 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8929 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8930 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8931 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8932 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8933}
8934
Kevin Enderby48ef5342014-12-23 22:56:39 +00008935static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8936 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8937 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8938 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8939 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8940 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8941 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8942 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8943 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8944 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8945 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8946 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8947 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8948 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8949 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8950 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8951 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8952 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8953 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8954 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8955 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8956 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8957}
8958
Kevin Enderby227df342014-12-23 23:43:59 +00008959static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008960 uint32_t f;
8961 outs() << "\t mmst_reg ";
8962 for (f = 0; f < 10; f++)
8963 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8964 outs() << "\n";
8965 outs() << "\t mmst_rsrv ";
8966 for (f = 0; f < 6; f++)
8967 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8968 outs() << "\n";
8969}
8970
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008971static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008972 uint32_t f;
8973 outs() << "\t xmm_reg ";
8974 for (f = 0; f < 16; f++)
8975 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8976 outs() << "\n";
8977}
8978
8979static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8980 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8981 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8982 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8983 outs() << " denorm " << fpu.fpu_fcw.denorm;
8984 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8985 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8986 outs() << " undfl " << fpu.fpu_fcw.undfl;
8987 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8988 outs() << "\t\t pc ";
8989 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8990 outs() << "FP_PREC_24B ";
8991 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8992 outs() << "FP_PREC_53B ";
8993 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8994 outs() << "FP_PREC_64B ";
8995 else
8996 outs() << fpu.fpu_fcw.pc << " ";
8997 outs() << "rc ";
8998 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8999 outs() << "FP_RND_NEAR ";
9000 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9001 outs() << "FP_RND_DOWN ";
9002 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9003 outs() << "FP_RND_UP ";
9004 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009005 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009006 outs() << "\n";
9007 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9008 outs() << " denorm " << fpu.fpu_fsw.denorm;
9009 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9010 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9011 outs() << " undfl " << fpu.fpu_fsw.undfl;
9012 outs() << " precis " << fpu.fpu_fsw.precis;
9013 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9014 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9015 outs() << " c0 " << fpu.fpu_fsw.c0;
9016 outs() << " c1 " << fpu.fpu_fsw.c1;
9017 outs() << " c2 " << fpu.fpu_fsw.c2;
9018 outs() << " tos " << fpu.fpu_fsw.tos;
9019 outs() << " c3 " << fpu.fpu_fsw.c3;
9020 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9021 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9022 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9023 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9024 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9025 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9026 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9027 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9028 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9029 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9030 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9031 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9032 outs() << "\n";
9033 outs() << "\t fpu_stmm0:\n";
9034 Print_mmst_reg(fpu.fpu_stmm0);
9035 outs() << "\t fpu_stmm1:\n";
9036 Print_mmst_reg(fpu.fpu_stmm1);
9037 outs() << "\t fpu_stmm2:\n";
9038 Print_mmst_reg(fpu.fpu_stmm2);
9039 outs() << "\t fpu_stmm3:\n";
9040 Print_mmst_reg(fpu.fpu_stmm3);
9041 outs() << "\t fpu_stmm4:\n";
9042 Print_mmst_reg(fpu.fpu_stmm4);
9043 outs() << "\t fpu_stmm5:\n";
9044 Print_mmst_reg(fpu.fpu_stmm5);
9045 outs() << "\t fpu_stmm6:\n";
9046 Print_mmst_reg(fpu.fpu_stmm6);
9047 outs() << "\t fpu_stmm7:\n";
9048 Print_mmst_reg(fpu.fpu_stmm7);
9049 outs() << "\t fpu_xmm0:\n";
9050 Print_xmm_reg(fpu.fpu_xmm0);
9051 outs() << "\t fpu_xmm1:\n";
9052 Print_xmm_reg(fpu.fpu_xmm1);
9053 outs() << "\t fpu_xmm2:\n";
9054 Print_xmm_reg(fpu.fpu_xmm2);
9055 outs() << "\t fpu_xmm3:\n";
9056 Print_xmm_reg(fpu.fpu_xmm3);
9057 outs() << "\t fpu_xmm4:\n";
9058 Print_xmm_reg(fpu.fpu_xmm4);
9059 outs() << "\t fpu_xmm5:\n";
9060 Print_xmm_reg(fpu.fpu_xmm5);
9061 outs() << "\t fpu_xmm6:\n";
9062 Print_xmm_reg(fpu.fpu_xmm6);
9063 outs() << "\t fpu_xmm7:\n";
9064 Print_xmm_reg(fpu.fpu_xmm7);
9065 outs() << "\t fpu_xmm8:\n";
9066 Print_xmm_reg(fpu.fpu_xmm8);
9067 outs() << "\t fpu_xmm9:\n";
9068 Print_xmm_reg(fpu.fpu_xmm9);
9069 outs() << "\t fpu_xmm10:\n";
9070 Print_xmm_reg(fpu.fpu_xmm10);
9071 outs() << "\t fpu_xmm11:\n";
9072 Print_xmm_reg(fpu.fpu_xmm11);
9073 outs() << "\t fpu_xmm12:\n";
9074 Print_xmm_reg(fpu.fpu_xmm12);
9075 outs() << "\t fpu_xmm13:\n";
9076 Print_xmm_reg(fpu.fpu_xmm13);
9077 outs() << "\t fpu_xmm14:\n";
9078 Print_xmm_reg(fpu.fpu_xmm14);
9079 outs() << "\t fpu_xmm15:\n";
9080 Print_xmm_reg(fpu.fpu_xmm15);
9081 outs() << "\t fpu_rsrv4:\n";
9082 for (uint32_t f = 0; f < 6; f++) {
9083 outs() << "\t ";
9084 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009085 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009086 outs() << "\n";
9087 }
9088 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9089 outs() << "\n";
9090}
9091
9092static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9093 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9094 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9095 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9096}
9097
Kevin Enderby41c9c002016-10-21 18:22:35 +00009098static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9099 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9100 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9101 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9102 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9103 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9104 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9105 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9106 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9107 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9108 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9109 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9110 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9111 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9112 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9113 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9114 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9115 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9116}
9117
Kevin Enderby7747cb52016-11-03 20:51:28 +00009118static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9119 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9120 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9121 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9122 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9123 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9124 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9125 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9126 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9127 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9128 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9129 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9130 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9131 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9132 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9133 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9134 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9135 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9136 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9137 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9138 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9139 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9140 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9141 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9142 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9143 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9144 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9145 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9146 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9147 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9148 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9149 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9150 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9151 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9152 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9153}
9154
Kevin Enderby48ef5342014-12-23 22:56:39 +00009155static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9156 bool isLittleEndian, uint32_t cputype) {
9157 if (t.cmd == MachO::LC_THREAD)
9158 outs() << " cmd LC_THREAD\n";
9159 else if (t.cmd == MachO::LC_UNIXTHREAD)
9160 outs() << " cmd LC_UNIXTHREAD\n";
9161 else
9162 outs() << " cmd " << t.cmd << " (unknown)\n";
9163 outs() << " cmdsize " << t.cmdsize;
9164 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9165 outs() << " Incorrect size\n";
9166 else
9167 outs() << "\n";
9168
9169 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9170 const char *end = Ptr + t.cmdsize;
9171 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009172 if (cputype == MachO::CPU_TYPE_I386) {
9173 while (begin < end) {
9174 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9175 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9176 begin += sizeof(uint32_t);
9177 } else {
9178 flavor = 0;
9179 begin = end;
9180 }
9181 if (isLittleEndian != sys::IsLittleEndianHost)
9182 sys::swapByteOrder(flavor);
9183 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9184 memcpy((char *)&count, begin, sizeof(uint32_t));
9185 begin += sizeof(uint32_t);
9186 } else {
9187 count = 0;
9188 begin = end;
9189 }
9190 if (isLittleEndian != sys::IsLittleEndianHost)
9191 sys::swapByteOrder(count);
9192 if (flavor == MachO::x86_THREAD_STATE32) {
9193 outs() << " flavor i386_THREAD_STATE\n";
9194 if (count == MachO::x86_THREAD_STATE32_COUNT)
9195 outs() << " count i386_THREAD_STATE_COUNT\n";
9196 else
9197 outs() << " count " << count
9198 << " (not x86_THREAD_STATE32_COUNT)\n";
9199 MachO::x86_thread_state32_t cpu32;
9200 left = end - begin;
9201 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9202 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9203 begin += sizeof(MachO::x86_thread_state32_t);
9204 } else {
9205 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9206 memcpy(&cpu32, begin, left);
9207 begin += left;
9208 }
9209 if (isLittleEndian != sys::IsLittleEndianHost)
9210 swapStruct(cpu32);
9211 Print_x86_thread_state32_t(cpu32);
9212 } else if (flavor == MachO::x86_THREAD_STATE) {
9213 outs() << " flavor x86_THREAD_STATE\n";
9214 if (count == MachO::x86_THREAD_STATE_COUNT)
9215 outs() << " count x86_THREAD_STATE_COUNT\n";
9216 else
9217 outs() << " count " << count
9218 << " (not x86_THREAD_STATE_COUNT)\n";
9219 struct MachO::x86_thread_state_t ts;
9220 left = end - begin;
9221 if (left >= sizeof(MachO::x86_thread_state_t)) {
9222 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9223 begin += sizeof(MachO::x86_thread_state_t);
9224 } else {
9225 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9226 memcpy(&ts, begin, left);
9227 begin += left;
9228 }
9229 if (isLittleEndian != sys::IsLittleEndianHost)
9230 swapStruct(ts);
9231 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9232 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9233 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9234 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9235 else
9236 outs() << "tsh.count " << ts.tsh.count
9237 << " (not x86_THREAD_STATE32_COUNT\n";
9238 Print_x86_thread_state32_t(ts.uts.ts32);
9239 } else {
9240 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9241 << ts.tsh.count << "\n";
9242 }
9243 } else {
9244 outs() << " flavor " << flavor << " (unknown)\n";
9245 outs() << " count " << count << "\n";
9246 outs() << " state (unknown)\n";
9247 begin += count * sizeof(uint32_t);
9248 }
9249 }
9250 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009251 while (begin < end) {
9252 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9253 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9254 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009255 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009256 flavor = 0;
9257 begin = end;
9258 }
9259 if (isLittleEndian != sys::IsLittleEndianHost)
9260 sys::swapByteOrder(flavor);
9261 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9262 memcpy((char *)&count, begin, sizeof(uint32_t));
9263 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009264 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009265 count = 0;
9266 begin = end;
9267 }
9268 if (isLittleEndian != sys::IsLittleEndianHost)
9269 sys::swapByteOrder(count);
9270 if (flavor == MachO::x86_THREAD_STATE64) {
9271 outs() << " flavor x86_THREAD_STATE64\n";
9272 if (count == MachO::x86_THREAD_STATE64_COUNT)
9273 outs() << " count x86_THREAD_STATE64_COUNT\n";
9274 else
9275 outs() << " count " << count
9276 << " (not x86_THREAD_STATE64_COUNT)\n";
9277 MachO::x86_thread_state64_t cpu64;
9278 left = end - begin;
9279 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9280 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9281 begin += sizeof(MachO::x86_thread_state64_t);
9282 } else {
9283 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9284 memcpy(&cpu64, begin, left);
9285 begin += left;
9286 }
9287 if (isLittleEndian != sys::IsLittleEndianHost)
9288 swapStruct(cpu64);
9289 Print_x86_thread_state64_t(cpu64);
9290 } else if (flavor == MachO::x86_THREAD_STATE) {
9291 outs() << " flavor x86_THREAD_STATE\n";
9292 if (count == MachO::x86_THREAD_STATE_COUNT)
9293 outs() << " count x86_THREAD_STATE_COUNT\n";
9294 else
9295 outs() << " count " << count
9296 << " (not x86_THREAD_STATE_COUNT)\n";
9297 struct MachO::x86_thread_state_t ts;
9298 left = end - begin;
9299 if (left >= sizeof(MachO::x86_thread_state_t)) {
9300 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9301 begin += sizeof(MachO::x86_thread_state_t);
9302 } else {
9303 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9304 memcpy(&ts, begin, left);
9305 begin += left;
9306 }
9307 if (isLittleEndian != sys::IsLittleEndianHost)
9308 swapStruct(ts);
9309 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9310 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9311 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9312 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9313 else
9314 outs() << "tsh.count " << ts.tsh.count
9315 << " (not x86_THREAD_STATE64_COUNT\n";
9316 Print_x86_thread_state64_t(ts.uts.ts64);
9317 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009318 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9319 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009320 }
9321 } else if (flavor == MachO::x86_FLOAT_STATE) {
9322 outs() << " flavor x86_FLOAT_STATE\n";
9323 if (count == MachO::x86_FLOAT_STATE_COUNT)
9324 outs() << " count x86_FLOAT_STATE_COUNT\n";
9325 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009326 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009327 struct MachO::x86_float_state_t fs;
9328 left = end - begin;
9329 if (left >= sizeof(MachO::x86_float_state_t)) {
9330 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9331 begin += sizeof(MachO::x86_float_state_t);
9332 } else {
9333 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9334 memcpy(&fs, begin, left);
9335 begin += left;
9336 }
9337 if (isLittleEndian != sys::IsLittleEndianHost)
9338 swapStruct(fs);
9339 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9340 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009341 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009342 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9343 else
9344 outs() << "fsh.count " << fs.fsh.count
9345 << " (not x86_FLOAT_STATE64_COUNT\n";
9346 Print_x86_float_state_t(fs.ufs.fs64);
9347 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009348 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9349 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009350 }
9351 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9352 outs() << " flavor x86_EXCEPTION_STATE\n";
9353 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9354 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9355 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009356 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009357 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9358 struct MachO::x86_exception_state_t es;
9359 left = end - begin;
9360 if (left >= sizeof(MachO::x86_exception_state_t)) {
9361 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9362 begin += sizeof(MachO::x86_exception_state_t);
9363 } else {
9364 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9365 memcpy(&es, begin, left);
9366 begin += left;
9367 }
9368 if (isLittleEndian != sys::IsLittleEndianHost)
9369 swapStruct(es);
9370 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9371 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009372 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009373 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9374 else
9375 outs() << "\t esh.count " << es.esh.count
9376 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9377 Print_x86_exception_state_t(es.ues.es64);
9378 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009379 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9380 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009381 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009382 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9383 outs() << " flavor x86_EXCEPTION_STATE64\n";
9384 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9385 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9386 else
9387 outs() << " count " << count
9388 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9389 struct MachO::x86_exception_state64_t es64;
9390 left = end - begin;
9391 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9392 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9393 begin += sizeof(MachO::x86_exception_state64_t);
9394 } else {
9395 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9396 memcpy(&es64, begin, left);
9397 begin += left;
9398 }
9399 if (isLittleEndian != sys::IsLittleEndianHost)
9400 swapStruct(es64);
9401 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009402 } else {
9403 outs() << " flavor " << flavor << " (unknown)\n";
9404 outs() << " count " << count << "\n";
9405 outs() << " state (unknown)\n";
9406 begin += count * sizeof(uint32_t);
9407 }
9408 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009409 } else if (cputype == MachO::CPU_TYPE_ARM) {
9410 while (begin < end) {
9411 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9412 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9413 begin += sizeof(uint32_t);
9414 } else {
9415 flavor = 0;
9416 begin = end;
9417 }
9418 if (isLittleEndian != sys::IsLittleEndianHost)
9419 sys::swapByteOrder(flavor);
9420 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9421 memcpy((char *)&count, begin, sizeof(uint32_t));
9422 begin += sizeof(uint32_t);
9423 } else {
9424 count = 0;
9425 begin = end;
9426 }
9427 if (isLittleEndian != sys::IsLittleEndianHost)
9428 sys::swapByteOrder(count);
9429 if (flavor == MachO::ARM_THREAD_STATE) {
9430 outs() << " flavor ARM_THREAD_STATE\n";
9431 if (count == MachO::ARM_THREAD_STATE_COUNT)
9432 outs() << " count ARM_THREAD_STATE_COUNT\n";
9433 else
9434 outs() << " count " << count
9435 << " (not ARM_THREAD_STATE_COUNT)\n";
9436 MachO::arm_thread_state32_t cpu32;
9437 left = end - begin;
9438 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9439 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9440 begin += sizeof(MachO::arm_thread_state32_t);
9441 } else {
9442 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9443 memcpy(&cpu32, begin, left);
9444 begin += left;
9445 }
9446 if (isLittleEndian != sys::IsLittleEndianHost)
9447 swapStruct(cpu32);
9448 Print_arm_thread_state32_t(cpu32);
9449 } else {
9450 outs() << " flavor " << flavor << " (unknown)\n";
9451 outs() << " count " << count << "\n";
9452 outs() << " state (unknown)\n";
9453 begin += count * sizeof(uint32_t);
9454 }
9455 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009456 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9457 while (begin < end) {
9458 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9459 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9460 begin += sizeof(uint32_t);
9461 } else {
9462 flavor = 0;
9463 begin = end;
9464 }
9465 if (isLittleEndian != sys::IsLittleEndianHost)
9466 sys::swapByteOrder(flavor);
9467 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9468 memcpy((char *)&count, begin, sizeof(uint32_t));
9469 begin += sizeof(uint32_t);
9470 } else {
9471 count = 0;
9472 begin = end;
9473 }
9474 if (isLittleEndian != sys::IsLittleEndianHost)
9475 sys::swapByteOrder(count);
9476 if (flavor == MachO::ARM_THREAD_STATE64) {
9477 outs() << " flavor ARM_THREAD_STATE64\n";
9478 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9479 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9480 else
9481 outs() << " count " << count
9482 << " (not ARM_THREAD_STATE64_COUNT)\n";
9483 MachO::arm_thread_state64_t cpu64;
9484 left = end - begin;
9485 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9486 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9487 begin += sizeof(MachO::arm_thread_state64_t);
9488 } else {
9489 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9490 memcpy(&cpu64, begin, left);
9491 begin += left;
9492 }
9493 if (isLittleEndian != sys::IsLittleEndianHost)
9494 swapStruct(cpu64);
9495 Print_arm_thread_state64_t(cpu64);
9496 } else {
9497 outs() << " flavor " << flavor << " (unknown)\n";
9498 outs() << " count " << count << "\n";
9499 outs() << " state (unknown)\n";
9500 begin += count * sizeof(uint32_t);
9501 }
9502 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009503 } else {
9504 while (begin < end) {
9505 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9506 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9507 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009508 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009509 flavor = 0;
9510 begin = end;
9511 }
9512 if (isLittleEndian != sys::IsLittleEndianHost)
9513 sys::swapByteOrder(flavor);
9514 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9515 memcpy((char *)&count, begin, sizeof(uint32_t));
9516 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009517 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009518 count = 0;
9519 begin = end;
9520 }
9521 if (isLittleEndian != sys::IsLittleEndianHost)
9522 sys::swapByteOrder(count);
9523 outs() << " flavor " << flavor << "\n";
9524 outs() << " count " << count << "\n";
9525 outs() << " state (Unknown cputype/cpusubtype)\n";
9526 begin += count * sizeof(uint32_t);
9527 }
9528 }
9529}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009530
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009531static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9532 if (dl.cmd == MachO::LC_ID_DYLIB)
9533 outs() << " cmd LC_ID_DYLIB\n";
9534 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9535 outs() << " cmd LC_LOAD_DYLIB\n";
9536 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9537 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9538 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9539 outs() << " cmd LC_REEXPORT_DYLIB\n";
9540 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9541 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9542 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9543 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9544 else
9545 outs() << " cmd " << dl.cmd << " (unknown)\n";
9546 outs() << " cmdsize " << dl.cmdsize;
9547 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9548 outs() << " Incorrect size\n";
9549 else
9550 outs() << "\n";
9551 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009552 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009553 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9554 } else {
9555 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9556 }
9557 outs() << " time stamp " << dl.dylib.timestamp << " ";
9558 time_t t = dl.dylib.timestamp;
9559 outs() << ctime(&t);
9560 outs() << " current version ";
9561 if (dl.dylib.current_version == 0xffffffff)
9562 outs() << "n/a\n";
9563 else
9564 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9565 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9566 << (dl.dylib.current_version & 0xff) << "\n";
9567 outs() << "compatibility version ";
9568 if (dl.dylib.compatibility_version == 0xffffffff)
9569 outs() << "n/a\n";
9570 else
9571 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9572 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9573 << (dl.dylib.compatibility_version & 0xff) << "\n";
9574}
9575
9576static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9577 uint32_t object_size) {
9578 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009579 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009580 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9581 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9582 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9583 outs() << " cmd LC_FUNCTION_STARTS\n";
9584 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9585 outs() << " cmd LC_DATA_IN_CODE\n";
9586 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9587 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9588 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9589 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9590 else
9591 outs() << " cmd " << ld.cmd << " (?)\n";
9592 outs() << " cmdsize " << ld.cmdsize;
9593 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9594 outs() << " Incorrect size\n";
9595 else
9596 outs() << "\n";
9597 outs() << " dataoff " << ld.dataoff;
9598 if (ld.dataoff > object_size)
9599 outs() << " (past end of file)\n";
9600 else
9601 outs() << "\n";
9602 outs() << " datasize " << ld.datasize;
9603 uint64_t big_size = ld.dataoff;
9604 big_size += ld.datasize;
9605 if (big_size > object_size)
9606 outs() << " (past end of file)\n";
9607 else
9608 outs() << "\n";
9609}
9610
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009611static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9612 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009613 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009614 unsigned Index = 0;
9615 for (const auto &Command : Obj->load_commands()) {
9616 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009617 if (Command.C.cmd == MachO::LC_SEGMENT) {
9618 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9619 const char *sg_segname = SLC.segname;
9620 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9621 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9622 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9623 verbose);
9624 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009625 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009626 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9627 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9628 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9629 }
9630 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9631 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9632 const char *sg_segname = SLC_64.segname;
9633 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9634 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9635 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9636 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9637 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9638 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9639 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9640 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9641 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9642 sg_segname, filetype, Buf.size(), verbose);
9643 }
9644 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9645 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009646 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009647 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9648 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9649 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009650 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9651 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009652 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9653 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9654 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9655 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9656 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9657 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9658 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9659 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9660 PrintDyldLoadCommand(Dyld, Command.Ptr);
9661 } else if (Command.C.cmd == MachO::LC_UUID) {
9662 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9663 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009664 } else if (Command.C.cmd == MachO::LC_RPATH) {
9665 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9666 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009667 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009668 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9669 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9670 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009671 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9672 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009673 } else if (Command.C.cmd == MachO::LC_NOTE) {
9674 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9675 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009676 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9677 MachO::build_version_command Bv =
9678 Obj->getBuildVersionLoadCommand(Command);
9679 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009680 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9681 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9682 PrintSourceVersionCommand(Sd);
9683 } else if (Command.C.cmd == MachO::LC_MAIN) {
9684 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9685 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009686 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009687 MachO::encryption_info_command Ei =
9688 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009689 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009690 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009691 MachO::encryption_info_command_64 Ei =
9692 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009693 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009694 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009695 MachO::linker_option_command Lo =
9696 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009697 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009698 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9699 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9700 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009701 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9702 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9703 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009704 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9705 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9706 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009707 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9708 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9709 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009710 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9711 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9712 PrintRoutinesCommand(Rc);
9713 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9714 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9715 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009716 } else if (Command.C.cmd == MachO::LC_THREAD ||
9717 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9718 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9719 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009720 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9721 Command.C.cmd == MachO::LC_ID_DYLIB ||
9722 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9723 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9724 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9725 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009726 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9727 PrintDylibCommand(Dl, Command.Ptr);
9728 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9729 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9730 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9731 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9732 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9733 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9734 MachO::linkedit_data_command Ld =
9735 Obj->getLinkeditDataLoadCommand(Command);
9736 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009737 } else {
9738 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9739 << ")\n";
9740 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9741 // TODO: get and print the raw bytes of the load command.
9742 }
9743 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009744 }
9745}
9746
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009747static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009748 if (Obj->is64Bit()) {
9749 MachO::mach_header_64 H_64;
9750 H_64 = Obj->getHeader64();
9751 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9752 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9753 } else {
9754 MachO::mach_header H;
9755 H = Obj->getHeader();
9756 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9757 H.sizeofcmds, H.flags, verbose);
9758 }
9759}
9760
9761void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9762 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009763 PrintMachHeader(file, !NonVerbose);
9764}
9765
9766void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9767 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009768 uint32_t filetype = 0;
9769 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009770 if (file->is64Bit()) {
9771 MachO::mach_header_64 H_64;
9772 H_64 = file->getHeader64();
9773 filetype = H_64.filetype;
9774 cputype = H_64.cputype;
9775 } else {
9776 MachO::mach_header H;
9777 H = file->getHeader();
9778 filetype = H.filetype;
9779 cputype = H.cputype;
9780 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009781 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009782}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009783
9784//===----------------------------------------------------------------------===//
9785// export trie dumping
9786//===----------------------------------------------------------------------===//
9787
9788void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009789 uint64_t BaseSegmentAddress = 0;
9790 for (const auto &Command : Obj->load_commands()) {
9791 if (Command.C.cmd == MachO::LC_SEGMENT) {
9792 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9793 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9794 BaseSegmentAddress = Seg.vmaddr;
9795 break;
9796 }
9797 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9798 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9799 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9800 BaseSegmentAddress = Seg.vmaddr;
9801 break;
9802 }
9803 }
9804 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009805 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +00009806 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009807 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009808 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9809 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9810 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9811 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9812 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9813 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9814 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9815 if (ReExport)
9816 outs() << "[re-export] ";
9817 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009818 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009819 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009820 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009821 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009822 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009823 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009824 if (WeakDef) {
9825 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009826 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009827 }
9828 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009829 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009830 outs() << ", ";
9831 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009832 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009833 }
9834 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009835 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009836 outs() << ", ";
9837 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009838 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009839 }
9840 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009841 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009842 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009843 outs() << format("resolver=0x%08llX", Entry.other());
9844 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009845 }
9846 outs() << "]";
9847 }
9848 if (ReExport) {
9849 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009850 int Ordinal = Entry.other() - 1;
9851 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9852 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009853 outs() << " (from " << DylibName << ")";
9854 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009855 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009856 }
9857 outs() << "\n";
9858 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009859 if (Err)
9860 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +00009861}
Nick Kledzikac431442014-09-12 21:34:15 +00009862
Nick Kledzikac431442014-09-12 21:34:15 +00009863//===----------------------------------------------------------------------===//
9864// rebase table dumping
9865//===----------------------------------------------------------------------===//
9866
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009867void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009868 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009869 Error Err = Error::success();
9870 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9871 StringRef SegmentName = Entry.segmentName();
9872 StringRef SectionName = Entry.sectionName();
9873 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009874
9875 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009876 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9877 SegmentName.str().c_str(), SectionName.str().c_str(),
9878 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009879 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009880 if (Err)
9881 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009882}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009883
9884static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9885 StringRef DylibName;
9886 switch (Ordinal) {
9887 case MachO::BIND_SPECIAL_DYLIB_SELF:
9888 return "this-image";
9889 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9890 return "main-executable";
9891 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9892 return "flat-namespace";
9893 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009894 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009895 std::error_code EC =
9896 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009897 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009898 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009899 return DylibName;
9900 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009901 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009902 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009903}
9904
9905//===----------------------------------------------------------------------===//
9906// bind table dumping
9907//===----------------------------------------------------------------------===//
9908
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009909void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009910 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009911 outs() << "segment section address type "
9912 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009913 Error Err = Error::success();
9914 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009915 StringRef SegmentName = Entry.segmentName();
9916 StringRef SectionName = Entry.sectionName();
9917 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009918
9919 // Table lines look like:
9920 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009921 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009922 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009923 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009924 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009925 << left_justify(SectionName, 18) << " "
9926 << format_hex(Address, 10, true) << " "
9927 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009928 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009929 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009930 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009931 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009932 if (Err)
9933 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009934}
9935
9936//===----------------------------------------------------------------------===//
9937// lazy bind table dumping
9938//===----------------------------------------------------------------------===//
9939
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009940void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009941 outs() << "segment section address "
9942 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009943 Error Err = Error::success();
9944 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009945 StringRef SegmentName = Entry.segmentName();
9946 StringRef SectionName = Entry.sectionName();
9947 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009948
9949 // Table lines look like:
9950 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009951 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009952 << left_justify(SectionName, 18) << " "
9953 << format_hex(Address, 10, true) << " "
9954 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009955 << Entry.symbolName() << "\n";
9956 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009957 if (Err)
9958 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009959}
9960
Nick Kledzik56ebef42014-09-16 01:41:51 +00009961//===----------------------------------------------------------------------===//
9962// weak bind table dumping
9963//===----------------------------------------------------------------------===//
9964
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009965void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009966 outs() << "segment section address "
9967 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009968 Error Err = Error::success();
9969 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009970 // Strong symbols don't have a location to update.
9971 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009972 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009973 << Entry.symbolName() << "\n";
9974 continue;
9975 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009976 StringRef SegmentName = Entry.segmentName();
9977 StringRef SectionName = Entry.sectionName();
9978 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009979
9980 // Table lines look like:
9981 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009982 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009983 << left_justify(SectionName, 18) << " "
9984 << format_hex(Address, 10, true) << " "
9985 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009986 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9987 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009988 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009989 if (Err)
9990 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009991}
9992
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009993// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9994// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9995// information for that address. If the address is found its binding symbol
9996// name is returned. If not nullptr is returned.
9997static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9998 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009999 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010000 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010001 Error Err = Error::success();
10002 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010003 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010004 StringRef name = Entry.symbolName();
10005 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010006 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010007 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010008 if (Err)
10009 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010010 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010011 auto name = info->bindtable->lookup(ReferenceValue);
10012 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010013}
Michael Trent1854ecc2017-12-05 07:50:00 +000010014