blob: b5c0439c24c2916c4583d60275b5acd7b66cfd5d [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"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000047#include "llvm/Support/WithColor.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000049#include <algorithm>
50#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000051#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000052
Kevin Enderby9873e2c2016-05-23 21:34:12 +000053#ifdef HAVE_LIBXAR
54extern "C" {
55#include <xar/xar.h>
56}
57#endif
58
Benjamin Kramer43a772e2011-09-19 17:56:04 +000059using namespace llvm;
60using namespace object;
61
62static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000063 UseDbg("g",
64 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000065
Kevin Enderbyb28ed012014-10-29 21:28:24 +000066static cl::opt<std::string> DSYMFile("dsym",
67 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000068
Kevin Enderbyb28ed012014-10-29 21:28:24 +000069static cl::opt<bool> FullLeadingAddr("full-leading-addr",
70 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000071
Kevin Enderbyf9d60f02016-11-29 21:43:40 +000072static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
73 cl::desc("Print no leading headers"));
74
Kevin Enderby13023a12015-01-15 23:19:11 +000075cl::opt<bool> llvm::UniversalHeaders("universal-headers",
76 cl::desc("Print Mach-O universal headers "
77 "(requires -macho)"));
78
Kevin Enderby131d1772015-01-09 19:22:37 +000079cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000080 ArchiveMemberOffsets("archive-member-offsets",
81 cl::desc("Print the offset to each archive member for "
82 "Mach-O archives (requires -macho and "
83 "-archive-headers)"));
84
85cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000086 llvm::IndirectSymbols("indirect-symbols",
87 cl::desc("Print indirect symbol table for Mach-O "
88 "objects (requires -macho)"));
89
Kevin Enderby69fe98d2015-01-23 18:52:17 +000090cl::opt<bool>
91 llvm::DataInCode("data-in-code",
92 cl::desc("Print the data in code table for Mach-O objects "
93 "(requires -macho)"));
94
Kevin Enderby9a509442015-01-27 21:28:24 +000095cl::opt<bool>
96 llvm::LinkOptHints("link-opt-hints",
97 cl::desc("Print the linker optimization hints for "
98 "Mach-O objects (requires -macho)"));
99
Kevin Enderbycd66be52015-03-11 22:06:32 +0000100cl::opt<bool>
101 llvm::InfoPlist("info-plist",
102 cl::desc("Print the info plist section as strings for "
103 "Mach-O objects (requires -macho)"));
104
Kevin Enderbyf0640752015-03-13 17:56:32 +0000105cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000106 llvm::DylibsUsed("dylibs-used",
107 cl::desc("Print the shared libraries used for linked "
108 "Mach-O files (requires -macho)"));
109
110cl::opt<bool>
111 llvm::DylibId("dylib-id",
112 cl::desc("Print the shared library's id for the dylib Mach-O "
113 "file (requires -macho)"));
114
115cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000116 llvm::NonVerbose("non-verbose",
117 cl::desc("Print the info for Mach-O objects in "
118 "non-verbose or numeric form (requires -macho)"));
119
Kevin Enderby0fc11822015-04-01 20:57:01 +0000120cl::opt<bool>
121 llvm::ObjcMetaData("objc-meta-data",
122 cl::desc("Print the Objective-C runtime meta data for "
123 "Mach-O files (requires -macho)"));
124
Kevin Enderby6a221752015-03-17 17:10:57 +0000125cl::opt<std::string> llvm::DisSymName(
126 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000127 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000128
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000129static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
132
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000133static cl::list<std::string>
134 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
135 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000136
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137bool ArchAll = false;
138
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000139static std::string ThumbTripleName;
140
141static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000144 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000145 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000146 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000147 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000148 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000149 }
150
151 if (TT.getArch() == Triple::arm) {
152 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
153 // that support ARM are also capable of Thumb mode.
154 llvm::Triple ThumbTriple = TT;
155 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
156 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000157 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000158 }
159
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000160 // Get the target specific parser.
161 std::string Error;
162 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000163 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000164 return TheTarget;
165
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000166 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
167 if (*ThumbTarget)
168 return TheTarget;
169
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000170 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000171 if (!TheTarget)
172 errs() << TripleName;
173 else
174 errs() << ThumbTripleName;
175 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000176 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000177}
178
Owen Andersond9243c42011-10-17 21:37:35 +0000179struct SymbolSorter {
180 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000181 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000182 if (!ATypeOrErr)
183 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000184 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000185 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000186 if (!BTypeOrErr)
187 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000188 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000189 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
190 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000191 return AAddr < BAddr;
192 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000193};
194
Kevin Enderby273ae012013-06-06 17:20:50 +0000195// Types for the storted data in code table that is built before disassembly
196// and the predicate function to sort them.
197typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
198typedef std::vector<DiceTableEntry> DiceTable;
199typedef DiceTable::iterator dice_table_iterator;
200
Francis Ricci195a66f2017-10-06 15:54:20 +0000201#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000202namespace {
203struct ScopedXarFile {
204 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000205 ScopedXarFile(const char *filename, int32_t flags)
206 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000207 ~ScopedXarFile() {
208 if (xar)
209 xar_close(xar);
210 }
211 ScopedXarFile(const ScopedXarFile &) = delete;
212 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
213 operator xar_t() { return xar; }
214};
215
216struct ScopedXarIter {
217 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000218 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000219 ~ScopedXarIter() {
220 if (iter)
221 xar_iter_free(iter);
222 }
223 ScopedXarIter(const ScopedXarIter &) = delete;
224 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
225 operator xar_iter_t() { return iter; }
226};
227} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000228#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000229
Kevin Enderby930fdc72014-11-06 19:00:13 +0000230// This is used to search for a data in code table entry for the PC being
231// disassembled. The j parameter has the PC in j.first. A single data in code
232// table entry can cover many bytes for each of its Kind's. So if the offset,
233// aka the i.first value, of the data in code table entry plus its Length
234// covers the PC being searched for this will return true. If not it will
235// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000236static bool compareDiceTableEntries(const DiceTableEntry &i,
237 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000238 uint16_t Length;
239 i.second.getLength(Length);
240
241 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000242}
243
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000244static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000245 unsigned short Kind) {
246 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000247
248 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000249 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000250 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000251 if (Length >= 4) {
252 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000253 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000254 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000255 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000256 Size = 4;
257 } else if (Length >= 2) {
258 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000259 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000260 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000261 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000262 Size = 2;
263 } else {
264 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000265 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000266 Value = bytes[0];
267 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000268 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000269 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000270 if (Kind == MachO::DICE_KIND_DATA)
271 outs() << "\t@ KIND_DATA\n";
272 else
273 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000274 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000275 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000276 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000277 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000278 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000279 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
280 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000281 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000282 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000283 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000284 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000285 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000286 outs() << "\t.short " << format("%5u", Value & 0xffff)
287 << "\t@ KIND_JUMP_TABLE16\n";
288 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000289 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000290 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000291 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
292 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000293 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000294 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000295 outs() << "\t.long " << Value;
296 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
297 outs() << "\t@ KIND_JUMP_TABLE32\n";
298 else
299 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
300 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000301 break;
302 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000303 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000304}
305
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000306static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000307 std::vector<SectionRef> &Sections,
308 std::vector<SymbolRef> &Symbols,
309 SmallVectorImpl<uint64_t> &FoundFns,
310 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000311 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000312 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000313 if (!SymName)
314 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000315 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000316 Symbols.push_back(Symbol);
317 }
Owen Andersond9243c42011-10-17 21:37:35 +0000318
Alexey Samsonov48803e52014-03-13 14:37:36 +0000319 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000320 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000321 Section.getName(SectName);
322 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000323 }
324
Kevin Enderby273ae012013-06-06 17:20:50 +0000325 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000326 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000327 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000328 // We found a function starts segment, parse the addresses for later
329 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000330 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000331 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000332
Charles Davis8bdfafd2013-09-01 04:28:48 +0000333 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000334 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
335 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000336 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000337 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000338 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000339 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000340 }
341 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000342 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000343}
344
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000345static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
346 uint32_t n, uint32_t count,
347 uint32_t stride, uint64_t addr) {
348 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
349 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
350 if (n > nindirectsyms)
351 outs() << " (entries start past the end of the indirect symbol "
352 "table) (reserved1 field greater than the table size)";
353 else if (n + count > nindirectsyms)
354 outs() << " (entries extends past the end of the indirect symbol "
355 "table)";
356 outs() << "\n";
357 uint32_t cputype = O->getHeader().cputype;
358 if (cputype & MachO::CPU_ARCH_ABI64)
359 outs() << "address index";
360 else
361 outs() << "address index";
362 if (verbose)
363 outs() << " name\n";
364 else
365 outs() << "\n";
366 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
367 if (cputype & MachO::CPU_ARCH_ABI64)
368 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
369 else
Tim Northover43978372016-04-26 18:29:16 +0000370 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000371 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
372 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
373 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
374 outs() << "LOCAL\n";
375 continue;
376 }
377 if (indirect_symbol ==
378 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
379 outs() << "LOCAL ABSOLUTE\n";
380 continue;
381 }
382 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
383 outs() << "ABSOLUTE\n";
384 continue;
385 }
386 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000387 if (verbose) {
388 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
389 if (indirect_symbol < Symtab.nsyms) {
390 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
391 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000392 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000393 if (!SymName)
394 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000395 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000396 } else {
397 outs() << "?";
398 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000399 }
400 outs() << "\n";
401 }
402}
403
404static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000405 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000406 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
407 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
408 for (unsigned J = 0; J < Seg.nsects; ++J) {
409 MachO::section_64 Sec = O->getSection64(Load, J);
410 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
411 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
412 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
413 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
414 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
415 section_type == MachO::S_SYMBOL_STUBS) {
416 uint32_t stride;
417 if (section_type == MachO::S_SYMBOL_STUBS)
418 stride = Sec.reserved2;
419 else
420 stride = 8;
421 if (stride == 0) {
422 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
423 << Sec.sectname << ") "
424 << "(size of stubs in reserved2 field is zero)\n";
425 continue;
426 }
427 uint32_t count = Sec.size / stride;
428 outs() << "Indirect symbols for (" << Sec.segname << ","
429 << Sec.sectname << ") " << count << " entries";
430 uint32_t n = Sec.reserved1;
431 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
432 }
433 }
434 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
435 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
436 for (unsigned J = 0; J < Seg.nsects; ++J) {
437 MachO::section Sec = O->getSection(Load, J);
438 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
439 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
440 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
441 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
442 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
443 section_type == MachO::S_SYMBOL_STUBS) {
444 uint32_t stride;
445 if (section_type == MachO::S_SYMBOL_STUBS)
446 stride = Sec.reserved2;
447 else
448 stride = 4;
449 if (stride == 0) {
450 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
451 << Sec.sectname << ") "
452 << "(size of stubs in reserved2 field is zero)\n";
453 continue;
454 }
455 uint32_t count = Sec.size / stride;
456 outs() << "Indirect symbols for (" << Sec.segname << ","
457 << Sec.sectname << ") " << count << " entries";
458 uint32_t n = Sec.reserved1;
459 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
460 }
461 }
462 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000463 }
464}
465
Michael Trenta1703b12017-12-15 17:57:40 +0000466static void PrintRType(const uint64_t cputype, const unsigned r_type) {
467 static char const *generic_r_types[] = {
468 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
469 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
470 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
471 };
472 static char const *x86_64_r_types[] = {
473 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
474 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
475 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
476 };
477 static char const *arm_r_types[] = {
478 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
479 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
480 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
481 };
482 static char const *arm64_r_types[] = {
483 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
484 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
485 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
486 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000487
Michael Trenta1703b12017-12-15 17:57:40 +0000488 if (r_type > 0xf){
489 outs() << format("%-7u", r_type) << " ";
490 return;
491 }
492 switch (cputype) {
493 case MachO::CPU_TYPE_I386:
494 outs() << generic_r_types[r_type];
495 break;
496 case MachO::CPU_TYPE_X86_64:
497 outs() << x86_64_r_types[r_type];
498 break;
499 case MachO::CPU_TYPE_ARM:
500 outs() << arm_r_types[r_type];
501 break;
502 case MachO::CPU_TYPE_ARM64:
503 outs() << arm64_r_types[r_type];
504 break;
505 default:
506 outs() << format("%-7u ", r_type);
507 }
508}
509
510static void PrintRLength(const uint64_t cputype, const unsigned r_type,
511 const unsigned r_length, const bool previous_arm_half){
512 if (cputype == MachO::CPU_TYPE_ARM &&
513 (r_type == llvm::MachO::ARM_RELOC_HALF ||
514 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
515 previous_arm_half == true)) {
516 if ((r_length & 0x1) == 0)
517 outs() << "lo/";
518 else
519 outs() << "hi/";
520 if ((r_length & 0x1) == 0)
521 outs() << "arm ";
522 else
523 outs() << "thm ";
524 } else {
525 switch (r_length) {
526 case 0:
527 outs() << "byte ";
528 break;
529 case 1:
530 outs() << "word ";
531 break;
532 case 2:
533 outs() << "long ";
534 break;
535 case 3:
536 if (cputype == MachO::CPU_TYPE_X86_64)
537 outs() << "quad ";
538 else
539 outs() << format("?(%2d) ", r_length);
540 break;
541 default:
542 outs() << format("?(%2d) ", r_length);
543 }
544 }
545}
546
547static void PrintRelocationEntries(const MachOObjectFile *O,
548 const relocation_iterator Begin,
549 const relocation_iterator End,
550 const uint64_t cputype,
551 const bool verbose) {
552 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
553 bool previous_arm_half = false;
554 bool previous_sectdiff = false;
555 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000556
Michael Trenta1703b12017-12-15 17:57:40 +0000557 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
558 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
559 const MachO::any_relocation_info RE = O->getRelocation(Rel);
560 const unsigned r_type = O->getAnyRelocationType(RE);
561 const bool r_scattered = O->isRelocationScattered(RE);
562 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
563 const unsigned r_length = O->getAnyRelocationLength(RE);
564 const unsigned r_address = O->getAnyRelocationAddress(RE);
565 const bool r_extern = (r_scattered ? false :
566 O->getPlainRelocationExternal(RE));
567 const uint32_t r_value = (r_scattered ?
568 O->getScatteredRelocationValue(RE) : 0);
569 const unsigned r_symbolnum = (r_scattered ? 0 :
570 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000571
Michael Trenta1703b12017-12-15 17:57:40 +0000572 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
573 if (verbose) {
574 // scattered: address
575 if ((cputype == MachO::CPU_TYPE_I386 &&
576 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
577 (cputype == MachO::CPU_TYPE_ARM &&
578 r_type == llvm::MachO::ARM_RELOC_PAIR))
579 outs() << " ";
580 else
581 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000582
Michael Trenta1703b12017-12-15 17:57:40 +0000583 // scattered: pcrel
584 if (r_pcrel)
585 outs() << "True ";
586 else
587 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000588
Michael Trenta1703b12017-12-15 17:57:40 +0000589 // scattered: length
590 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000591
Michael Trenta1703b12017-12-15 17:57:40 +0000592 // scattered: extern & type
593 outs() << "n/a ";
594 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000595
Michael Trenta1703b12017-12-15 17:57:40 +0000596 // scattered: scattered & value
597 outs() << format("True 0x%08x", (unsigned int)r_value);
598 if (previous_sectdiff == false) {
599 if ((cputype == MachO::CPU_TYPE_ARM &&
600 r_type == llvm::MachO::ARM_RELOC_PAIR))
601 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
602 }
603 else if (cputype == MachO::CPU_TYPE_ARM &&
604 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
605 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
606 if ((cputype == MachO::CPU_TYPE_I386 &&
607 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
608 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
609 (cputype == MachO::CPU_TYPE_ARM &&
610 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
611 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
612 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
613 previous_sectdiff = true;
614 sectdiff_r_type = r_type;
615 }
616 else {
617 previous_sectdiff = false;
618 sectdiff_r_type = 0;
619 }
620 if (cputype == MachO::CPU_TYPE_ARM &&
621 (r_type == llvm::MachO::ARM_RELOC_HALF ||
622 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
623 previous_arm_half = true;
624 else
625 previous_arm_half = false;
626 outs() << "\n";
627 }
628 else {
629 // scattered: address pcrel length extern type scattered value
630 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
631 (unsigned int)r_address, r_pcrel, r_length, r_type,
632 (unsigned int)r_value);
633 }
634 }
635 else {
636 if (verbose) {
637 // plain: address
638 if (cputype == MachO::CPU_TYPE_ARM &&
639 r_type == llvm::MachO::ARM_RELOC_PAIR)
640 outs() << " ";
641 else
642 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000643
Michael Trenta1703b12017-12-15 17:57:40 +0000644 // plain: pcrel
645 if (r_pcrel)
646 outs() << "True ";
647 else
648 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000649
Michael Trenta1703b12017-12-15 17:57:40 +0000650 // plain: length
651 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000652
Michael Trenta1703b12017-12-15 17:57:40 +0000653 if (r_extern) {
654 // plain: extern & type & scattered
655 outs() << "True ";
656 PrintRType(cputype, r_type);
657 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000658
Michael Trenta1703b12017-12-15 17:57:40 +0000659 // plain: symbolnum/value
660 if (r_symbolnum > Symtab.nsyms)
661 outs() << format("?(%d)\n", r_symbolnum);
662 else {
663 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
664 Expected<StringRef> SymNameNext = Symbol.getName();
665 const char *name = NULL;
666 if (SymNameNext)
667 name = SymNameNext->data();
668 if (name == NULL)
669 outs() << format("?(%d)\n", r_symbolnum);
670 else
671 outs() << name << "\n";
672 }
673 }
674 else {
675 // plain: extern & type & scattered
676 outs() << "False ";
677 PrintRType(cputype, r_type);
678 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000679
Michael Trenta1703b12017-12-15 17:57:40 +0000680 // plain: symbolnum/value
681 if (cputype == MachO::CPU_TYPE_ARM &&
682 r_type == llvm::MachO::ARM_RELOC_PAIR)
683 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
684 else if (cputype == MachO::CPU_TYPE_ARM64 &&
685 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
686 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
687 else {
688 outs() << format("%d ", r_symbolnum);
689 if (r_symbolnum == llvm::MachO::R_ABS)
690 outs() << "R_ABS\n";
691 else {
692 // in this case, r_symbolnum is actually a 1-based section number
693 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
694 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
695 llvm::object::DataRefImpl DRI;
696 DRI.d.a = r_symbolnum-1;
697 StringRef SegName = O->getSectionFinalSegmentName(DRI);
698 StringRef SectName;
699 if (O->getSectionName(DRI, SectName))
700 outs() << "(?,?)\n";
701 else
702 outs() << "(" << SegName << "," << SectName << ")\n";
703 }
704 else {
705 outs() << "(?,?)\n";
706 }
707 }
708 }
709 }
710 if (cputype == MachO::CPU_TYPE_ARM &&
711 (r_type == llvm::MachO::ARM_RELOC_HALF ||
712 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
713 previous_arm_half = true;
714 else
715 previous_arm_half = false;
716 }
717 else {
718 // plain: address pcrel length extern type scattered symbolnum/section
719 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
720 (unsigned int)r_address, r_pcrel, r_length, r_extern,
721 r_type, r_symbolnum);
722 }
723 }
724 }
725}
726
727static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
728 const uint64_t cputype = O->getHeader().cputype;
729 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
730 if (Dysymtab.nextrel != 0) {
731 outs() << "External relocation information " << Dysymtab.nextrel
732 << " entries";
733 outs() << "\naddress pcrel length extern type scattered "
734 "symbolnum/value\n";
735 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
736 verbose);
737 }
738 if (Dysymtab.nlocrel != 0) {
739 outs() << format("Local relocation information %u entries",
740 Dysymtab.nlocrel);
741 outs() << "\naddress pcrel length extern type scattered "
742 "symbolnum/value\n";
743 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
744 verbose);
745 }
746 for (const auto &Load : O->load_commands()) {
747 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
748 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
749 for (unsigned J = 0; J < Seg.nsects; ++J) {
750 const MachO::section_64 Sec = O->getSection64(Load, J);
751 if (Sec.nreloc != 0) {
752 DataRefImpl DRI;
753 DRI.d.a = J;
754 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
755 StringRef SectName;
756 if (O->getSectionName(DRI, SectName))
757 outs() << "Relocation information (" << SegName << ",?) "
758 << format("%u entries", Sec.nreloc);
759 else
760 outs() << "Relocation information (" << SegName << ","
761 << SectName << format(") %u entries", Sec.nreloc);
762 outs() << "\naddress pcrel length extern type scattered "
763 "symbolnum/value\n";
764 PrintRelocationEntries(O, O->section_rel_begin(DRI),
765 O->section_rel_end(DRI), cputype, verbose);
766 }
767 }
768 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
769 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
770 for (unsigned J = 0; J < Seg.nsects; ++J) {
771 const MachO::section Sec = O->getSection(Load, J);
772 if (Sec.nreloc != 0) {
773 DataRefImpl DRI;
774 DRI.d.a = J;
775 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
776 StringRef SectName;
777 if (O->getSectionName(DRI, SectName))
778 outs() << "Relocation information (" << SegName << ",?) "
779 << format("%u entries", Sec.nreloc);
780 else
781 outs() << "Relocation information (" << SegName << ","
782 << SectName << format(") %u entries", Sec.nreloc);
783 outs() << "\naddress pcrel length extern type scattered "
784 "symbolnum/value\n";
785 PrintRelocationEntries(O, O->section_rel_begin(DRI),
786 O->section_rel_end(DRI), cputype, verbose);
787 }
788 }
789 }
790 }
791}
792
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000793static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
794 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
795 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
796 outs() << "Data in code table (" << nentries << " entries)\n";
797 outs() << "offset length kind\n";
798 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
799 ++DI) {
800 uint32_t Offset;
801 DI->getOffset(Offset);
802 outs() << format("0x%08" PRIx32, Offset) << " ";
803 uint16_t Length;
804 DI->getLength(Length);
805 outs() << format("%6u", Length) << " ";
806 uint16_t Kind;
807 DI->getKind(Kind);
808 if (verbose) {
809 switch (Kind) {
810 case MachO::DICE_KIND_DATA:
811 outs() << "DATA";
812 break;
813 case MachO::DICE_KIND_JUMP_TABLE8:
814 outs() << "JUMP_TABLE8";
815 break;
816 case MachO::DICE_KIND_JUMP_TABLE16:
817 outs() << "JUMP_TABLE16";
818 break;
819 case MachO::DICE_KIND_JUMP_TABLE32:
820 outs() << "JUMP_TABLE32";
821 break;
822 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
823 outs() << "ABS_JUMP_TABLE32";
824 break;
825 default:
826 outs() << format("0x%04" PRIx32, Kind);
827 break;
828 }
829 } else
830 outs() << format("0x%04" PRIx32, Kind);
831 outs() << "\n";
832 }
833}
834
Kevin Enderby9a509442015-01-27 21:28:24 +0000835static void PrintLinkOptHints(MachOObjectFile *O) {
836 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
837 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
838 uint32_t nloh = LohLC.datasize;
839 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
840 for (uint32_t i = 0; i < nloh;) {
841 unsigned n;
842 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
843 i += n;
844 outs() << " identifier " << identifier << " ";
845 if (i >= nloh)
846 return;
847 switch (identifier) {
848 case 1:
849 outs() << "AdrpAdrp\n";
850 break;
851 case 2:
852 outs() << "AdrpLdr\n";
853 break;
854 case 3:
855 outs() << "AdrpAddLdr\n";
856 break;
857 case 4:
858 outs() << "AdrpLdrGotLdr\n";
859 break;
860 case 5:
861 outs() << "AdrpAddStr\n";
862 break;
863 case 6:
864 outs() << "AdrpLdrGotStr\n";
865 break;
866 case 7:
867 outs() << "AdrpAdd\n";
868 break;
869 case 8:
870 outs() << "AdrpLdrGot\n";
871 break;
872 default:
873 outs() << "Unknown identifier value\n";
874 break;
875 }
876 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
877 i += n;
878 outs() << " narguments " << narguments << "\n";
879 if (i >= nloh)
880 return;
881
882 for (uint32_t j = 0; j < narguments; j++) {
883 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
884 i += n;
885 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
886 if (i >= nloh)
887 return;
888 }
889 }
890}
891
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000892static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000893 unsigned Index = 0;
894 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000895 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
896 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
897 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
898 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
899 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
900 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
901 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
902 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
903 if (dl.dylib.name < dl.cmdsize) {
904 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
905 if (JustId)
906 outs() << p << "\n";
907 else {
908 outs() << "\t" << p;
909 outs() << " (compatibility version "
910 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
911 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
912 << (dl.dylib.compatibility_version & 0xff) << ",";
913 outs() << " current version "
914 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
915 << ((dl.dylib.current_version >> 8) & 0xff) << "."
916 << (dl.dylib.current_version & 0xff) << ")\n";
917 }
918 } else {
919 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
920 if (Load.C.cmd == MachO::LC_ID_DYLIB)
921 outs() << "LC_ID_DYLIB ";
922 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
923 outs() << "LC_LOAD_DYLIB ";
924 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
925 outs() << "LC_LOAD_WEAK_DYLIB ";
926 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
927 outs() << "LC_LAZY_LOAD_DYLIB ";
928 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
929 outs() << "LC_REEXPORT_DYLIB ";
930 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
931 outs() << "LC_LOAD_UPWARD_DYLIB ";
932 else
933 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000934 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000935 }
936 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000937 }
938}
939
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000940typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
941
942static void CreateSymbolAddressMap(MachOObjectFile *O,
943 SymbolAddressMap *AddrMap) {
944 // Create a map of symbol addresses to symbol names.
945 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000946 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000947 if (!STOrErr)
948 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000949 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000950 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
951 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000952 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000953 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000954 if (!SymNameOrErr)
955 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000956 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000957 if (!SymName.startswith(".objc"))
958 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000959 }
960 }
961}
962
963// GuessSymbolName is passed the address of what might be a symbol and a
964// pointer to the SymbolAddressMap. It returns the name of a symbol
965// with that address or nullptr if no symbol is found with that address.
966static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
967 const char *SymbolName = nullptr;
968 // A DenseMap can't lookup up some values.
969 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
970 StringRef name = AddrMap->lookup(value);
971 if (!name.empty())
972 SymbolName = name.data();
973 }
974 return SymbolName;
975}
976
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000977static void DumpCstringChar(const char c) {
978 char p[2];
979 p[0] = c;
980 p[1] = '\0';
981 outs().write_escaped(p);
982}
983
Kevin Enderby10ba0412015-02-04 21:38:42 +0000984static void DumpCstringSection(MachOObjectFile *O, const char *sect,
985 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000986 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000987 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000988 if (print_addresses) {
989 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000990 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000991 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000992 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000993 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000994 for (; i < sect_size && sect[i] != '\0'; i++)
995 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000996 if (i < sect_size && sect[i] == '\0')
997 outs() << "\n";
998 }
999}
1000
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001001static void DumpLiteral4(uint32_t l, float f) {
1002 outs() << format("0x%08" PRIx32, l);
1003 if ((l & 0x7f800000) != 0x7f800000)
1004 outs() << format(" (%.16e)\n", f);
1005 else {
1006 if (l == 0x7f800000)
1007 outs() << " (+Infinity)\n";
1008 else if (l == 0xff800000)
1009 outs() << " (-Infinity)\n";
1010 else if ((l & 0x00400000) == 0x00400000)
1011 outs() << " (non-signaling Not-a-Number)\n";
1012 else
1013 outs() << " (signaling Not-a-Number)\n";
1014 }
1015}
1016
1017static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1018 uint32_t sect_size, uint64_t sect_addr,
1019 bool print_addresses) {
1020 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1021 if (print_addresses) {
1022 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001023 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001024 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001025 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001026 }
1027 float f;
1028 memcpy(&f, sect + i, sizeof(float));
1029 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1030 sys::swapByteOrder(f);
1031 uint32_t l;
1032 memcpy(&l, sect + i, sizeof(uint32_t));
1033 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1034 sys::swapByteOrder(l);
1035 DumpLiteral4(l, f);
1036 }
1037}
1038
1039static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1040 double d) {
1041 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1042 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001043 Hi = (O->isLittleEndian()) ? l1 : l0;
1044 Lo = (O->isLittleEndian()) ? l0 : l1;
1045
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001046 // Hi is the high word, so this is equivalent to if(isfinite(d))
1047 if ((Hi & 0x7ff00000) != 0x7ff00000)
1048 outs() << format(" (%.16e)\n", d);
1049 else {
1050 if (Hi == 0x7ff00000 && Lo == 0)
1051 outs() << " (+Infinity)\n";
1052 else if (Hi == 0xfff00000 && Lo == 0)
1053 outs() << " (-Infinity)\n";
1054 else if ((Hi & 0x00080000) == 0x00080000)
1055 outs() << " (non-signaling Not-a-Number)\n";
1056 else
1057 outs() << " (signaling Not-a-Number)\n";
1058 }
1059}
1060
1061static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1062 uint32_t sect_size, uint64_t sect_addr,
1063 bool print_addresses) {
1064 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1065 if (print_addresses) {
1066 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001067 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001068 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001069 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001070 }
1071 double d;
1072 memcpy(&d, sect + i, sizeof(double));
1073 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1074 sys::swapByteOrder(d);
1075 uint32_t l0, l1;
1076 memcpy(&l0, sect + i, sizeof(uint32_t));
1077 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1078 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1079 sys::swapByteOrder(l0);
1080 sys::swapByteOrder(l1);
1081 }
1082 DumpLiteral8(O, l0, l1, d);
1083 }
1084}
1085
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001086static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1087 outs() << format("0x%08" PRIx32, l0) << " ";
1088 outs() << format("0x%08" PRIx32, l1) << " ";
1089 outs() << format("0x%08" PRIx32, l2) << " ";
1090 outs() << format("0x%08" PRIx32, l3) << "\n";
1091}
1092
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001093static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1094 uint32_t sect_size, uint64_t sect_addr,
1095 bool print_addresses) {
1096 for (uint32_t i = 0; i < sect_size; i += 16) {
1097 if (print_addresses) {
1098 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001099 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001101 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001102 }
1103 uint32_t l0, l1, l2, l3;
1104 memcpy(&l0, sect + i, sizeof(uint32_t));
1105 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1106 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1107 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1108 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1109 sys::swapByteOrder(l0);
1110 sys::swapByteOrder(l1);
1111 sys::swapByteOrder(l2);
1112 sys::swapByteOrder(l3);
1113 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001114 DumpLiteral16(l0, l1, l2, l3);
1115 }
1116}
1117
1118static void DumpLiteralPointerSection(MachOObjectFile *O,
1119 const SectionRef &Section,
1120 const char *sect, uint32_t sect_size,
1121 uint64_t sect_addr,
1122 bool print_addresses) {
1123 // Collect the literal sections in this Mach-O file.
1124 std::vector<SectionRef> LiteralSections;
1125 for (const SectionRef &Section : O->sections()) {
1126 DataRefImpl Ref = Section.getRawDataRefImpl();
1127 uint32_t section_type;
1128 if (O->is64Bit()) {
1129 const MachO::section_64 Sec = O->getSection64(Ref);
1130 section_type = Sec.flags & MachO::SECTION_TYPE;
1131 } else {
1132 const MachO::section Sec = O->getSection(Ref);
1133 section_type = Sec.flags & MachO::SECTION_TYPE;
1134 }
1135 if (section_type == MachO::S_CSTRING_LITERALS ||
1136 section_type == MachO::S_4BYTE_LITERALS ||
1137 section_type == MachO::S_8BYTE_LITERALS ||
1138 section_type == MachO::S_16BYTE_LITERALS)
1139 LiteralSections.push_back(Section);
1140 }
1141
1142 // Set the size of the literal pointer.
1143 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1144
Eric Christopher572e03a2015-06-19 01:53:21 +00001145 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001146 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1147 for (const RelocationRef &Reloc : Section.relocations()) {
1148 DataRefImpl Rel;
1149 MachO::any_relocation_info RE;
1150 bool isExtern = false;
1151 Rel = Reloc.getRawDataRefImpl();
1152 RE = O->getRelocation(Rel);
1153 isExtern = O->getPlainRelocationExternal(RE);
1154 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001155 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001156 symbol_iterator RelocSym = Reloc.getSymbol();
1157 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1158 }
1159 }
1160 array_pod_sort(Relocs.begin(), Relocs.end());
1161
1162 // Dump each literal pointer.
1163 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1164 if (print_addresses) {
1165 if (O->is64Bit())
1166 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1167 else
1168 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1169 }
1170 uint64_t lp;
1171 if (O->is64Bit()) {
1172 memcpy(&lp, sect + i, sizeof(uint64_t));
1173 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1174 sys::swapByteOrder(lp);
1175 } else {
1176 uint32_t li;
1177 memcpy(&li, sect + i, sizeof(uint32_t));
1178 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1179 sys::swapByteOrder(li);
1180 lp = li;
1181 }
1182
1183 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001184 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1185 return P.first == i;
1186 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001187 if (Reloc != Relocs.end()) {
1188 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001189 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001190 if (!SymName)
1191 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001192 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001193 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001194 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001195
1196 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001197 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1198 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1199 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001200 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001201 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001202 continue;
1203 }
1204
1205 uint64_t SectAddress = Sect->getAddress();
1206 uint64_t SectSize = Sect->getSize();
1207
1208 StringRef SectName;
1209 Sect->getName(SectName);
1210 DataRefImpl Ref = Sect->getRawDataRefImpl();
1211 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1212 outs() << SegmentName << ":" << SectName << ":";
1213
1214 uint32_t section_type;
1215 if (O->is64Bit()) {
1216 const MachO::section_64 Sec = O->getSection64(Ref);
1217 section_type = Sec.flags & MachO::SECTION_TYPE;
1218 } else {
1219 const MachO::section Sec = O->getSection(Ref);
1220 section_type = Sec.flags & MachO::SECTION_TYPE;
1221 }
1222
1223 StringRef BytesStr;
1224 Sect->getContents(BytesStr);
1225 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1226
1227 switch (section_type) {
1228 case MachO::S_CSTRING_LITERALS:
1229 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1230 i++) {
1231 DumpCstringChar(Contents[i]);
1232 }
1233 outs() << "\n";
1234 break;
1235 case MachO::S_4BYTE_LITERALS:
1236 float f;
1237 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1238 uint32_t l;
1239 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1240 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1241 sys::swapByteOrder(f);
1242 sys::swapByteOrder(l);
1243 }
1244 DumpLiteral4(l, f);
1245 break;
1246 case MachO::S_8BYTE_LITERALS: {
1247 double d;
1248 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1249 uint32_t l0, l1;
1250 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1251 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1252 sizeof(uint32_t));
1253 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1254 sys::swapByteOrder(f);
1255 sys::swapByteOrder(l0);
1256 sys::swapByteOrder(l1);
1257 }
1258 DumpLiteral8(O, l0, l1, d);
1259 break;
1260 }
1261 case MachO::S_16BYTE_LITERALS: {
1262 uint32_t l0, l1, l2, l3;
1263 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1264 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1265 sizeof(uint32_t));
1266 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1267 sizeof(uint32_t));
1268 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1269 sizeof(uint32_t));
1270 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1271 sys::swapByteOrder(l0);
1272 sys::swapByteOrder(l1);
1273 sys::swapByteOrder(l2);
1274 sys::swapByteOrder(l3);
1275 }
1276 DumpLiteral16(l0, l1, l2, l3);
1277 break;
1278 }
1279 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001280 }
1281}
1282
Kevin Enderby85b7a662018-03-20 20:29:52 +00001283static void DumpInitTermPointerSection(MachOObjectFile *O,
1284 const SectionRef &Section,
1285 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001286 uint32_t sect_size, uint64_t sect_addr,
1287 SymbolAddressMap *AddrMap,
1288 bool verbose) {
1289 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001290 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001291
1292 // Collect the external relocation symbols for the pointers.
1293 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1294 for (const RelocationRef &Reloc : Section.relocations()) {
1295 DataRefImpl Rel;
1296 MachO::any_relocation_info RE;
1297 bool isExtern = false;
1298 Rel = Reloc.getRawDataRefImpl();
1299 RE = O->getRelocation(Rel);
1300 isExtern = O->getPlainRelocationExternal(RE);
1301 if (isExtern) {
1302 uint64_t RelocOffset = Reloc.getOffset();
1303 symbol_iterator RelocSym = Reloc.getSymbol();
1304 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1305 }
1306 }
1307 array_pod_sort(Relocs.begin(), Relocs.end());
1308
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001309 for (uint32_t i = 0; i < sect_size; i += stride) {
1310 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001311 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001312 if (O->is64Bit()) {
1313 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1314 uint64_t pointer_value;
1315 memcpy(&pointer_value, sect + i, stride);
1316 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1317 sys::swapByteOrder(pointer_value);
1318 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001319 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001320 } else {
1321 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1322 uint32_t pointer_value;
1323 memcpy(&pointer_value, sect + i, stride);
1324 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1325 sys::swapByteOrder(pointer_value);
1326 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001327 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001328 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001329 if (verbose) {
1330 // First look for an external relocation entry for this pointer.
1331 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1332 return P.first == i;
1333 });
1334 if (Reloc != Relocs.end()) {
1335 symbol_iterator RelocSym = Reloc->second;
1336 Expected<StringRef> SymName = RelocSym->getName();
1337 if (!SymName)
1338 report_error(O->getFileName(), SymName.takeError());
1339 outs() << " " << *SymName;
1340 } else {
1341 SymbolName = GuessSymbolName(p, AddrMap);
1342 if (SymbolName)
1343 outs() << " " << SymbolName;
1344 }
1345 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001346 outs() << "\n";
1347 }
1348}
1349
1350static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1351 uint32_t size, uint64_t addr) {
1352 uint32_t cputype = O->getHeader().cputype;
1353 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1354 uint32_t j;
1355 for (uint32_t i = 0; i < size; i += j, addr += j) {
1356 if (O->is64Bit())
1357 outs() << format("%016" PRIx64, addr) << "\t";
1358 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001359 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001360 for (j = 0; j < 16 && i + j < size; j++) {
1361 uint8_t byte_word = *(sect + i + j);
1362 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1363 }
1364 outs() << "\n";
1365 }
1366 } else {
1367 uint32_t j;
1368 for (uint32_t i = 0; i < size; i += j, addr += j) {
1369 if (O->is64Bit())
1370 outs() << format("%016" PRIx64, addr) << "\t";
1371 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001372 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001373 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1374 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001375 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001376 uint32_t long_word;
1377 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1378 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1379 sys::swapByteOrder(long_word);
1380 outs() << format("%08" PRIx32, long_word) << " ";
1381 } else {
1382 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001383 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001384 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1385 }
1386 }
1387 }
1388 outs() << "\n";
1389 }
1390 }
1391}
1392
Kevin Enderby95df54c2015-02-04 01:01:38 +00001393static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1394 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001395static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1396 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001397#ifdef HAVE_LIBXAR
1398static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1399 uint32_t size, bool verbose,
1400 bool PrintXarHeader, bool PrintXarFileHeaders,
1401 std::string XarMemberName);
1402#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001403
1404static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1405 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001406 SymbolAddressMap AddrMap;
1407 if (verbose)
1408 CreateSymbolAddressMap(O, &AddrMap);
1409
Colin LeMahieufcc32762015-07-29 19:08:10 +00001410 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1411 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001412 std::pair<StringRef, StringRef> DumpSegSectName;
1413 DumpSegSectName = DumpSection.split(',');
1414 StringRef DumpSegName, DumpSectName;
1415 if (DumpSegSectName.second.size()) {
1416 DumpSegName = DumpSegSectName.first;
1417 DumpSectName = DumpSegSectName.second;
1418 } else {
1419 DumpSegName = "";
1420 DumpSectName = DumpSegSectName.first;
1421 }
1422 for (const SectionRef &Section : O->sections()) {
1423 StringRef SectName;
1424 Section.getName(SectName);
1425 DataRefImpl Ref = Section.getRawDataRefImpl();
1426 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1427 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1428 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001429
Kevin Enderby95df54c2015-02-04 01:01:38 +00001430 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001431 if (O->is64Bit()) {
1432 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001433 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001434
1435 } else {
1436 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001437 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001438 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001439 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001440
1441 StringRef BytesStr;
1442 Section.getContents(BytesStr);
1443 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1444 uint32_t sect_size = BytesStr.size();
1445 uint64_t sect_addr = Section.getAddress();
1446
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001447 outs() << "Contents of (" << SegName << "," << SectName
1448 << ") section\n";
1449
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001450 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001451 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1452 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1453 DisassembleMachO(Filename, O, SegName, SectName);
1454 continue;
1455 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001456 if (SegName == "__TEXT" && SectName == "__info_plist") {
1457 outs() << sect;
1458 continue;
1459 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001460 if (SegName == "__OBJC" && SectName == "__protocol") {
1461 DumpProtocolSection(O, sect, sect_size, sect_addr);
1462 continue;
1463 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001464#ifdef HAVE_LIBXAR
1465 if (SegName == "__LLVM" && SectName == "__bundle") {
1466 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1467 ArchiveHeaders, "");
1468 continue;
1469 }
1470#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001471 switch (section_type) {
1472 case MachO::S_REGULAR:
1473 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1474 break;
1475 case MachO::S_ZEROFILL:
1476 outs() << "zerofill section and has no contents in the file\n";
1477 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001478 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001479 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001480 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001481 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001482 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001483 break;
1484 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001485 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001486 break;
1487 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001488 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1489 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001490 case MachO::S_LITERAL_POINTERS:
1491 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001492 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001493 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001494 case MachO::S_MOD_INIT_FUNC_POINTERS:
1495 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001496 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1497 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001498 break;
1499 default:
1500 outs() << "Unknown section type ("
1501 << format("0x%08" PRIx32, section_type) << ")\n";
1502 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1503 break;
1504 }
1505 } else {
1506 if (section_type == MachO::S_ZEROFILL)
1507 outs() << "zerofill section and has no contents in the file\n";
1508 else
1509 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1510 }
1511 }
1512 }
1513 }
1514}
1515
Kevin Enderbycd66be52015-03-11 22:06:32 +00001516static void DumpInfoPlistSectionContents(StringRef Filename,
1517 MachOObjectFile *O) {
1518 for (const SectionRef &Section : O->sections()) {
1519 StringRef SectName;
1520 Section.getName(SectName);
1521 DataRefImpl Ref = Section.getRawDataRefImpl();
1522 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1523 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001524 if (!NoLeadingHeaders)
1525 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001526 StringRef BytesStr;
1527 Section.getContents(BytesStr);
1528 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001529 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001530 return;
1531 }
1532 }
1533}
1534
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001535// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1536// and if it is and there is a list of architecture flags is specified then
1537// check to make sure this Mach-O file is one of those architectures or all
1538// architectures were specified. If not then an error is generated and this
1539// routine returns false. Else it returns true.
1540static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001541 auto *MachO = dyn_cast<MachOObjectFile>(O);
1542
1543 if (!MachO || ArchAll || ArchFlags.empty())
1544 return true;
1545
1546 MachO::mach_header H;
1547 MachO::mach_header_64 H_64;
1548 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001549 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001550 if (MachO->is64Bit()) {
1551 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001552 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1553 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001554 } else {
1555 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001556 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1557 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001558 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001559 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001560 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001561 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001562 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001563 WithColor::error(errs(), "llvm-objdump")
1564 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001565 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001566 }
1567 return true;
1568}
1569
Kevin Enderby0fc11822015-04-01 20:57:01 +00001570static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1571
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001572// ProcessMachO() is passed a single opened Mach-O file, which may be an
1573// archive member and or in a slice of a universal file. It prints the
1574// the file name and header info and then processes it according to the
1575// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001576static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001577 StringRef ArchiveMemberName = StringRef(),
1578 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001579 // If we are doing some processing here on the Mach-O file print the header
1580 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001581 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001582 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1583 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1584 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1585 (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001586 if (!NoLeadingHeaders) {
1587 outs() << Name;
1588 if (!ArchiveMemberName.empty())
1589 outs() << '(' << ArchiveMemberName << ')';
1590 if (!ArchitectureName.empty())
1591 outs() << " (architecture " << ArchitectureName << ")";
1592 outs() << ":\n";
1593 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001594 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001595 // To use the report_error() form with an ArchiveName and FileName set
1596 // these up based on what is passed for Name and ArchiveMemberName.
1597 StringRef ArchiveName;
1598 StringRef FileName;
1599 if (!ArchiveMemberName.empty()) {
1600 ArchiveName = Name;
1601 FileName = ArchiveMemberName;
1602 } else {
1603 ArchiveName = StringRef();
1604 FileName = Name;
1605 }
1606
1607 // If we need the symbol table to do the operation then check it here to
1608 // produce a good error message as to where the Mach-O file comes from in
1609 // the error message.
1610 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1611 UnwindInfo)
1612 if (Error Err = MachOOF->checkSymbolTable())
1613 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001614
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001615 if (Disassemble) {
1616 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001617 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001618 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1619 else
1620 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1621 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001622 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001623 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001624 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001625 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001626 if (LinkOptHints)
1627 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001628 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001629 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001630 if (SectionHeaders)
1631 PrintSectionHeaders(MachOOF);
1632 if (SectionContents)
1633 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001634 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001635 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001636 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001637 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001638 if (DylibsUsed)
1639 PrintDylibs(MachOOF, false);
1640 if (DylibId)
1641 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001642 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001643 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001644 if (UnwindInfo)
1645 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001646 if (PrivateHeaders) {
1647 printMachOFileHeader(MachOOF);
1648 printMachOLoadCommands(MachOOF);
1649 }
1650 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001651 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001652 if (ObjcMetaData)
1653 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001654 if (ExportsTrie)
1655 printExportsTrie(MachOOF);
1656 if (Rebase)
1657 printRebaseTable(MachOOF);
1658 if (Bind)
1659 printBindTable(MachOOF);
1660 if (LazyBind)
1661 printLazyBindTable(MachOOF);
1662 if (WeakBind)
1663 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001664
1665 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001666 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001667 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001668 DIDumpOptions DumpOpts;
1669 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001670 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001671 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001672}
1673
Kevin Enderby131d1772015-01-09 19:22:37 +00001674// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1675static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1676 outs() << " cputype (" << cputype << ")\n";
1677 outs() << " cpusubtype (" << cpusubtype << ")\n";
1678}
1679
1680// printCPUType() helps print_fat_headers by printing the cputype and
1681// pusubtype (symbolically for the one's it knows about).
1682static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1683 switch (cputype) {
1684 case MachO::CPU_TYPE_I386:
1685 switch (cpusubtype) {
1686 case MachO::CPU_SUBTYPE_I386_ALL:
1687 outs() << " cputype CPU_TYPE_I386\n";
1688 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1689 break;
1690 default:
1691 printUnknownCPUType(cputype, cpusubtype);
1692 break;
1693 }
1694 break;
1695 case MachO::CPU_TYPE_X86_64:
1696 switch (cpusubtype) {
1697 case MachO::CPU_SUBTYPE_X86_64_ALL:
1698 outs() << " cputype CPU_TYPE_X86_64\n";
1699 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1700 break;
1701 case MachO::CPU_SUBTYPE_X86_64_H:
1702 outs() << " cputype CPU_TYPE_X86_64\n";
1703 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1704 break;
1705 default:
1706 printUnknownCPUType(cputype, cpusubtype);
1707 break;
1708 }
1709 break;
1710 case MachO::CPU_TYPE_ARM:
1711 switch (cpusubtype) {
1712 case MachO::CPU_SUBTYPE_ARM_ALL:
1713 outs() << " cputype CPU_TYPE_ARM\n";
1714 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1715 break;
1716 case MachO::CPU_SUBTYPE_ARM_V4T:
1717 outs() << " cputype CPU_TYPE_ARM\n";
1718 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1719 break;
1720 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1721 outs() << " cputype CPU_TYPE_ARM\n";
1722 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1723 break;
1724 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1725 outs() << " cputype CPU_TYPE_ARM\n";
1726 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1727 break;
1728 case MachO::CPU_SUBTYPE_ARM_V6:
1729 outs() << " cputype CPU_TYPE_ARM\n";
1730 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1731 break;
1732 case MachO::CPU_SUBTYPE_ARM_V6M:
1733 outs() << " cputype CPU_TYPE_ARM\n";
1734 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1735 break;
1736 case MachO::CPU_SUBTYPE_ARM_V7:
1737 outs() << " cputype CPU_TYPE_ARM\n";
1738 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1739 break;
1740 case MachO::CPU_SUBTYPE_ARM_V7EM:
1741 outs() << " cputype CPU_TYPE_ARM\n";
1742 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1743 break;
1744 case MachO::CPU_SUBTYPE_ARM_V7K:
1745 outs() << " cputype CPU_TYPE_ARM\n";
1746 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1747 break;
1748 case MachO::CPU_SUBTYPE_ARM_V7M:
1749 outs() << " cputype CPU_TYPE_ARM\n";
1750 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1751 break;
1752 case MachO::CPU_SUBTYPE_ARM_V7S:
1753 outs() << " cputype CPU_TYPE_ARM\n";
1754 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1755 break;
1756 default:
1757 printUnknownCPUType(cputype, cpusubtype);
1758 break;
1759 }
1760 break;
1761 case MachO::CPU_TYPE_ARM64:
1762 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1763 case MachO::CPU_SUBTYPE_ARM64_ALL:
1764 outs() << " cputype CPU_TYPE_ARM64\n";
1765 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1766 break;
1767 default:
1768 printUnknownCPUType(cputype, cpusubtype);
1769 break;
1770 }
1771 break;
1772 default:
1773 printUnknownCPUType(cputype, cpusubtype);
1774 break;
1775 }
1776}
1777
1778static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1779 bool verbose) {
1780 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001781 if (verbose) {
1782 if (UB->getMagic() == MachO::FAT_MAGIC)
1783 outs() << "fat_magic FAT_MAGIC\n";
1784 else // UB->getMagic() == MachO::FAT_MAGIC_64
1785 outs() << "fat_magic FAT_MAGIC_64\n";
1786 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001787 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1788
1789 uint32_t nfat_arch = UB->getNumberOfObjects();
1790 StringRef Buf = UB->getData();
1791 uint64_t size = Buf.size();
1792 uint64_t big_size = sizeof(struct MachO::fat_header) +
1793 nfat_arch * sizeof(struct MachO::fat_arch);
1794 outs() << "nfat_arch " << UB->getNumberOfObjects();
1795 if (nfat_arch == 0)
1796 outs() << " (malformed, contains zero architecture types)\n";
1797 else if (big_size > size)
1798 outs() << " (malformed, architectures past end of file)\n";
1799 else
1800 outs() << "\n";
1801
1802 for (uint32_t i = 0; i < nfat_arch; ++i) {
1803 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1804 uint32_t cputype = OFA.getCPUType();
1805 uint32_t cpusubtype = OFA.getCPUSubType();
1806 outs() << "architecture ";
1807 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1808 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1809 uint32_t other_cputype = other_OFA.getCPUType();
1810 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001811 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001812 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001813 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001814 outs() << "(illegal duplicate architecture) ";
1815 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001816 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001817 }
1818 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001819 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001820 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1821 } else {
1822 outs() << i << "\n";
1823 outs() << " cputype " << cputype << "\n";
1824 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1825 << "\n";
1826 }
1827 if (verbose &&
1828 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1829 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1830 else
1831 outs() << " capabilities "
1832 << format("0x%" PRIx32,
1833 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1834 outs() << " offset " << OFA.getOffset();
1835 if (OFA.getOffset() > size)
1836 outs() << " (past end of file)";
1837 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1838 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1839 outs() << "\n";
1840 outs() << " size " << OFA.getSize();
1841 big_size = OFA.getOffset() + OFA.getSize();
1842 if (big_size > size)
1843 outs() << " (past end of file)";
1844 outs() << "\n";
1845 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1846 << ")\n";
1847 }
1848}
1849
Kevin Enderby6524bd82016-07-19 20:47:07 +00001850static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1851 bool verbose, bool print_offset,
1852 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001853 if (print_offset)
1854 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001855 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1856 if (!ModeOrErr)
1857 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1858 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001859 if (verbose) {
1860 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1861 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1862 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001863 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1864 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1865 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1866 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1867 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1868 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1869 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1870 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1871 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001872 } else {
1873 outs() << format("0%o ", Mode);
1874 }
1875
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001876 Expected<unsigned> UIDOrErr = C.getUID();
1877 if (!UIDOrErr)
1878 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1879 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001880 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001881 Expected<unsigned> GIDOrErr = C.getGID();
1882 if (!GIDOrErr)
1883 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1884 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001885 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001886 Expected<uint64_t> Size = C.getRawSize();
1887 if (!Size)
1888 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001889 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001890
1891 StringRef RawLastModified = C.getRawLastModified();
1892 if (verbose) {
1893 unsigned Seconds;
1894 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001895 outs() << "(date: \"" << RawLastModified
1896 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001897 else {
1898 // Since cime(3) returns a 26 character string of the form:
1899 // "Sun Sep 16 01:03:52 1973\n\0"
1900 // just print 24 characters.
1901 time_t t = Seconds;
1902 outs() << format("%.24s ", ctime(&t));
1903 }
1904 } else {
1905 outs() << RawLastModified << " ";
1906 }
1907
1908 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001909 Expected<StringRef> NameOrErr = C.getName();
1910 if (!NameOrErr) {
1911 consumeError(NameOrErr.takeError());
1912 Expected<StringRef> NameOrErr = C.getRawName();
1913 if (!NameOrErr)
1914 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1915 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001916 outs() << RawName << "\n";
1917 } else {
1918 StringRef Name = NameOrErr.get();
1919 outs() << Name << "\n";
1920 }
1921 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001922 Expected<StringRef> NameOrErr = C.getRawName();
1923 if (!NameOrErr)
1924 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1925 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001926 outs() << RawName << "\n";
1927 }
1928}
1929
Kevin Enderby6524bd82016-07-19 20:47:07 +00001930static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1931 bool print_offset,
1932 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001933 Error Err = Error::success();
1934 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001935 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001936 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1937
Lang Hamesfc209622016-07-14 02:24:01 +00001938 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001939 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001940}
1941
Dave Lee3fb120f2018-08-03 00:06:38 +00001942static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001943 // Check for -arch all and verifiy the -arch flags are valid.
1944 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1945 if (ArchFlags[i] == "all") {
1946 ArchAll = true;
1947 } else {
1948 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001949 WithColor::error(errs(), "llvm-objdump")
1950 << "unknown architecture named '" + ArchFlags[i] +
1951 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00001952 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001953 }
1954 }
1955 }
Dave Lee3fb120f2018-08-03 00:06:38 +00001956 return true;
1957}
1958
1959// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1960// -arch flags selecting just those slices as specified by them and also parses
1961// archive files. Then for each individual Mach-O file ProcessMachO() is
1962// called to process the file based on the command line options.
1963void llvm::ParseInputMachO(StringRef Filename) {
1964 if (!ValidateArchFlags())
1965 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001966
1967 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001968 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001969 if (!BinaryOrErr) {
1970 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1971 report_error(Filename, std::move(E));
1972 else
1973 outs() << Filename << ": is not an object file\n";
1974 return;
1975 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001976 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001977
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001978 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1979 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001980 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001981 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1982
Mehdi Amini41af4302016-11-11 04:28:40 +00001983 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001984 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001985 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1986 if (!ChildOrErr) {
1987 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1988 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001989 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001990 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001991 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1992 if (!checkMachOAndArchFlags(O, Filename))
1993 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001994 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001995 }
1996 }
Lang Hamesfc209622016-07-14 02:24:01 +00001997 if (Err)
1998 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001999 return;
2000 }
2001 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002002 ParseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002003 return;
2004 }
2005 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2006 if (!checkMachOAndArchFlags(O, Filename))
2007 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002008 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002009 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002010 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002011 WithColor::error(errs(), "llvm-objdump")
2012 << Filename << "': "
2013 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002014 return;
2015 }
2016 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002017}
2018
Dave Lee3fb120f2018-08-03 00:06:38 +00002019void llvm::ParseInputMachO(MachOUniversalBinary *UB) {
2020 if (!ValidateArchFlags())
2021 return;
2022
2023 auto Filename = UB->getFileName();
2024
2025 if (UniversalHeaders)
2026 printMachOUniversalHeaders(UB, !NonVerbose);
2027
2028 // If we have a list of architecture flags specified dump only those.
2029 if (!ArchAll && ArchFlags.size() != 0) {
2030 // Look for a slice in the universal binary that matches each ArchFlag.
2031 bool ArchFound;
2032 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2033 ArchFound = false;
2034 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2035 E = UB->end_objects();
2036 I != E; ++I) {
2037 if (ArchFlags[i] == I->getArchFlagName()) {
2038 ArchFound = true;
2039 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2040 I->getAsObjectFile();
2041 std::string ArchitectureName = "";
2042 if (ArchFlags.size() > 1)
2043 ArchitectureName = I->getArchFlagName();
2044 if (ObjOrErr) {
2045 ObjectFile &O = *ObjOrErr.get();
2046 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2047 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2048 } else if (auto E = isNotObjectErrorInvalidFileType(
2049 ObjOrErr.takeError())) {
2050 report_error(Filename, StringRef(), std::move(E),
2051 ArchitectureName);
2052 continue;
2053 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2054 I->getAsArchive()) {
2055 std::unique_ptr<Archive> &A = *AOrErr;
2056 outs() << "Archive : " << Filename;
2057 if (!ArchitectureName.empty())
2058 outs() << " (architecture " << ArchitectureName << ")";
2059 outs() << "\n";
2060 if (ArchiveHeaders)
2061 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2062 ArchiveMemberOffsets, ArchitectureName);
2063 Error Err = Error::success();
2064 for (auto &C : A->children(Err)) {
2065 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2066 if (!ChildOrErr) {
2067 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2068 report_error(Filename, C, std::move(E), ArchitectureName);
2069 continue;
2070 }
2071 if (MachOObjectFile *O =
2072 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2073 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2074 }
2075 if (Err)
2076 report_error(Filename, std::move(Err));
2077 } else {
2078 consumeError(AOrErr.takeError());
2079 error("Mach-O universal file: " + Filename + " for " +
2080 "architecture " + StringRef(I->getArchFlagName()) +
2081 " is not a Mach-O file or an archive file");
2082 }
2083 }
2084 }
2085 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002086 WithColor::error(errs(), "llvm-objdump")
2087 << "file: " + Filename + " does not contain "
2088 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002089 return;
2090 }
2091 }
2092 return;
2093 }
2094 // No architecture flags were specified so if this contains a slice that
2095 // matches the host architecture dump only that.
2096 if (!ArchAll) {
2097 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2098 E = UB->end_objects();
2099 I != E; ++I) {
2100 if (MachOObjectFile::getHostArch().getArchName() ==
2101 I->getArchFlagName()) {
2102 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2103 std::string ArchiveName;
2104 ArchiveName.clear();
2105 if (ObjOrErr) {
2106 ObjectFile &O = *ObjOrErr.get();
2107 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2108 ProcessMachO(Filename, MachOOF);
2109 } else if (auto E = isNotObjectErrorInvalidFileType(
2110 ObjOrErr.takeError())) {
2111 report_error(Filename, std::move(E));
Dave Lee3fb120f2018-08-03 00:06:38 +00002112 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2113 I->getAsArchive()) {
2114 std::unique_ptr<Archive> &A = *AOrErr;
2115 outs() << "Archive : " << Filename << "\n";
2116 if (ArchiveHeaders)
2117 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2118 ArchiveMemberOffsets);
2119 Error Err = Error::success();
2120 for (auto &C : A->children(Err)) {
2121 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2122 if (!ChildOrErr) {
2123 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2124 report_error(Filename, C, std::move(E));
2125 continue;
2126 }
2127 if (MachOObjectFile *O =
2128 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2129 ProcessMachO(Filename, O, O->getFileName());
2130 }
2131 if (Err)
2132 report_error(Filename, std::move(Err));
2133 } else {
2134 consumeError(AOrErr.takeError());
2135 error("Mach-O universal file: " + Filename + " for architecture " +
2136 StringRef(I->getArchFlagName()) +
2137 " is not a Mach-O file or an archive file");
2138 }
2139 return;
2140 }
2141 }
2142 }
2143 // Either all architectures have been specified or none have been specified
2144 // and this does not contain the host architecture so dump all the slices.
2145 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2146 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2147 E = UB->end_objects();
2148 I != E; ++I) {
2149 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2150 std::string ArchitectureName = "";
2151 if (moreThanOneArch)
2152 ArchitectureName = I->getArchFlagName();
2153 if (ObjOrErr) {
2154 ObjectFile &Obj = *ObjOrErr.get();
2155 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2156 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2157 } else if (auto E = isNotObjectErrorInvalidFileType(
2158 ObjOrErr.takeError())) {
2159 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002160 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2161 I->getAsArchive()) {
2162 std::unique_ptr<Archive> &A = *AOrErr;
2163 outs() << "Archive : " << Filename;
2164 if (!ArchitectureName.empty())
2165 outs() << " (architecture " << ArchitectureName << ")";
2166 outs() << "\n";
2167 if (ArchiveHeaders)
2168 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2169 ArchiveMemberOffsets, ArchitectureName);
2170 Error Err = Error::success();
2171 for (auto &C : A->children(Err)) {
2172 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2173 if (!ChildOrErr) {
2174 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2175 report_error(Filename, C, std::move(E), ArchitectureName);
2176 continue;
2177 }
2178 if (MachOObjectFile *O =
2179 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2180 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2181 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2182 ArchitectureName);
2183 }
2184 }
2185 if (Err)
2186 report_error(Filename, std::move(Err));
2187 } else {
2188 consumeError(AOrErr.takeError());
2189 error("Mach-O universal file: " + Filename + " for architecture " +
2190 StringRef(I->getArchFlagName()) +
2191 " is not a Mach-O file or an archive file");
2192 }
2193 }
2194}
2195
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002196// The block of info used by the Symbolizer call backs.
2197struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002198 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2199 std::vector<SectionRef> *Sections, bool verbose)
2200 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002201 bool verbose;
2202 MachOObjectFile *O;
2203 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002204 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002205 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002206 const char *class_name = nullptr;
2207 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002208 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002209 char *demangled_name = nullptr;
2210 uint64_t adrp_addr = 0;
2211 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002212 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002213 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002214};
2215
2216// SymbolizerGetOpInfo() is the operand information call back function.
2217// This is called to get the symbolic information for operand(s) of an
2218// instruction when it is being done. This routine does this from
2219// the relocation information, symbol table, etc. That block of information
2220// is a pointer to the struct DisassembleInfo that was passed when the
2221// disassembler context was created and passed to back to here when
2222// called back by the disassembler for instruction operands that could have
2223// relocation information. The address of the instruction containing operand is
2224// at the Pc parameter. The immediate value the operand has is passed in
2225// op_info->Value and is at Offset past the start of the instruction and has a
2226// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2227// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2228// names and addends of the symbolic expression to add for the operand. The
2229// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2230// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002231static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2232 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002233 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2234 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002235 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002236
2237 // Make sure all fields returned are zero if we don't set them.
2238 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2239 op_info->Value = value;
2240
2241 // If the TagType is not the value 1 which it code knows about or if no
2242 // verbose symbolic information is wanted then just return 0, indicating no
2243 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002244 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002245 return 0;
2246
2247 unsigned int Arch = info->O->getArch();
2248 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002249 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2250 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002251 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2252 // TODO:
2253 // Search the external relocation entries of a fully linked image
2254 // (if any) for an entry that matches this segment offset.
2255 // uint32_t seg_offset = (Pc + Offset);
2256 return 0;
2257 }
2258 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2259 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002260 uint32_t sect_addr = info->S.getAddress();
2261 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2262 bool reloc_found = false;
2263 DataRefImpl Rel;
2264 MachO::any_relocation_info RE;
2265 bool isExtern = false;
2266 SymbolRef Symbol;
2267 bool r_scattered = false;
2268 uint32_t r_value, pair_r_value, r_type;
2269 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002270 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002271 if (RelocOffset == sect_offset) {
2272 Rel = Reloc.getRawDataRefImpl();
2273 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002274 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002275 r_scattered = info->O->isRelocationScattered(RE);
2276 if (r_scattered) {
2277 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002278 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2279 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2280 DataRefImpl RelNext = Rel;
2281 info->O->moveRelocationNext(RelNext);
2282 MachO::any_relocation_info RENext;
2283 RENext = info->O->getRelocation(RelNext);
2284 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002285 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002286 else
2287 return 0;
2288 }
2289 } else {
2290 isExtern = info->O->getPlainRelocationExternal(RE);
2291 if (isExtern) {
2292 symbol_iterator RelocSym = Reloc.getSymbol();
2293 Symbol = *RelocSym;
2294 }
2295 }
2296 reloc_found = true;
2297 break;
2298 }
2299 }
2300 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002301 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002302 if (!SymName)
2303 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002304 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002305 op_info->AddSymbol.Present = 1;
2306 op_info->AddSymbol.Name = name;
2307 // For i386 extern relocation entries the value in the instruction is
2308 // the offset from the symbol, and value is already set in op_info->Value.
2309 return 1;
2310 }
2311 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2312 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002313 const char *add = GuessSymbolName(r_value, info->AddrMap);
2314 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002315 uint32_t offset = value - (r_value - pair_r_value);
2316 op_info->AddSymbol.Present = 1;
2317 if (add != nullptr)
2318 op_info->AddSymbol.Name = add;
2319 else
2320 op_info->AddSymbol.Value = r_value;
2321 op_info->SubtractSymbol.Present = 1;
2322 if (sub != nullptr)
2323 op_info->SubtractSymbol.Name = sub;
2324 else
2325 op_info->SubtractSymbol.Value = pair_r_value;
2326 op_info->Value = offset;
2327 return 1;
2328 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002329 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002330 }
2331 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002332 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2333 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002334 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2335 // relocation entries of a linked image (if any) for an entry that matches
2336 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002337 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002338 uint64_t seg_offset = Pc + Offset;
2339 bool reloc_found = false;
2340 DataRefImpl Rel;
2341 MachO::any_relocation_info RE;
2342 bool isExtern = false;
2343 SymbolRef Symbol;
2344 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2345 uint64_t RelocOffset = Reloc.getOffset();
2346 if (RelocOffset == seg_offset) {
2347 Rel = Reloc.getRawDataRefImpl();
2348 RE = info->O->getRelocation(Rel);
2349 // external relocation entries should always be external.
2350 isExtern = info->O->getPlainRelocationExternal(RE);
2351 if (isExtern) {
2352 symbol_iterator RelocSym = Reloc.getSymbol();
2353 Symbol = *RelocSym;
2354 }
2355 reloc_found = true;
2356 break;
2357 }
2358 }
2359 if (reloc_found && isExtern) {
2360 // The Value passed in will be adjusted by the Pc if the instruction
2361 // adds the Pc. But for x86_64 external relocation entries the Value
2362 // is the offset from the external symbol.
2363 if (info->O->getAnyRelocationPCRel(RE))
2364 op_info->Value -= Pc + Offset + Size;
2365 Expected<StringRef> SymName = Symbol.getName();
2366 if (!SymName)
2367 report_error(info->O->getFileName(), SymName.takeError());
2368 const char *name = SymName->data();
2369 op_info->AddSymbol.Present = 1;
2370 op_info->AddSymbol.Name = name;
2371 return 1;
2372 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002373 return 0;
2374 }
2375 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2376 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002377 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002378 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2379 bool reloc_found = false;
2380 DataRefImpl Rel;
2381 MachO::any_relocation_info RE;
2382 bool isExtern = false;
2383 SymbolRef Symbol;
2384 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002385 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002386 if (RelocOffset == sect_offset) {
2387 Rel = Reloc.getRawDataRefImpl();
2388 RE = info->O->getRelocation(Rel);
2389 // NOTE: Scattered relocations don't exist on x86_64.
2390 isExtern = info->O->getPlainRelocationExternal(RE);
2391 if (isExtern) {
2392 symbol_iterator RelocSym = Reloc.getSymbol();
2393 Symbol = *RelocSym;
2394 }
2395 reloc_found = true;
2396 break;
2397 }
2398 }
2399 if (reloc_found && isExtern) {
2400 // The Value passed in will be adjusted by the Pc if the instruction
2401 // adds the Pc. But for x86_64 external relocation entries the Value
2402 // is the offset from the external symbol.
2403 if (info->O->getAnyRelocationPCRel(RE))
2404 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002405 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002406 if (!SymName)
2407 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002408 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002409 unsigned Type = info->O->getAnyRelocationType(RE);
2410 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2411 DataRefImpl RelNext = Rel;
2412 info->O->moveRelocationNext(RelNext);
2413 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2414 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2415 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2416 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2417 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2418 op_info->SubtractSymbol.Present = 1;
2419 op_info->SubtractSymbol.Name = name;
2420 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2421 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002422 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002423 if (!SymNameNext)
2424 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002425 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002426 }
2427 }
2428 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2429 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2430 op_info->AddSymbol.Present = 1;
2431 op_info->AddSymbol.Name = name;
2432 return 1;
2433 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002434 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002435 }
2436 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002437 if (Offset != 0 || (Size != 4 && Size != 2))
2438 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002439 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2440 // TODO:
2441 // Search the external relocation entries of a fully linked image
2442 // (if any) for an entry that matches this segment offset.
2443 // uint32_t seg_offset = (Pc + Offset);
2444 return 0;
2445 }
2446 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2447 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002448 uint32_t sect_addr = info->S.getAddress();
2449 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002450 DataRefImpl Rel;
2451 MachO::any_relocation_info RE;
2452 bool isExtern = false;
2453 SymbolRef Symbol;
2454 bool r_scattered = false;
2455 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002456 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002457 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2458 uint64_t RelocOffset = Reloc.getOffset();
2459 return RelocOffset == sect_offset;
2460 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002461
2462 if (Reloc == info->S.relocations().end())
2463 return 0;
2464
2465 Rel = Reloc->getRawDataRefImpl();
2466 RE = info->O->getRelocation(Rel);
2467 r_length = info->O->getAnyRelocationLength(RE);
2468 r_scattered = info->O->isRelocationScattered(RE);
2469 if (r_scattered) {
2470 r_value = info->O->getScatteredRelocationValue(RE);
2471 r_type = info->O->getScatteredRelocationType(RE);
2472 } else {
2473 r_type = info->O->getAnyRelocationType(RE);
2474 isExtern = info->O->getPlainRelocationExternal(RE);
2475 if (isExtern) {
2476 symbol_iterator RelocSym = Reloc->getSymbol();
2477 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002478 }
2479 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002480 if (r_type == MachO::ARM_RELOC_HALF ||
2481 r_type == MachO::ARM_RELOC_SECTDIFF ||
2482 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2483 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2484 DataRefImpl RelNext = Rel;
2485 info->O->moveRelocationNext(RelNext);
2486 MachO::any_relocation_info RENext;
2487 RENext = info->O->getRelocation(RelNext);
2488 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2489 if (info->O->isRelocationScattered(RENext))
2490 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2491 }
2492
2493 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002494 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002495 if (!SymName)
2496 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002497 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002498 op_info->AddSymbol.Present = 1;
2499 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002500 switch (r_type) {
2501 case MachO::ARM_RELOC_HALF:
2502 if ((r_length & 0x1) == 1) {
2503 op_info->Value = value << 16 | other_half;
2504 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2505 } else {
2506 op_info->Value = other_half << 16 | value;
2507 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002508 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002509 break;
2510 default:
2511 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002512 }
2513 return 1;
2514 }
2515 // If we have a branch that is not an external relocation entry then
2516 // return 0 so the code in tryAddingSymbolicOperand() can use the
2517 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002518 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002519 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2520 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002521 return 0;
2522
2523 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002524 if (r_type == MachO::ARM_RELOC_HALF ||
2525 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2526 if ((r_length & 0x1) == 1)
2527 value = value << 16 | other_half;
2528 else
2529 value = other_half << 16 | value;
2530 }
2531 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2532 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2533 offset = value - r_value;
2534 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002535 }
2536
David Blaikie33dd45d02015-03-23 18:39:02 +00002537 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002538 if ((r_length & 0x1) == 1)
2539 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2540 else
2541 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002542 const char *add = GuessSymbolName(r_value, info->AddrMap);
2543 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002544 int32_t offset = value - (r_value - pair_r_value);
2545 op_info->AddSymbol.Present = 1;
2546 if (add != nullptr)
2547 op_info->AddSymbol.Name = add;
2548 else
2549 op_info->AddSymbol.Value = r_value;
2550 op_info->SubtractSymbol.Present = 1;
2551 if (sub != nullptr)
2552 op_info->SubtractSymbol.Name = sub;
2553 else
2554 op_info->SubtractSymbol.Value = pair_r_value;
2555 op_info->Value = offset;
2556 return 1;
2557 }
2558
Kevin Enderby930fdc72014-11-06 19:00:13 +00002559 op_info->AddSymbol.Present = 1;
2560 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002561 if (r_type == MachO::ARM_RELOC_HALF) {
2562 if ((r_length & 0x1) == 1)
2563 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2564 else
2565 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002566 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002567 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002568 if (add != nullptr) {
2569 op_info->AddSymbol.Name = add;
2570 return 1;
2571 }
2572 op_info->AddSymbol.Value = value;
2573 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002574 }
2575 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002576 if (Offset != 0 || Size != 4)
2577 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002578 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2579 // TODO:
2580 // Search the external relocation entries of a fully linked image
2581 // (if any) for an entry that matches this segment offset.
2582 // uint64_t seg_offset = (Pc + Offset);
2583 return 0;
2584 }
2585 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2586 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002587 uint64_t sect_addr = info->S.getAddress();
2588 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002589 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002590 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2591 uint64_t RelocOffset = Reloc.getOffset();
2592 return RelocOffset == sect_offset;
2593 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002594
David Blaikie33dd45d02015-03-23 18:39:02 +00002595 if (Reloc == info->S.relocations().end())
2596 return 0;
2597
2598 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2599 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2600 uint32_t r_type = info->O->getAnyRelocationType(RE);
2601 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2602 DataRefImpl RelNext = Rel;
2603 info->O->moveRelocationNext(RelNext);
2604 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2605 if (value == 0) {
2606 value = info->O->getPlainRelocationSymbolNum(RENext);
2607 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002608 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002609 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002610 // NOTE: Scattered relocations don't exist on arm64.
2611 if (!info->O->getPlainRelocationExternal(RE))
2612 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002613 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002614 if (!SymName)
2615 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002616 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002617 op_info->AddSymbol.Present = 1;
2618 op_info->AddSymbol.Name = name;
2619
2620 switch (r_type) {
2621 case MachO::ARM64_RELOC_PAGE21:
2622 /* @page */
2623 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2624 break;
2625 case MachO::ARM64_RELOC_PAGEOFF12:
2626 /* @pageoff */
2627 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2628 break;
2629 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2630 /* @gotpage */
2631 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2632 break;
2633 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2634 /* @gotpageoff */
2635 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2636 break;
2637 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2638 /* @tvlppage is not implemented in llvm-mc */
2639 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2640 break;
2641 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2642 /* @tvlppageoff is not implemented in llvm-mc */
2643 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2644 break;
2645 default:
2646 case MachO::ARM64_RELOC_BRANCH26:
2647 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2648 break;
2649 }
2650 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002651 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002652 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002653}
2654
Kevin Enderbybf246f52014-09-24 23:08:22 +00002655// GuessCstringPointer is passed the address of what might be a pointer to a
2656// literal string in a cstring section. If that address is in a cstring section
2657// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002658static const char *GuessCstringPointer(uint64_t ReferenceValue,
2659 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002660 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002661 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2662 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2663 for (unsigned J = 0; J < Seg.nsects; ++J) {
2664 MachO::section_64 Sec = info->O->getSection64(Load, J);
2665 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2666 if (section_type == MachO::S_CSTRING_LITERALS &&
2667 ReferenceValue >= Sec.addr &&
2668 ReferenceValue < Sec.addr + Sec.size) {
2669 uint64_t sect_offset = ReferenceValue - Sec.addr;
2670 uint64_t object_offset = Sec.offset + sect_offset;
2671 StringRef MachOContents = info->O->getData();
2672 uint64_t object_size = MachOContents.size();
2673 const char *object_addr = (const char *)MachOContents.data();
2674 if (object_offset < object_size) {
2675 const char *name = object_addr + object_offset;
2676 return name;
2677 } else {
2678 return nullptr;
2679 }
2680 }
2681 }
2682 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2683 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2684 for (unsigned J = 0; J < Seg.nsects; ++J) {
2685 MachO::section Sec = info->O->getSection(Load, J);
2686 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2687 if (section_type == MachO::S_CSTRING_LITERALS &&
2688 ReferenceValue >= Sec.addr &&
2689 ReferenceValue < Sec.addr + Sec.size) {
2690 uint64_t sect_offset = ReferenceValue - Sec.addr;
2691 uint64_t object_offset = Sec.offset + sect_offset;
2692 StringRef MachOContents = info->O->getData();
2693 uint64_t object_size = MachOContents.size();
2694 const char *object_addr = (const char *)MachOContents.data();
2695 if (object_offset < object_size) {
2696 const char *name = object_addr + object_offset;
2697 return name;
2698 } else {
2699 return nullptr;
2700 }
2701 }
2702 }
2703 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002704 }
2705 return nullptr;
2706}
2707
Kevin Enderby85974882014-09-26 22:20:44 +00002708// GuessIndirectSymbol returns the name of the indirect symbol for the
2709// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2710// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2711// symbol name being referenced by the stub or pointer.
2712static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2713 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002714 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2715 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002716 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002717 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2718 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2719 for (unsigned J = 0; J < Seg.nsects; ++J) {
2720 MachO::section_64 Sec = info->O->getSection64(Load, J);
2721 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2722 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2723 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2724 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2725 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2726 section_type == MachO::S_SYMBOL_STUBS) &&
2727 ReferenceValue >= Sec.addr &&
2728 ReferenceValue < Sec.addr + Sec.size) {
2729 uint32_t stride;
2730 if (section_type == MachO::S_SYMBOL_STUBS)
2731 stride = Sec.reserved2;
2732 else
2733 stride = 8;
2734 if (stride == 0)
2735 return nullptr;
2736 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2737 if (index < Dysymtab.nindirectsyms) {
2738 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002739 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002740 if (indirect_symbol < Symtab.nsyms) {
2741 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2742 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002743 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002744 if (!SymName)
2745 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002746 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002747 return name;
2748 }
2749 }
2750 }
2751 }
2752 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2753 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2754 for (unsigned J = 0; J < Seg.nsects; ++J) {
2755 MachO::section Sec = info->O->getSection(Load, J);
2756 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2757 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2758 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2759 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2760 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2761 section_type == MachO::S_SYMBOL_STUBS) &&
2762 ReferenceValue >= Sec.addr &&
2763 ReferenceValue < Sec.addr + Sec.size) {
2764 uint32_t stride;
2765 if (section_type == MachO::S_SYMBOL_STUBS)
2766 stride = Sec.reserved2;
2767 else
2768 stride = 4;
2769 if (stride == 0)
2770 return nullptr;
2771 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2772 if (index < Dysymtab.nindirectsyms) {
2773 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002774 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002775 if (indirect_symbol < Symtab.nsyms) {
2776 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2777 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002778 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002779 if (!SymName)
2780 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002781 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002782 return name;
2783 }
2784 }
2785 }
2786 }
2787 }
Kevin Enderby85974882014-09-26 22:20:44 +00002788 }
2789 return nullptr;
2790}
2791
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002792// method_reference() is called passing it the ReferenceName that might be
2793// a reference it to an Objective-C method call. If so then it allocates and
2794// assembles a method call string with the values last seen and saved in
2795// the DisassembleInfo's class_name and selector_name fields. This is saved
2796// into the method field of the info and any previous string is free'ed.
2797// Then the class_name field in the info is set to nullptr. The method call
2798// string is set into ReferenceName and ReferenceType is set to
2799// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2800// then both ReferenceType and ReferenceName are left unchanged.
2801static void method_reference(struct DisassembleInfo *info,
2802 uint64_t *ReferenceType,
2803 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002804 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002805 if (*ReferenceName != nullptr) {
2806 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002807 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002808 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002809 info->method = llvm::make_unique<char[]>(
2810 5 + strlen(info->class_name) + strlen(info->selector_name));
2811 char *method = info->method.get();
2812 if (method != nullptr) {
2813 strcpy(method, "+[");
2814 strcat(method, info->class_name);
2815 strcat(method, " ");
2816 strcat(method, info->selector_name);
2817 strcat(method, "]");
2818 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002819 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2820 }
2821 } else {
David Blaikie0e550682018-02-20 18:48:51 +00002822 info->method =
2823 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
2824 char *method = info->method.get();
2825 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002826 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002827 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002828 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002829 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002830 else
David Blaikie0e550682018-02-20 18:48:51 +00002831 strcpy(method, "-[r? ");
2832 strcat(method, info->selector_name);
2833 strcat(method, "]");
2834 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002835 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2836 }
2837 }
2838 info->class_name = nullptr;
2839 }
2840 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002841 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002842 info->method =
2843 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
2844 char *method = info->method.get();
2845 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002846 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002847 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002848 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002849 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002850 else
David Blaikie0e550682018-02-20 18:48:51 +00002851 strcpy(method, "-[[r? super] ");
2852 strcat(method, info->selector_name);
2853 strcat(method, "]");
2854 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002855 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2856 }
2857 info->class_name = nullptr;
2858 }
2859 }
2860 }
2861}
2862
2863// GuessPointerPointer() is passed the address of what might be a pointer to
2864// a reference to an Objective-C class, selector, message ref or cfstring.
2865// If so the value of the pointer is returned and one of the booleans are set
2866// to true. If not zero is returned and all the booleans are set to false.
2867static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2868 struct DisassembleInfo *info,
2869 bool &classref, bool &selref, bool &msgref,
2870 bool &cfstring) {
2871 classref = false;
2872 selref = false;
2873 msgref = false;
2874 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002875 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002876 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2877 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2878 for (unsigned J = 0; J < Seg.nsects; ++J) {
2879 MachO::section_64 Sec = info->O->getSection64(Load, J);
2880 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2881 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2882 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2883 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2884 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2885 ReferenceValue >= Sec.addr &&
2886 ReferenceValue < Sec.addr + Sec.size) {
2887 uint64_t sect_offset = ReferenceValue - Sec.addr;
2888 uint64_t object_offset = Sec.offset + sect_offset;
2889 StringRef MachOContents = info->O->getData();
2890 uint64_t object_size = MachOContents.size();
2891 const char *object_addr = (const char *)MachOContents.data();
2892 if (object_offset < object_size) {
2893 uint64_t pointer_value;
2894 memcpy(&pointer_value, object_addr + object_offset,
2895 sizeof(uint64_t));
2896 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2897 sys::swapByteOrder(pointer_value);
2898 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2899 selref = true;
2900 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2901 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2902 classref = true;
2903 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2904 ReferenceValue + 8 < Sec.addr + Sec.size) {
2905 msgref = true;
2906 memcpy(&pointer_value, object_addr + object_offset + 8,
2907 sizeof(uint64_t));
2908 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2909 sys::swapByteOrder(pointer_value);
2910 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2911 cfstring = true;
2912 return pointer_value;
2913 } else {
2914 return 0;
2915 }
2916 }
2917 }
2918 }
2919 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002920 }
2921 return 0;
2922}
2923
2924// get_pointer_64 returns a pointer to the bytes in the object file at the
2925// Address from a section in the Mach-O file. And indirectly returns the
2926// offset into the section, number of bytes left in the section past the offset
2927// and which section is was being referenced. If the Address is not in a
2928// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002929static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2930 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002931 DisassembleInfo *info,
2932 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002933 offset = 0;
2934 left = 0;
2935 S = SectionRef();
2936 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2937 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2938 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002939 if (SectSize == 0)
2940 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002941 if (objc_only) {
2942 StringRef SectName;
2943 ((*(info->Sections))[SectIdx]).getName(SectName);
2944 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2945 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2946 if (SegName != "__OBJC" && SectName != "__cstring")
2947 continue;
2948 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002949 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2950 S = (*(info->Sections))[SectIdx];
2951 offset = Address - SectAddress;
2952 left = SectSize - offset;
2953 StringRef SectContents;
2954 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2955 return SectContents.data() + offset;
2956 }
2957 }
2958 return nullptr;
2959}
2960
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002961static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2962 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002963 DisassembleInfo *info,
2964 bool objc_only = false) {
2965 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002966}
2967
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002968// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2969// the symbol indirectly through n_value. Based on the relocation information
2970// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002971// If no relocation information is found and a non-zero ReferenceValue for the
2972// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002973static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2974 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002975 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002976 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002977 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002978 return nullptr;
2979
2980 // See if there is an external relocation entry at the sect_offset.
2981 bool reloc_found = false;
2982 DataRefImpl Rel;
2983 MachO::any_relocation_info RE;
2984 bool isExtern = false;
2985 SymbolRef Symbol;
2986 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002987 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002988 if (RelocOffset == sect_offset) {
2989 Rel = Reloc.getRawDataRefImpl();
2990 RE = info->O->getRelocation(Rel);
2991 if (info->O->isRelocationScattered(RE))
2992 continue;
2993 isExtern = info->O->getPlainRelocationExternal(RE);
2994 if (isExtern) {
2995 symbol_iterator RelocSym = Reloc.getSymbol();
2996 Symbol = *RelocSym;
2997 }
2998 reloc_found = true;
2999 break;
3000 }
3001 }
3002 // If there is an external relocation entry for a symbol in this section
3003 // at this section_offset then use that symbol's value for the n_value
3004 // and return its name.
3005 const char *SymbolName = nullptr;
3006 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003007 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003008 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003009 if (!NameOrError)
3010 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003011 StringRef Name = *NameOrError;
3012 if (!Name.empty()) {
3013 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003014 return SymbolName;
3015 }
3016 }
3017
3018 // TODO: For fully linked images, look through the external relocation
3019 // entries off the dynamic symtab command. For these the r_offset is from the
3020 // start of the first writeable segment in the Mach-O file. So the offset
3021 // to this section from that segment is passed to this routine by the caller,
3022 // as the database_offset. Which is the difference of the section's starting
3023 // address and the first writable segment.
3024 //
3025 // NOTE: need add passing the database_offset to this routine.
3026
Kevin Enderby0fc11822015-04-01 20:57:01 +00003027 // We did not find an external relocation entry so look up the ReferenceValue
3028 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003029 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003030
3031 return SymbolName;
3032}
3033
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003034static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3035 DisassembleInfo *info,
3036 uint32_t ReferenceValue) {
3037 uint64_t n_value64;
3038 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3039}
3040
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003041// These are structs in the Objective-C meta data and read to produce the
3042// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003043// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3044// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003045
3046// The cfstring object in a 64-bit Mach-O file.
3047struct cfstring64_t {
3048 uint64_t isa; // class64_t * (64-bit pointer)
3049 uint64_t flags; // flag bits
3050 uint64_t characters; // char * (64-bit pointer)
3051 uint64_t length; // number of non-NULL characters in above
3052};
3053
3054// The class object in a 64-bit Mach-O file.
3055struct class64_t {
3056 uint64_t isa; // class64_t * (64-bit pointer)
3057 uint64_t superclass; // class64_t * (64-bit pointer)
3058 uint64_t cache; // Cache (64-bit pointer)
3059 uint64_t vtable; // IMP * (64-bit pointer)
3060 uint64_t data; // class_ro64_t * (64-bit pointer)
3061};
3062
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003063struct class32_t {
3064 uint32_t isa; /* class32_t * (32-bit pointer) */
3065 uint32_t superclass; /* class32_t * (32-bit pointer) */
3066 uint32_t cache; /* Cache (32-bit pointer) */
3067 uint32_t vtable; /* IMP * (32-bit pointer) */
3068 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3069};
3070
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003071struct class_ro64_t {
3072 uint32_t flags;
3073 uint32_t instanceStart;
3074 uint32_t instanceSize;
3075 uint32_t reserved;
3076 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3077 uint64_t name; // const char * (64-bit pointer)
3078 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3079 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3080 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3081 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3082 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3083};
3084
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003085struct class_ro32_t {
3086 uint32_t flags;
3087 uint32_t instanceStart;
3088 uint32_t instanceSize;
3089 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3090 uint32_t name; /* const char * (32-bit pointer) */
3091 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3092 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3093 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3094 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3095 uint32_t baseProperties; /* const struct objc_property_list *
3096 (32-bit pointer) */
3097};
3098
3099/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003100#define RO_META (1 << 0)
3101#define RO_ROOT (1 << 1)
3102#define RO_HAS_CXX_STRUCTORS (1 << 2)
3103
3104struct method_list64_t {
3105 uint32_t entsize;
3106 uint32_t count;
3107 /* struct method64_t first; These structures follow inline */
3108};
3109
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003110struct method_list32_t {
3111 uint32_t entsize;
3112 uint32_t count;
3113 /* struct method32_t first; These structures follow inline */
3114};
3115
Kevin Enderby0fc11822015-04-01 20:57:01 +00003116struct method64_t {
3117 uint64_t name; /* SEL (64-bit pointer) */
3118 uint64_t types; /* const char * (64-bit pointer) */
3119 uint64_t imp; /* IMP (64-bit pointer) */
3120};
3121
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003122struct method32_t {
3123 uint32_t name; /* SEL (32-bit pointer) */
3124 uint32_t types; /* const char * (32-bit pointer) */
3125 uint32_t imp; /* IMP (32-bit pointer) */
3126};
3127
Kevin Enderby0fc11822015-04-01 20:57:01 +00003128struct protocol_list64_t {
3129 uint64_t count; /* uintptr_t (a 64-bit value) */
3130 /* struct protocol64_t * list[0]; These pointers follow inline */
3131};
3132
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003133struct protocol_list32_t {
3134 uint32_t count; /* uintptr_t (a 32-bit value) */
3135 /* struct protocol32_t * list[0]; These pointers follow inline */
3136};
3137
Kevin Enderby0fc11822015-04-01 20:57:01 +00003138struct protocol64_t {
3139 uint64_t isa; /* id * (64-bit pointer) */
3140 uint64_t name; /* const char * (64-bit pointer) */
3141 uint64_t protocols; /* struct protocol_list64_t *
3142 (64-bit pointer) */
3143 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3144 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3145 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3146 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3147 uint64_t instanceProperties; /* struct objc_property_list *
3148 (64-bit pointer) */
3149};
3150
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003151struct protocol32_t {
3152 uint32_t isa; /* id * (32-bit pointer) */
3153 uint32_t name; /* const char * (32-bit pointer) */
3154 uint32_t protocols; /* struct protocol_list_t *
3155 (32-bit pointer) */
3156 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3157 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3158 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3159 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3160 uint32_t instanceProperties; /* struct objc_property_list *
3161 (32-bit pointer) */
3162};
3163
Kevin Enderby0fc11822015-04-01 20:57:01 +00003164struct ivar_list64_t {
3165 uint32_t entsize;
3166 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003167 /* struct ivar64_t first; These structures follow inline */
3168};
3169
3170struct ivar_list32_t {
3171 uint32_t entsize;
3172 uint32_t count;
3173 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003174};
3175
3176struct ivar64_t {
3177 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3178 uint64_t name; /* const char * (64-bit pointer) */
3179 uint64_t type; /* const char * (64-bit pointer) */
3180 uint32_t alignment;
3181 uint32_t size;
3182};
3183
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003184struct ivar32_t {
3185 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3186 uint32_t name; /* const char * (32-bit pointer) */
3187 uint32_t type; /* const char * (32-bit pointer) */
3188 uint32_t alignment;
3189 uint32_t size;
3190};
3191
Kevin Enderby0fc11822015-04-01 20:57:01 +00003192struct objc_property_list64 {
3193 uint32_t entsize;
3194 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003195 /* struct objc_property64 first; These structures follow inline */
3196};
3197
3198struct objc_property_list32 {
3199 uint32_t entsize;
3200 uint32_t count;
3201 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003202};
3203
3204struct objc_property64 {
3205 uint64_t name; /* const char * (64-bit pointer) */
3206 uint64_t attributes; /* const char * (64-bit pointer) */
3207};
3208
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003209struct objc_property32 {
3210 uint32_t name; /* const char * (32-bit pointer) */
3211 uint32_t attributes; /* const char * (32-bit pointer) */
3212};
3213
Kevin Enderby0fc11822015-04-01 20:57:01 +00003214struct category64_t {
3215 uint64_t name; /* const char * (64-bit pointer) */
3216 uint64_t cls; /* struct class_t * (64-bit pointer) */
3217 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3218 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3219 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3220 uint64_t instanceProperties; /* struct objc_property_list *
3221 (64-bit pointer) */
3222};
3223
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003224struct category32_t {
3225 uint32_t name; /* const char * (32-bit pointer) */
3226 uint32_t cls; /* struct class_t * (32-bit pointer) */
3227 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3228 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3229 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3230 uint32_t instanceProperties; /* struct objc_property_list *
3231 (32-bit pointer) */
3232};
3233
Kevin Enderby0fc11822015-04-01 20:57:01 +00003234struct objc_image_info64 {
3235 uint32_t version;
3236 uint32_t flags;
3237};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003238struct objc_image_info32 {
3239 uint32_t version;
3240 uint32_t flags;
3241};
Kevin Enderby846c0002015-04-16 17:19:59 +00003242struct imageInfo_t {
3243 uint32_t version;
3244 uint32_t flags;
3245};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003246/* masks for objc_image_info.flags */
3247#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3248#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003249#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3250#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003251
3252struct message_ref64 {
3253 uint64_t imp; /* IMP (64-bit pointer) */
3254 uint64_t sel; /* SEL (64-bit pointer) */
3255};
3256
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003257struct message_ref32 {
3258 uint32_t imp; /* IMP (32-bit pointer) */
3259 uint32_t sel; /* SEL (32-bit pointer) */
3260};
3261
Kevin Enderby846c0002015-04-16 17:19:59 +00003262// Objective-C 1 (32-bit only) meta data structs.
3263
3264struct objc_module_t {
3265 uint32_t version;
3266 uint32_t size;
3267 uint32_t name; /* char * (32-bit pointer) */
3268 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3269};
3270
3271struct objc_symtab_t {
3272 uint32_t sel_ref_cnt;
3273 uint32_t refs; /* SEL * (32-bit pointer) */
3274 uint16_t cls_def_cnt;
3275 uint16_t cat_def_cnt;
3276 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3277};
3278
3279struct objc_class_t {
3280 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3281 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3282 uint32_t name; /* const char * (32-bit pointer) */
3283 int32_t version;
3284 int32_t info;
3285 int32_t instance_size;
3286 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3287 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3288 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3289 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3290};
3291
3292#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3293// class is not a metaclass
3294#define CLS_CLASS 0x1
3295// class is a metaclass
3296#define CLS_META 0x2
3297
3298struct objc_category_t {
3299 uint32_t category_name; /* char * (32-bit pointer) */
3300 uint32_t class_name; /* char * (32-bit pointer) */
3301 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3302 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3303 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3304};
3305
3306struct objc_ivar_t {
3307 uint32_t ivar_name; /* char * (32-bit pointer) */
3308 uint32_t ivar_type; /* char * (32-bit pointer) */
3309 int32_t ivar_offset;
3310};
3311
3312struct objc_ivar_list_t {
3313 int32_t ivar_count;
3314 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3315};
3316
3317struct objc_method_list_t {
3318 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3319 int32_t method_count;
3320 // struct objc_method_t method_list[1]; /* variable length structure */
3321};
3322
3323struct objc_method_t {
3324 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3325 uint32_t method_types; /* char * (32-bit pointer) */
3326 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3327 (32-bit pointer) */
3328};
3329
3330struct objc_protocol_list_t {
3331 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3332 int32_t count;
3333 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3334 // (32-bit pointer) */
3335};
3336
3337struct objc_protocol_t {
3338 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3339 uint32_t protocol_name; /* char * (32-bit pointer) */
3340 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3341 uint32_t instance_methods; /* struct objc_method_description_list *
3342 (32-bit pointer) */
3343 uint32_t class_methods; /* struct objc_method_description_list *
3344 (32-bit pointer) */
3345};
3346
3347struct objc_method_description_list_t {
3348 int32_t count;
3349 // struct objc_method_description_t list[1];
3350};
3351
3352struct objc_method_description_t {
3353 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3354 uint32_t types; /* char * (32-bit pointer) */
3355};
3356
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003357inline void swapStruct(struct cfstring64_t &cfs) {
3358 sys::swapByteOrder(cfs.isa);
3359 sys::swapByteOrder(cfs.flags);
3360 sys::swapByteOrder(cfs.characters);
3361 sys::swapByteOrder(cfs.length);
3362}
3363
3364inline void swapStruct(struct class64_t &c) {
3365 sys::swapByteOrder(c.isa);
3366 sys::swapByteOrder(c.superclass);
3367 sys::swapByteOrder(c.cache);
3368 sys::swapByteOrder(c.vtable);
3369 sys::swapByteOrder(c.data);
3370}
3371
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003372inline void swapStruct(struct class32_t &c) {
3373 sys::swapByteOrder(c.isa);
3374 sys::swapByteOrder(c.superclass);
3375 sys::swapByteOrder(c.cache);
3376 sys::swapByteOrder(c.vtable);
3377 sys::swapByteOrder(c.data);
3378}
3379
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003380inline void swapStruct(struct class_ro64_t &cro) {
3381 sys::swapByteOrder(cro.flags);
3382 sys::swapByteOrder(cro.instanceStart);
3383 sys::swapByteOrder(cro.instanceSize);
3384 sys::swapByteOrder(cro.reserved);
3385 sys::swapByteOrder(cro.ivarLayout);
3386 sys::swapByteOrder(cro.name);
3387 sys::swapByteOrder(cro.baseMethods);
3388 sys::swapByteOrder(cro.baseProtocols);
3389 sys::swapByteOrder(cro.ivars);
3390 sys::swapByteOrder(cro.weakIvarLayout);
3391 sys::swapByteOrder(cro.baseProperties);
3392}
3393
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003394inline void swapStruct(struct class_ro32_t &cro) {
3395 sys::swapByteOrder(cro.flags);
3396 sys::swapByteOrder(cro.instanceStart);
3397 sys::swapByteOrder(cro.instanceSize);
3398 sys::swapByteOrder(cro.ivarLayout);
3399 sys::swapByteOrder(cro.name);
3400 sys::swapByteOrder(cro.baseMethods);
3401 sys::swapByteOrder(cro.baseProtocols);
3402 sys::swapByteOrder(cro.ivars);
3403 sys::swapByteOrder(cro.weakIvarLayout);
3404 sys::swapByteOrder(cro.baseProperties);
3405}
3406
Kevin Enderby0fc11822015-04-01 20:57:01 +00003407inline void swapStruct(struct method_list64_t &ml) {
3408 sys::swapByteOrder(ml.entsize);
3409 sys::swapByteOrder(ml.count);
3410}
3411
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003412inline void swapStruct(struct method_list32_t &ml) {
3413 sys::swapByteOrder(ml.entsize);
3414 sys::swapByteOrder(ml.count);
3415}
3416
Kevin Enderby0fc11822015-04-01 20:57:01 +00003417inline void swapStruct(struct method64_t &m) {
3418 sys::swapByteOrder(m.name);
3419 sys::swapByteOrder(m.types);
3420 sys::swapByteOrder(m.imp);
3421}
3422
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003423inline void swapStruct(struct method32_t &m) {
3424 sys::swapByteOrder(m.name);
3425 sys::swapByteOrder(m.types);
3426 sys::swapByteOrder(m.imp);
3427}
3428
Kevin Enderby0fc11822015-04-01 20:57:01 +00003429inline void swapStruct(struct protocol_list64_t &pl) {
3430 sys::swapByteOrder(pl.count);
3431}
3432
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003433inline void swapStruct(struct protocol_list32_t &pl) {
3434 sys::swapByteOrder(pl.count);
3435}
3436
Kevin Enderby0fc11822015-04-01 20:57:01 +00003437inline void swapStruct(struct protocol64_t &p) {
3438 sys::swapByteOrder(p.isa);
3439 sys::swapByteOrder(p.name);
3440 sys::swapByteOrder(p.protocols);
3441 sys::swapByteOrder(p.instanceMethods);
3442 sys::swapByteOrder(p.classMethods);
3443 sys::swapByteOrder(p.optionalInstanceMethods);
3444 sys::swapByteOrder(p.optionalClassMethods);
3445 sys::swapByteOrder(p.instanceProperties);
3446}
3447
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003448inline void swapStruct(struct protocol32_t &p) {
3449 sys::swapByteOrder(p.isa);
3450 sys::swapByteOrder(p.name);
3451 sys::swapByteOrder(p.protocols);
3452 sys::swapByteOrder(p.instanceMethods);
3453 sys::swapByteOrder(p.classMethods);
3454 sys::swapByteOrder(p.optionalInstanceMethods);
3455 sys::swapByteOrder(p.optionalClassMethods);
3456 sys::swapByteOrder(p.instanceProperties);
3457}
3458
Kevin Enderby0fc11822015-04-01 20:57:01 +00003459inline void swapStruct(struct ivar_list64_t &il) {
3460 sys::swapByteOrder(il.entsize);
3461 sys::swapByteOrder(il.count);
3462}
3463
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003464inline void swapStruct(struct ivar_list32_t &il) {
3465 sys::swapByteOrder(il.entsize);
3466 sys::swapByteOrder(il.count);
3467}
3468
Kevin Enderby0fc11822015-04-01 20:57:01 +00003469inline void swapStruct(struct ivar64_t &i) {
3470 sys::swapByteOrder(i.offset);
3471 sys::swapByteOrder(i.name);
3472 sys::swapByteOrder(i.type);
3473 sys::swapByteOrder(i.alignment);
3474 sys::swapByteOrder(i.size);
3475}
3476
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003477inline void swapStruct(struct ivar32_t &i) {
3478 sys::swapByteOrder(i.offset);
3479 sys::swapByteOrder(i.name);
3480 sys::swapByteOrder(i.type);
3481 sys::swapByteOrder(i.alignment);
3482 sys::swapByteOrder(i.size);
3483}
3484
Kevin Enderby0fc11822015-04-01 20:57:01 +00003485inline void swapStruct(struct objc_property_list64 &pl) {
3486 sys::swapByteOrder(pl.entsize);
3487 sys::swapByteOrder(pl.count);
3488}
3489
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003490inline void swapStruct(struct objc_property_list32 &pl) {
3491 sys::swapByteOrder(pl.entsize);
3492 sys::swapByteOrder(pl.count);
3493}
3494
Kevin Enderby0fc11822015-04-01 20:57:01 +00003495inline void swapStruct(struct objc_property64 &op) {
3496 sys::swapByteOrder(op.name);
3497 sys::swapByteOrder(op.attributes);
3498}
3499
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003500inline void swapStruct(struct objc_property32 &op) {
3501 sys::swapByteOrder(op.name);
3502 sys::swapByteOrder(op.attributes);
3503}
3504
Kevin Enderby0fc11822015-04-01 20:57:01 +00003505inline void swapStruct(struct category64_t &c) {
3506 sys::swapByteOrder(c.name);
3507 sys::swapByteOrder(c.cls);
3508 sys::swapByteOrder(c.instanceMethods);
3509 sys::swapByteOrder(c.classMethods);
3510 sys::swapByteOrder(c.protocols);
3511 sys::swapByteOrder(c.instanceProperties);
3512}
3513
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003514inline void swapStruct(struct category32_t &c) {
3515 sys::swapByteOrder(c.name);
3516 sys::swapByteOrder(c.cls);
3517 sys::swapByteOrder(c.instanceMethods);
3518 sys::swapByteOrder(c.classMethods);
3519 sys::swapByteOrder(c.protocols);
3520 sys::swapByteOrder(c.instanceProperties);
3521}
3522
Kevin Enderby0fc11822015-04-01 20:57:01 +00003523inline void swapStruct(struct objc_image_info64 &o) {
3524 sys::swapByteOrder(o.version);
3525 sys::swapByteOrder(o.flags);
3526}
3527
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003528inline void swapStruct(struct objc_image_info32 &o) {
3529 sys::swapByteOrder(o.version);
3530 sys::swapByteOrder(o.flags);
3531}
3532
Kevin Enderby846c0002015-04-16 17:19:59 +00003533inline void swapStruct(struct imageInfo_t &o) {
3534 sys::swapByteOrder(o.version);
3535 sys::swapByteOrder(o.flags);
3536}
3537
Kevin Enderby0fc11822015-04-01 20:57:01 +00003538inline void swapStruct(struct message_ref64 &mr) {
3539 sys::swapByteOrder(mr.imp);
3540 sys::swapByteOrder(mr.sel);
3541}
3542
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003543inline void swapStruct(struct message_ref32 &mr) {
3544 sys::swapByteOrder(mr.imp);
3545 sys::swapByteOrder(mr.sel);
3546}
3547
Kevin Enderby846c0002015-04-16 17:19:59 +00003548inline void swapStruct(struct objc_module_t &module) {
3549 sys::swapByteOrder(module.version);
3550 sys::swapByteOrder(module.size);
3551 sys::swapByteOrder(module.name);
3552 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003553}
Kevin Enderby846c0002015-04-16 17:19:59 +00003554
3555inline void swapStruct(struct objc_symtab_t &symtab) {
3556 sys::swapByteOrder(symtab.sel_ref_cnt);
3557 sys::swapByteOrder(symtab.refs);
3558 sys::swapByteOrder(symtab.cls_def_cnt);
3559 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003560}
Kevin Enderby846c0002015-04-16 17:19:59 +00003561
3562inline void swapStruct(struct objc_class_t &objc_class) {
3563 sys::swapByteOrder(objc_class.isa);
3564 sys::swapByteOrder(objc_class.super_class);
3565 sys::swapByteOrder(objc_class.name);
3566 sys::swapByteOrder(objc_class.version);
3567 sys::swapByteOrder(objc_class.info);
3568 sys::swapByteOrder(objc_class.instance_size);
3569 sys::swapByteOrder(objc_class.ivars);
3570 sys::swapByteOrder(objc_class.methodLists);
3571 sys::swapByteOrder(objc_class.cache);
3572 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003573}
Kevin Enderby846c0002015-04-16 17:19:59 +00003574
3575inline void swapStruct(struct objc_category_t &objc_category) {
3576 sys::swapByteOrder(objc_category.category_name);
3577 sys::swapByteOrder(objc_category.class_name);
3578 sys::swapByteOrder(objc_category.instance_methods);
3579 sys::swapByteOrder(objc_category.class_methods);
3580 sys::swapByteOrder(objc_category.protocols);
3581}
3582
3583inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3584 sys::swapByteOrder(objc_ivar_list.ivar_count);
3585}
3586
3587inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3588 sys::swapByteOrder(objc_ivar.ivar_name);
3589 sys::swapByteOrder(objc_ivar.ivar_type);
3590 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003591}
Kevin Enderby846c0002015-04-16 17:19:59 +00003592
3593inline void swapStruct(struct objc_method_list_t &method_list) {
3594 sys::swapByteOrder(method_list.obsolete);
3595 sys::swapByteOrder(method_list.method_count);
3596}
3597
3598inline void swapStruct(struct objc_method_t &method) {
3599 sys::swapByteOrder(method.method_name);
3600 sys::swapByteOrder(method.method_types);
3601 sys::swapByteOrder(method.method_imp);
3602}
3603
3604inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3605 sys::swapByteOrder(protocol_list.next);
3606 sys::swapByteOrder(protocol_list.count);
3607}
3608
3609inline void swapStruct(struct objc_protocol_t &protocol) {
3610 sys::swapByteOrder(protocol.isa);
3611 sys::swapByteOrder(protocol.protocol_name);
3612 sys::swapByteOrder(protocol.protocol_list);
3613 sys::swapByteOrder(protocol.instance_methods);
3614 sys::swapByteOrder(protocol.class_methods);
3615}
3616
3617inline void swapStruct(struct objc_method_description_list_t &mdl) {
3618 sys::swapByteOrder(mdl.count);
3619}
3620
3621inline void swapStruct(struct objc_method_description_t &md) {
3622 sys::swapByteOrder(md.name);
3623 sys::swapByteOrder(md.types);
3624}
3625
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003626static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3627 struct DisassembleInfo *info);
3628
3629// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3630// to an Objective-C class and returns the class name. It is also passed the
3631// address of the pointer, so when the pointer is zero as it can be in an .o
3632// file, that is used to look for an external relocation entry with a symbol
3633// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003634static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3635 uint64_t ReferenceValue,
3636 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003637 const char *r;
3638 uint32_t offset, left;
3639 SectionRef S;
3640
3641 // The pointer_value can be 0 in an object file and have a relocation
3642 // entry for the class symbol at the ReferenceValue (the address of the
3643 // pointer).
3644 if (pointer_value == 0) {
3645 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3646 if (r == nullptr || left < sizeof(uint64_t))
3647 return nullptr;
3648 uint64_t n_value;
3649 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3650 if (symbol_name == nullptr)
3651 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003652 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003653 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3654 return class_name + 2;
3655 else
3656 return nullptr;
3657 }
3658
3659 // The case were the pointer_value is non-zero and points to a class defined
3660 // in this Mach-O file.
3661 r = get_pointer_64(pointer_value, offset, left, S, info);
3662 if (r == nullptr || left < sizeof(struct class64_t))
3663 return nullptr;
3664 struct class64_t c;
3665 memcpy(&c, r, sizeof(struct class64_t));
3666 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3667 swapStruct(c);
3668 if (c.data == 0)
3669 return nullptr;
3670 r = get_pointer_64(c.data, offset, left, S, info);
3671 if (r == nullptr || left < sizeof(struct class_ro64_t))
3672 return nullptr;
3673 struct class_ro64_t cro;
3674 memcpy(&cro, r, sizeof(struct class_ro64_t));
3675 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3676 swapStruct(cro);
3677 if (cro.name == 0)
3678 return nullptr;
3679 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3680 return name;
3681}
3682
3683// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3684// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003685static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3686 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003687 const char *r, *name;
3688 uint32_t offset, left;
3689 SectionRef S;
3690 struct cfstring64_t cfs;
3691 uint64_t cfs_characters;
3692
3693 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3694 if (r == nullptr || left < sizeof(struct cfstring64_t))
3695 return nullptr;
3696 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3697 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3698 swapStruct(cfs);
3699 if (cfs.characters == 0) {
3700 uint64_t n_value;
3701 const char *symbol_name = get_symbol_64(
3702 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3703 if (symbol_name == nullptr)
3704 return nullptr;
3705 cfs_characters = n_value;
3706 } else
3707 cfs_characters = cfs.characters;
3708 name = get_pointer_64(cfs_characters, offset, left, S, info);
3709
3710 return name;
3711}
3712
3713// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3714// of a pointer to an Objective-C selector reference when the pointer value is
3715// zero as in a .o file and is likely to have a external relocation entry with
3716// who's symbol's n_value is the real pointer to the selector name. If that is
3717// the case the real pointer to the selector name is returned else 0 is
3718// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003719static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3720 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003721 uint32_t offset, left;
3722 SectionRef S;
3723
3724 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3725 if (r == nullptr || left < sizeof(uint64_t))
3726 return 0;
3727 uint64_t n_value;
3728 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3729 if (symbol_name == nullptr)
3730 return 0;
3731 return n_value;
3732}
3733
Kevin Enderby0fc11822015-04-01 20:57:01 +00003734static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3735 const char *sectname) {
3736 for (const SectionRef &Section : O->sections()) {
3737 StringRef SectName;
3738 Section.getName(SectName);
3739 DataRefImpl Ref = Section.getRawDataRefImpl();
3740 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3741 if (SegName == segname && SectName == sectname)
3742 return Section;
3743 }
3744 return SectionRef();
3745}
3746
3747static void
3748walk_pointer_list_64(const char *listname, const SectionRef S,
3749 MachOObjectFile *O, struct DisassembleInfo *info,
3750 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3751 if (S == SectionRef())
3752 return;
3753
3754 StringRef SectName;
3755 S.getName(SectName);
3756 DataRefImpl Ref = S.getRawDataRefImpl();
3757 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3758 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3759
3760 StringRef BytesStr;
3761 S.getContents(BytesStr);
3762 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3763
3764 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3765 uint32_t left = S.getSize() - i;
3766 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3767 uint64_t p = 0;
3768 memcpy(&p, Contents + i, size);
3769 if (i + sizeof(uint64_t) > S.getSize())
3770 outs() << listname << " list pointer extends past end of (" << SegName
3771 << "," << SectName << ") section\n";
3772 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3773
3774 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3775 sys::swapByteOrder(p);
3776
3777 uint64_t n_value = 0;
3778 const char *name = get_symbol_64(i, S, info, n_value, p);
3779 if (name == nullptr)
3780 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3781
3782 if (n_value != 0) {
3783 outs() << format("0x%" PRIx64, n_value);
3784 if (p != 0)
3785 outs() << " + " << format("0x%" PRIx64, p);
3786 } else
3787 outs() << format("0x%" PRIx64, p);
3788 if (name != nullptr)
3789 outs() << " " << name;
3790 outs() << "\n";
3791
3792 p += n_value;
3793 if (func)
3794 func(p, info);
3795 }
3796}
3797
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003798static void
3799walk_pointer_list_32(const char *listname, const SectionRef S,
3800 MachOObjectFile *O, struct DisassembleInfo *info,
3801 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3802 if (S == SectionRef())
3803 return;
3804
3805 StringRef SectName;
3806 S.getName(SectName);
3807 DataRefImpl Ref = S.getRawDataRefImpl();
3808 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3809 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3810
3811 StringRef BytesStr;
3812 S.getContents(BytesStr);
3813 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3814
3815 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3816 uint32_t left = S.getSize() - i;
3817 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3818 uint32_t p = 0;
3819 memcpy(&p, Contents + i, size);
3820 if (i + sizeof(uint32_t) > S.getSize())
3821 outs() << listname << " list pointer extends past end of (" << SegName
3822 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003823 uint32_t Address = S.getAddress() + i;
3824 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003825
3826 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3827 sys::swapByteOrder(p);
3828 outs() << format("0x%" PRIx32, p);
3829
3830 const char *name = get_symbol_32(i, S, info, p);
3831 if (name != nullptr)
3832 outs() << " " << name;
3833 outs() << "\n";
3834
3835 if (func)
3836 func(p, info);
3837 }
3838}
3839
3840static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003841 if (layout_map == nullptr)
3842 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003843 outs() << " layout map: ";
3844 do {
3845 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3846 left--;
3847 layout_map++;
3848 } while (*layout_map != '\0' && left != 0);
3849 outs() << "\n";
3850}
3851
Kevin Enderby0fc11822015-04-01 20:57:01 +00003852static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3853 uint32_t offset, left;
3854 SectionRef S;
3855 const char *layout_map;
3856
3857 if (p == 0)
3858 return;
3859 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003860 print_layout_map(layout_map, left);
3861}
3862
3863static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3864 uint32_t offset, left;
3865 SectionRef S;
3866 const char *layout_map;
3867
3868 if (p == 0)
3869 return;
3870 layout_map = get_pointer_32(p, offset, left, S, info);
3871 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003872}
3873
3874static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3875 const char *indent) {
3876 struct method_list64_t ml;
3877 struct method64_t m;
3878 const char *r;
3879 uint32_t offset, xoffset, left, i;
3880 SectionRef S, xS;
3881 const char *name, *sym_name;
3882 uint64_t n_value;
3883
3884 r = get_pointer_64(p, offset, left, S, info);
3885 if (r == nullptr)
3886 return;
3887 memset(&ml, '\0', sizeof(struct method_list64_t));
3888 if (left < sizeof(struct method_list64_t)) {
3889 memcpy(&ml, r, left);
3890 outs() << " (method_list_t entends past the end of the section)\n";
3891 } else
3892 memcpy(&ml, r, sizeof(struct method_list64_t));
3893 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3894 swapStruct(ml);
3895 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3896 outs() << indent << "\t\t count " << ml.count << "\n";
3897
3898 p += sizeof(struct method_list64_t);
3899 offset += sizeof(struct method_list64_t);
3900 for (i = 0; i < ml.count; i++) {
3901 r = get_pointer_64(p, offset, left, S, info);
3902 if (r == nullptr)
3903 return;
3904 memset(&m, '\0', sizeof(struct method64_t));
3905 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003906 memcpy(&m, r, left);
3907 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003908 } else
3909 memcpy(&m, r, sizeof(struct method64_t));
3910 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3911 swapStruct(m);
3912
3913 outs() << indent << "\t\t name ";
3914 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3915 info, n_value, m.name);
3916 if (n_value != 0) {
3917 if (info->verbose && sym_name != nullptr)
3918 outs() << sym_name;
3919 else
3920 outs() << format("0x%" PRIx64, n_value);
3921 if (m.name != 0)
3922 outs() << " + " << format("0x%" PRIx64, m.name);
3923 } else
3924 outs() << format("0x%" PRIx64, m.name);
3925 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3926 if (name != nullptr)
3927 outs() << format(" %.*s", left, name);
3928 outs() << "\n";
3929
3930 outs() << indent << "\t\t types ";
3931 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3932 info, n_value, m.types);
3933 if (n_value != 0) {
3934 if (info->verbose && sym_name != nullptr)
3935 outs() << sym_name;
3936 else
3937 outs() << format("0x%" PRIx64, n_value);
3938 if (m.types != 0)
3939 outs() << " + " << format("0x%" PRIx64, m.types);
3940 } else
3941 outs() << format("0x%" PRIx64, m.types);
3942 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3943 if (name != nullptr)
3944 outs() << format(" %.*s", left, name);
3945 outs() << "\n";
3946
3947 outs() << indent << "\t\t imp ";
3948 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3949 n_value, m.imp);
3950 if (info->verbose && name == nullptr) {
3951 if (n_value != 0) {
3952 outs() << format("0x%" PRIx64, n_value) << " ";
3953 if (m.imp != 0)
3954 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3955 } else
3956 outs() << format("0x%" PRIx64, m.imp) << " ";
3957 }
3958 if (name != nullptr)
3959 outs() << name;
3960 outs() << "\n";
3961
3962 p += sizeof(struct method64_t);
3963 offset += sizeof(struct method64_t);
3964 }
3965}
3966
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003967static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3968 const char *indent) {
3969 struct method_list32_t ml;
3970 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003971 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003972 uint32_t offset, xoffset, left, i;
3973 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003974
3975 r = get_pointer_32(p, offset, left, S, info);
3976 if (r == nullptr)
3977 return;
3978 memset(&ml, '\0', sizeof(struct method_list32_t));
3979 if (left < sizeof(struct method_list32_t)) {
3980 memcpy(&ml, r, left);
3981 outs() << " (method_list_t entends past the end of the section)\n";
3982 } else
3983 memcpy(&ml, r, sizeof(struct method_list32_t));
3984 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3985 swapStruct(ml);
3986 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3987 outs() << indent << "\t\t count " << ml.count << "\n";
3988
3989 p += sizeof(struct method_list32_t);
3990 offset += sizeof(struct method_list32_t);
3991 for (i = 0; i < ml.count; i++) {
3992 r = get_pointer_32(p, offset, left, S, info);
3993 if (r == nullptr)
3994 return;
3995 memset(&m, '\0', sizeof(struct method32_t));
3996 if (left < sizeof(struct method32_t)) {
3997 memcpy(&ml, r, left);
3998 outs() << indent << " (method_t entends past the end of the section)\n";
3999 } else
4000 memcpy(&m, r, sizeof(struct method32_t));
4001 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4002 swapStruct(m);
4003
4004 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4005 name = get_pointer_32(m.name, xoffset, left, xS, info);
4006 if (name != nullptr)
4007 outs() << format(" %.*s", left, name);
4008 outs() << "\n";
4009
4010 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4011 name = get_pointer_32(m.types, xoffset, left, xS, info);
4012 if (name != nullptr)
4013 outs() << format(" %.*s", left, name);
4014 outs() << "\n";
4015
4016 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4017 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4018 m.imp);
4019 if (name != nullptr)
4020 outs() << " " << name;
4021 outs() << "\n";
4022
4023 p += sizeof(struct method32_t);
4024 offset += sizeof(struct method32_t);
4025 }
4026}
4027
Kevin Enderby846c0002015-04-16 17:19:59 +00004028static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4029 uint32_t offset, left, xleft;
4030 SectionRef S;
4031 struct objc_method_list_t method_list;
4032 struct objc_method_t method;
4033 const char *r, *methods, *name, *SymbolName;
4034 int32_t i;
4035
4036 r = get_pointer_32(p, offset, left, S, info, true);
4037 if (r == nullptr)
4038 return true;
4039
4040 outs() << "\n";
4041 if (left > sizeof(struct objc_method_list_t)) {
4042 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4043 } else {
4044 outs() << "\t\t objc_method_list extends past end of the section\n";
4045 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4046 memcpy(&method_list, r, left);
4047 }
4048 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4049 swapStruct(method_list);
4050
4051 outs() << "\t\t obsolete "
4052 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4053 outs() << "\t\t method_count " << method_list.method_count << "\n";
4054
4055 methods = r + sizeof(struct objc_method_list_t);
4056 for (i = 0; i < method_list.method_count; i++) {
4057 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4058 outs() << "\t\t remaining method's extend past the of the section\n";
4059 break;
4060 }
4061 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4062 sizeof(struct objc_method_t));
4063 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4064 swapStruct(method);
4065
4066 outs() << "\t\t method_name "
4067 << format("0x%08" PRIx32, method.method_name);
4068 if (info->verbose) {
4069 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4070 if (name != nullptr)
4071 outs() << format(" %.*s", xleft, name);
4072 else
4073 outs() << " (not in an __OBJC section)";
4074 }
4075 outs() << "\n";
4076
4077 outs() << "\t\t method_types "
4078 << format("0x%08" PRIx32, method.method_types);
4079 if (info->verbose) {
4080 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4081 if (name != nullptr)
4082 outs() << format(" %.*s", xleft, name);
4083 else
4084 outs() << " (not in an __OBJC section)";
4085 }
4086 outs() << "\n";
4087
4088 outs() << "\t\t method_imp "
4089 << format("0x%08" PRIx32, method.method_imp) << " ";
4090 if (info->verbose) {
4091 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4092 if (SymbolName != nullptr)
4093 outs() << SymbolName;
4094 }
4095 outs() << "\n";
4096 }
4097 return false;
4098}
4099
Kevin Enderby0fc11822015-04-01 20:57:01 +00004100static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4101 struct protocol_list64_t pl;
4102 uint64_t q, n_value;
4103 struct protocol64_t pc;
4104 const char *r;
4105 uint32_t offset, xoffset, left, i;
4106 SectionRef S, xS;
4107 const char *name, *sym_name;
4108
4109 r = get_pointer_64(p, offset, left, S, info);
4110 if (r == nullptr)
4111 return;
4112 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4113 if (left < sizeof(struct protocol_list64_t)) {
4114 memcpy(&pl, r, left);
4115 outs() << " (protocol_list_t entends past the end of the section)\n";
4116 } else
4117 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4118 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4119 swapStruct(pl);
4120 outs() << " count " << pl.count << "\n";
4121
4122 p += sizeof(struct protocol_list64_t);
4123 offset += sizeof(struct protocol_list64_t);
4124 for (i = 0; i < pl.count; i++) {
4125 r = get_pointer_64(p, offset, left, S, info);
4126 if (r == nullptr)
4127 return;
4128 q = 0;
4129 if (left < sizeof(uint64_t)) {
4130 memcpy(&q, r, left);
4131 outs() << " (protocol_t * entends past the end of the section)\n";
4132 } else
4133 memcpy(&q, r, sizeof(uint64_t));
4134 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4135 sys::swapByteOrder(q);
4136
4137 outs() << "\t\t list[" << i << "] ";
4138 sym_name = get_symbol_64(offset, S, info, n_value, q);
4139 if (n_value != 0) {
4140 if (info->verbose && sym_name != nullptr)
4141 outs() << sym_name;
4142 else
4143 outs() << format("0x%" PRIx64, n_value);
4144 if (q != 0)
4145 outs() << " + " << format("0x%" PRIx64, q);
4146 } else
4147 outs() << format("0x%" PRIx64, q);
4148 outs() << " (struct protocol_t *)\n";
4149
4150 r = get_pointer_64(q + n_value, offset, left, S, info);
4151 if (r == nullptr)
4152 return;
4153 memset(&pc, '\0', sizeof(struct protocol64_t));
4154 if (left < sizeof(struct protocol64_t)) {
4155 memcpy(&pc, r, left);
4156 outs() << " (protocol_t entends past the end of the section)\n";
4157 } else
4158 memcpy(&pc, r, sizeof(struct protocol64_t));
4159 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4160 swapStruct(pc);
4161
4162 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4163
4164 outs() << "\t\t\t name ";
4165 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4166 info, n_value, pc.name);
4167 if (n_value != 0) {
4168 if (info->verbose && sym_name != nullptr)
4169 outs() << sym_name;
4170 else
4171 outs() << format("0x%" PRIx64, n_value);
4172 if (pc.name != 0)
4173 outs() << " + " << format("0x%" PRIx64, pc.name);
4174 } else
4175 outs() << format("0x%" PRIx64, pc.name);
4176 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4177 if (name != nullptr)
4178 outs() << format(" %.*s", left, name);
4179 outs() << "\n";
4180
4181 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4182
4183 outs() << "\t\t instanceMethods ";
4184 sym_name =
4185 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4186 S, info, n_value, pc.instanceMethods);
4187 if (n_value != 0) {
4188 if (info->verbose && sym_name != nullptr)
4189 outs() << sym_name;
4190 else
4191 outs() << format("0x%" PRIx64, n_value);
4192 if (pc.instanceMethods != 0)
4193 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4194 } else
4195 outs() << format("0x%" PRIx64, pc.instanceMethods);
4196 outs() << " (struct method_list_t *)\n";
4197 if (pc.instanceMethods + n_value != 0)
4198 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4199
4200 outs() << "\t\t classMethods ";
4201 sym_name =
4202 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4203 info, n_value, pc.classMethods);
4204 if (n_value != 0) {
4205 if (info->verbose && sym_name != nullptr)
4206 outs() << sym_name;
4207 else
4208 outs() << format("0x%" PRIx64, n_value);
4209 if (pc.classMethods != 0)
4210 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4211 } else
4212 outs() << format("0x%" PRIx64, pc.classMethods);
4213 outs() << " (struct method_list_t *)\n";
4214 if (pc.classMethods + n_value != 0)
4215 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4216
4217 outs() << "\t optionalInstanceMethods "
4218 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4219 outs() << "\t optionalClassMethods "
4220 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4221 outs() << "\t instanceProperties "
4222 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4223
4224 p += sizeof(uint64_t);
4225 offset += sizeof(uint64_t);
4226 }
4227}
4228
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004229static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4230 struct protocol_list32_t pl;
4231 uint32_t q;
4232 struct protocol32_t pc;
4233 const char *r;
4234 uint32_t offset, xoffset, left, i;
4235 SectionRef S, xS;
4236 const char *name;
4237
4238 r = get_pointer_32(p, offset, left, S, info);
4239 if (r == nullptr)
4240 return;
4241 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4242 if (left < sizeof(struct protocol_list32_t)) {
4243 memcpy(&pl, r, left);
4244 outs() << " (protocol_list_t entends past the end of the section)\n";
4245 } else
4246 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4247 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4248 swapStruct(pl);
4249 outs() << " count " << pl.count << "\n";
4250
4251 p += sizeof(struct protocol_list32_t);
4252 offset += sizeof(struct protocol_list32_t);
4253 for (i = 0; i < pl.count; i++) {
4254 r = get_pointer_32(p, offset, left, S, info);
4255 if (r == nullptr)
4256 return;
4257 q = 0;
4258 if (left < sizeof(uint32_t)) {
4259 memcpy(&q, r, left);
4260 outs() << " (protocol_t * entends past the end of the section)\n";
4261 } else
4262 memcpy(&q, r, sizeof(uint32_t));
4263 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4264 sys::swapByteOrder(q);
4265 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4266 << " (struct protocol_t *)\n";
4267 r = get_pointer_32(q, offset, left, S, info);
4268 if (r == nullptr)
4269 return;
4270 memset(&pc, '\0', sizeof(struct protocol32_t));
4271 if (left < sizeof(struct protocol32_t)) {
4272 memcpy(&pc, r, left);
4273 outs() << " (protocol_t entends past the end of the section)\n";
4274 } else
4275 memcpy(&pc, r, sizeof(struct protocol32_t));
4276 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4277 swapStruct(pc);
4278 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4279 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4280 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4281 if (name != nullptr)
4282 outs() << format(" %.*s", left, name);
4283 outs() << "\n";
4284 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4285 outs() << "\t\t instanceMethods "
4286 << format("0x%" PRIx32, pc.instanceMethods)
4287 << " (struct method_list_t *)\n";
4288 if (pc.instanceMethods != 0)
4289 print_method_list32_t(pc.instanceMethods, info, "\t");
4290 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4291 << " (struct method_list_t *)\n";
4292 if (pc.classMethods != 0)
4293 print_method_list32_t(pc.classMethods, info, "\t");
4294 outs() << "\t optionalInstanceMethods "
4295 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4296 outs() << "\t optionalClassMethods "
4297 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4298 outs() << "\t instanceProperties "
4299 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4300 p += sizeof(uint32_t);
4301 offset += sizeof(uint32_t);
4302 }
4303}
4304
Kevin Enderby846c0002015-04-16 17:19:59 +00004305static void print_indent(uint32_t indent) {
4306 for (uint32_t i = 0; i < indent;) {
4307 if (indent - i >= 8) {
4308 outs() << "\t";
4309 i += 8;
4310 } else {
4311 for (uint32_t j = i; j < indent; j++)
4312 outs() << " ";
4313 return;
4314 }
4315 }
4316}
4317
4318static bool print_method_description_list(uint32_t p, uint32_t indent,
4319 struct DisassembleInfo *info) {
4320 uint32_t offset, left, xleft;
4321 SectionRef S;
4322 struct objc_method_description_list_t mdl;
4323 struct objc_method_description_t md;
4324 const char *r, *list, *name;
4325 int32_t i;
4326
4327 r = get_pointer_32(p, offset, left, S, info, true);
4328 if (r == nullptr)
4329 return true;
4330
4331 outs() << "\n";
4332 if (left > sizeof(struct objc_method_description_list_t)) {
4333 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4334 } else {
4335 print_indent(indent);
4336 outs() << " objc_method_description_list extends past end of the section\n";
4337 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4338 memcpy(&mdl, r, left);
4339 }
4340 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4341 swapStruct(mdl);
4342
4343 print_indent(indent);
4344 outs() << " count " << mdl.count << "\n";
4345
4346 list = r + sizeof(struct objc_method_description_list_t);
4347 for (i = 0; i < mdl.count; i++) {
4348 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4349 print_indent(indent);
4350 outs() << " remaining list entries extend past the of the section\n";
4351 break;
4352 }
4353 print_indent(indent);
4354 outs() << " list[" << i << "]\n";
4355 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4356 sizeof(struct objc_method_description_t));
4357 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4358 swapStruct(md);
4359
4360 print_indent(indent);
4361 outs() << " name " << format("0x%08" PRIx32, md.name);
4362 if (info->verbose) {
4363 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4364 if (name != nullptr)
4365 outs() << format(" %.*s", xleft, name);
4366 else
4367 outs() << " (not in an __OBJC section)";
4368 }
4369 outs() << "\n";
4370
4371 print_indent(indent);
4372 outs() << " types " << format("0x%08" PRIx32, md.types);
4373 if (info->verbose) {
4374 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4375 if (name != nullptr)
4376 outs() << format(" %.*s", xleft, name);
4377 else
4378 outs() << " (not in an __OBJC section)";
4379 }
4380 outs() << "\n";
4381 }
4382 return false;
4383}
4384
4385static bool print_protocol_list(uint32_t p, uint32_t indent,
4386 struct DisassembleInfo *info);
4387
4388static bool print_protocol(uint32_t p, uint32_t indent,
4389 struct DisassembleInfo *info) {
4390 uint32_t offset, left;
4391 SectionRef S;
4392 struct objc_protocol_t protocol;
4393 const char *r, *name;
4394
4395 r = get_pointer_32(p, offset, left, S, info, true);
4396 if (r == nullptr)
4397 return true;
4398
4399 outs() << "\n";
4400 if (left >= sizeof(struct objc_protocol_t)) {
4401 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4402 } else {
4403 print_indent(indent);
4404 outs() << " Protocol extends past end of the section\n";
4405 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4406 memcpy(&protocol, r, left);
4407 }
4408 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4409 swapStruct(protocol);
4410
4411 print_indent(indent);
4412 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4413 << "\n";
4414
4415 print_indent(indent);
4416 outs() << " protocol_name "
4417 << format("0x%08" PRIx32, protocol.protocol_name);
4418 if (info->verbose) {
4419 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4420 if (name != nullptr)
4421 outs() << format(" %.*s", left, name);
4422 else
4423 outs() << " (not in an __OBJC section)";
4424 }
4425 outs() << "\n";
4426
4427 print_indent(indent);
4428 outs() << " protocol_list "
4429 << format("0x%08" PRIx32, protocol.protocol_list);
4430 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4431 outs() << " (not in an __OBJC section)\n";
4432
4433 print_indent(indent);
4434 outs() << " instance_methods "
4435 << format("0x%08" PRIx32, protocol.instance_methods);
4436 if (print_method_description_list(protocol.instance_methods, indent, info))
4437 outs() << " (not in an __OBJC section)\n";
4438
4439 print_indent(indent);
4440 outs() << " class_methods "
4441 << format("0x%08" PRIx32, protocol.class_methods);
4442 if (print_method_description_list(protocol.class_methods, indent, info))
4443 outs() << " (not in an __OBJC section)\n";
4444
4445 return false;
4446}
4447
4448static bool print_protocol_list(uint32_t p, uint32_t indent,
4449 struct DisassembleInfo *info) {
4450 uint32_t offset, left, l;
4451 SectionRef S;
4452 struct objc_protocol_list_t protocol_list;
4453 const char *r, *list;
4454 int32_t i;
4455
4456 r = get_pointer_32(p, offset, left, S, info, true);
4457 if (r == nullptr)
4458 return true;
4459
4460 outs() << "\n";
4461 if (left > sizeof(struct objc_protocol_list_t)) {
4462 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4463 } else {
4464 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4465 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4466 memcpy(&protocol_list, r, left);
4467 }
4468 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4469 swapStruct(protocol_list);
4470
4471 print_indent(indent);
4472 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4473 << "\n";
4474 print_indent(indent);
4475 outs() << " count " << protocol_list.count << "\n";
4476
4477 list = r + sizeof(struct objc_protocol_list_t);
4478 for (i = 0; i < protocol_list.count; i++) {
4479 if ((i + 1) * sizeof(uint32_t) > left) {
4480 outs() << "\t\t remaining list entries extend past the of the section\n";
4481 break;
4482 }
4483 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4484 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4485 sys::swapByteOrder(l);
4486
4487 print_indent(indent);
4488 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4489 if (print_protocol(l, indent, info))
4490 outs() << "(not in an __OBJC section)\n";
4491 }
4492 return false;
4493}
4494
Kevin Enderby0fc11822015-04-01 20:57:01 +00004495static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4496 struct ivar_list64_t il;
4497 struct ivar64_t i;
4498 const char *r;
4499 uint32_t offset, xoffset, left, j;
4500 SectionRef S, xS;
4501 const char *name, *sym_name, *ivar_offset_p;
4502 uint64_t ivar_offset, n_value;
4503
4504 r = get_pointer_64(p, offset, left, S, info);
4505 if (r == nullptr)
4506 return;
4507 memset(&il, '\0', sizeof(struct ivar_list64_t));
4508 if (left < sizeof(struct ivar_list64_t)) {
4509 memcpy(&il, r, left);
4510 outs() << " (ivar_list_t entends past the end of the section)\n";
4511 } else
4512 memcpy(&il, r, sizeof(struct ivar_list64_t));
4513 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4514 swapStruct(il);
4515 outs() << " entsize " << il.entsize << "\n";
4516 outs() << " count " << il.count << "\n";
4517
4518 p += sizeof(struct ivar_list64_t);
4519 offset += sizeof(struct ivar_list64_t);
4520 for (j = 0; j < il.count; j++) {
4521 r = get_pointer_64(p, offset, left, S, info);
4522 if (r == nullptr)
4523 return;
4524 memset(&i, '\0', sizeof(struct ivar64_t));
4525 if (left < sizeof(struct ivar64_t)) {
4526 memcpy(&i, r, left);
4527 outs() << " (ivar_t entends past the end of the section)\n";
4528 } else
4529 memcpy(&i, r, sizeof(struct ivar64_t));
4530 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4531 swapStruct(i);
4532
4533 outs() << "\t\t\t offset ";
4534 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4535 info, n_value, i.offset);
4536 if (n_value != 0) {
4537 if (info->verbose && sym_name != nullptr)
4538 outs() << sym_name;
4539 else
4540 outs() << format("0x%" PRIx64, n_value);
4541 if (i.offset != 0)
4542 outs() << " + " << format("0x%" PRIx64, i.offset);
4543 } else
4544 outs() << format("0x%" PRIx64, i.offset);
4545 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4546 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4547 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4548 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4549 sys::swapByteOrder(ivar_offset);
4550 outs() << " " << ivar_offset << "\n";
4551 } else
4552 outs() << "\n";
4553
4554 outs() << "\t\t\t name ";
4555 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4556 n_value, i.name);
4557 if (n_value != 0) {
4558 if (info->verbose && sym_name != nullptr)
4559 outs() << sym_name;
4560 else
4561 outs() << format("0x%" PRIx64, n_value);
4562 if (i.name != 0)
4563 outs() << " + " << format("0x%" PRIx64, i.name);
4564 } else
4565 outs() << format("0x%" PRIx64, i.name);
4566 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4567 if (name != nullptr)
4568 outs() << format(" %.*s", left, name);
4569 outs() << "\n";
4570
4571 outs() << "\t\t\t type ";
4572 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4573 n_value, i.name);
4574 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4575 if (n_value != 0) {
4576 if (info->verbose && sym_name != nullptr)
4577 outs() << sym_name;
4578 else
4579 outs() << format("0x%" PRIx64, n_value);
4580 if (i.type != 0)
4581 outs() << " + " << format("0x%" PRIx64, i.type);
4582 } else
4583 outs() << format("0x%" PRIx64, i.type);
4584 if (name != nullptr)
4585 outs() << format(" %.*s", left, name);
4586 outs() << "\n";
4587
4588 outs() << "\t\t\talignment " << i.alignment << "\n";
4589 outs() << "\t\t\t size " << i.size << "\n";
4590
4591 p += sizeof(struct ivar64_t);
4592 offset += sizeof(struct ivar64_t);
4593 }
4594}
4595
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004596static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4597 struct ivar_list32_t il;
4598 struct ivar32_t i;
4599 const char *r;
4600 uint32_t offset, xoffset, left, j;
4601 SectionRef S, xS;
4602 const char *name, *ivar_offset_p;
4603 uint32_t ivar_offset;
4604
4605 r = get_pointer_32(p, offset, left, S, info);
4606 if (r == nullptr)
4607 return;
4608 memset(&il, '\0', sizeof(struct ivar_list32_t));
4609 if (left < sizeof(struct ivar_list32_t)) {
4610 memcpy(&il, r, left);
4611 outs() << " (ivar_list_t entends past the end of the section)\n";
4612 } else
4613 memcpy(&il, r, sizeof(struct ivar_list32_t));
4614 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4615 swapStruct(il);
4616 outs() << " entsize " << il.entsize << "\n";
4617 outs() << " count " << il.count << "\n";
4618
4619 p += sizeof(struct ivar_list32_t);
4620 offset += sizeof(struct ivar_list32_t);
4621 for (j = 0; j < il.count; j++) {
4622 r = get_pointer_32(p, offset, left, S, info);
4623 if (r == nullptr)
4624 return;
4625 memset(&i, '\0', sizeof(struct ivar32_t));
4626 if (left < sizeof(struct ivar32_t)) {
4627 memcpy(&i, r, left);
4628 outs() << " (ivar_t entends past the end of the section)\n";
4629 } else
4630 memcpy(&i, r, sizeof(struct ivar32_t));
4631 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4632 swapStruct(i);
4633
4634 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4635 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4636 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4637 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4638 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4639 sys::swapByteOrder(ivar_offset);
4640 outs() << " " << ivar_offset << "\n";
4641 } else
4642 outs() << "\n";
4643
4644 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4645 name = get_pointer_32(i.name, xoffset, left, xS, info);
4646 if (name != nullptr)
4647 outs() << format(" %.*s", left, name);
4648 outs() << "\n";
4649
4650 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4651 name = get_pointer_32(i.type, xoffset, left, xS, info);
4652 if (name != nullptr)
4653 outs() << format(" %.*s", left, name);
4654 outs() << "\n";
4655
4656 outs() << "\t\t\talignment " << i.alignment << "\n";
4657 outs() << "\t\t\t size " << i.size << "\n";
4658
4659 p += sizeof(struct ivar32_t);
4660 offset += sizeof(struct ivar32_t);
4661 }
4662}
4663
Kevin Enderby0fc11822015-04-01 20:57:01 +00004664static void print_objc_property_list64(uint64_t p,
4665 struct DisassembleInfo *info) {
4666 struct objc_property_list64 opl;
4667 struct objc_property64 op;
4668 const char *r;
4669 uint32_t offset, xoffset, left, j;
4670 SectionRef S, xS;
4671 const char *name, *sym_name;
4672 uint64_t n_value;
4673
4674 r = get_pointer_64(p, offset, left, S, info);
4675 if (r == nullptr)
4676 return;
4677 memset(&opl, '\0', sizeof(struct objc_property_list64));
4678 if (left < sizeof(struct objc_property_list64)) {
4679 memcpy(&opl, r, left);
4680 outs() << " (objc_property_list entends past the end of the section)\n";
4681 } else
4682 memcpy(&opl, r, sizeof(struct objc_property_list64));
4683 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4684 swapStruct(opl);
4685 outs() << " entsize " << opl.entsize << "\n";
4686 outs() << " count " << opl.count << "\n";
4687
4688 p += sizeof(struct objc_property_list64);
4689 offset += sizeof(struct objc_property_list64);
4690 for (j = 0; j < opl.count; j++) {
4691 r = get_pointer_64(p, offset, left, S, info);
4692 if (r == nullptr)
4693 return;
4694 memset(&op, '\0', sizeof(struct objc_property64));
4695 if (left < sizeof(struct objc_property64)) {
4696 memcpy(&op, r, left);
4697 outs() << " (objc_property entends past the end of the section)\n";
4698 } else
4699 memcpy(&op, r, sizeof(struct objc_property64));
4700 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4701 swapStruct(op);
4702
4703 outs() << "\t\t\t name ";
4704 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4705 info, n_value, op.name);
4706 if (n_value != 0) {
4707 if (info->verbose && sym_name != nullptr)
4708 outs() << sym_name;
4709 else
4710 outs() << format("0x%" PRIx64, n_value);
4711 if (op.name != 0)
4712 outs() << " + " << format("0x%" PRIx64, op.name);
4713 } else
4714 outs() << format("0x%" PRIx64, op.name);
4715 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4716 if (name != nullptr)
4717 outs() << format(" %.*s", left, name);
4718 outs() << "\n";
4719
4720 outs() << "\t\t\tattributes ";
4721 sym_name =
4722 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4723 info, n_value, op.attributes);
4724 if (n_value != 0) {
4725 if (info->verbose && sym_name != nullptr)
4726 outs() << sym_name;
4727 else
4728 outs() << format("0x%" PRIx64, n_value);
4729 if (op.attributes != 0)
4730 outs() << " + " << format("0x%" PRIx64, op.attributes);
4731 } else
4732 outs() << format("0x%" PRIx64, op.attributes);
4733 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4734 if (name != nullptr)
4735 outs() << format(" %.*s", left, name);
4736 outs() << "\n";
4737
4738 p += sizeof(struct objc_property64);
4739 offset += sizeof(struct objc_property64);
4740 }
4741}
4742
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004743static void print_objc_property_list32(uint32_t p,
4744 struct DisassembleInfo *info) {
4745 struct objc_property_list32 opl;
4746 struct objc_property32 op;
4747 const char *r;
4748 uint32_t offset, xoffset, left, j;
4749 SectionRef S, xS;
4750 const char *name;
4751
4752 r = get_pointer_32(p, offset, left, S, info);
4753 if (r == nullptr)
4754 return;
4755 memset(&opl, '\0', sizeof(struct objc_property_list32));
4756 if (left < sizeof(struct objc_property_list32)) {
4757 memcpy(&opl, r, left);
4758 outs() << " (objc_property_list entends past the end of the section)\n";
4759 } else
4760 memcpy(&opl, r, sizeof(struct objc_property_list32));
4761 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4762 swapStruct(opl);
4763 outs() << " entsize " << opl.entsize << "\n";
4764 outs() << " count " << opl.count << "\n";
4765
4766 p += sizeof(struct objc_property_list32);
4767 offset += sizeof(struct objc_property_list32);
4768 for (j = 0; j < opl.count; j++) {
4769 r = get_pointer_32(p, offset, left, S, info);
4770 if (r == nullptr)
4771 return;
4772 memset(&op, '\0', sizeof(struct objc_property32));
4773 if (left < sizeof(struct objc_property32)) {
4774 memcpy(&op, r, left);
4775 outs() << " (objc_property entends past the end of the section)\n";
4776 } else
4777 memcpy(&op, r, sizeof(struct objc_property32));
4778 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4779 swapStruct(op);
4780
4781 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4782 name = get_pointer_32(op.name, xoffset, left, xS, info);
4783 if (name != nullptr)
4784 outs() << format(" %.*s", left, name);
4785 outs() << "\n";
4786
4787 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4788 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4789 if (name != nullptr)
4790 outs() << format(" %.*s", left, name);
4791 outs() << "\n";
4792
4793 p += sizeof(struct objc_property32);
4794 offset += sizeof(struct objc_property32);
4795 }
4796}
4797
Richard Smith81ff44d2015-10-09 22:09:56 +00004798static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004799 bool &is_meta_class) {
4800 struct class_ro64_t cro;
4801 const char *r;
4802 uint32_t offset, xoffset, left;
4803 SectionRef S, xS;
4804 const char *name, *sym_name;
4805 uint64_t n_value;
4806
4807 r = get_pointer_64(p, offset, left, S, info);
4808 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004809 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004810 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004811 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4812 swapStruct(cro);
4813 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4814 if (cro.flags & RO_META)
4815 outs() << " RO_META";
4816 if (cro.flags & RO_ROOT)
4817 outs() << " RO_ROOT";
4818 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4819 outs() << " RO_HAS_CXX_STRUCTORS";
4820 outs() << "\n";
4821 outs() << " instanceStart " << cro.instanceStart << "\n";
4822 outs() << " instanceSize " << cro.instanceSize << "\n";
4823 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4824 << "\n";
4825 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4826 << "\n";
4827 print_layout_map64(cro.ivarLayout, info);
4828
4829 outs() << " name ";
4830 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4831 info, n_value, cro.name);
4832 if (n_value != 0) {
4833 if (info->verbose && sym_name != nullptr)
4834 outs() << sym_name;
4835 else
4836 outs() << format("0x%" PRIx64, n_value);
4837 if (cro.name != 0)
4838 outs() << " + " << format("0x%" PRIx64, cro.name);
4839 } else
4840 outs() << format("0x%" PRIx64, cro.name);
4841 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4842 if (name != nullptr)
4843 outs() << format(" %.*s", left, name);
4844 outs() << "\n";
4845
4846 outs() << " baseMethods ";
4847 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4848 S, info, n_value, cro.baseMethods);
4849 if (n_value != 0) {
4850 if (info->verbose && sym_name != nullptr)
4851 outs() << sym_name;
4852 else
4853 outs() << format("0x%" PRIx64, n_value);
4854 if (cro.baseMethods != 0)
4855 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4856 } else
4857 outs() << format("0x%" PRIx64, cro.baseMethods);
4858 outs() << " (struct method_list_t *)\n";
4859 if (cro.baseMethods + n_value != 0)
4860 print_method_list64_t(cro.baseMethods + n_value, info, "");
4861
4862 outs() << " baseProtocols ";
4863 sym_name =
4864 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4865 info, n_value, cro.baseProtocols);
4866 if (n_value != 0) {
4867 if (info->verbose && sym_name != nullptr)
4868 outs() << sym_name;
4869 else
4870 outs() << format("0x%" PRIx64, n_value);
4871 if (cro.baseProtocols != 0)
4872 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4873 } else
4874 outs() << format("0x%" PRIx64, cro.baseProtocols);
4875 outs() << "\n";
4876 if (cro.baseProtocols + n_value != 0)
4877 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4878
4879 outs() << " ivars ";
4880 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004881 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004882 if (n_value != 0) {
4883 if (info->verbose && sym_name != nullptr)
4884 outs() << sym_name;
4885 else
4886 outs() << format("0x%" PRIx64, n_value);
4887 if (cro.ivars != 0)
4888 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4889 } else
4890 outs() << format("0x%" PRIx64, cro.ivars);
4891 outs() << "\n";
4892 if (cro.ivars + n_value != 0)
4893 print_ivar_list64_t(cro.ivars + n_value, info);
4894
4895 outs() << " weakIvarLayout ";
4896 sym_name =
4897 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4898 info, n_value, cro.weakIvarLayout);
4899 if (n_value != 0) {
4900 if (info->verbose && sym_name != nullptr)
4901 outs() << sym_name;
4902 else
4903 outs() << format("0x%" PRIx64, n_value);
4904 if (cro.weakIvarLayout != 0)
4905 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4906 } else
4907 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4908 outs() << "\n";
4909 print_layout_map64(cro.weakIvarLayout + n_value, info);
4910
4911 outs() << " baseProperties ";
4912 sym_name =
4913 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4914 info, n_value, cro.baseProperties);
4915 if (n_value != 0) {
4916 if (info->verbose && sym_name != nullptr)
4917 outs() << sym_name;
4918 else
4919 outs() << format("0x%" PRIx64, n_value);
4920 if (cro.baseProperties != 0)
4921 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4922 } else
4923 outs() << format("0x%" PRIx64, cro.baseProperties);
4924 outs() << "\n";
4925 if (cro.baseProperties + n_value != 0)
4926 print_objc_property_list64(cro.baseProperties + n_value, info);
4927
Rafael Espindolab9091322015-10-24 23:19:10 +00004928 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004929 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004930}
4931
Richard Smith81ff44d2015-10-09 22:09:56 +00004932static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004933 bool &is_meta_class) {
4934 struct class_ro32_t cro;
4935 const char *r;
4936 uint32_t offset, xoffset, left;
4937 SectionRef S, xS;
4938 const char *name;
4939
4940 r = get_pointer_32(p, offset, left, S, info);
4941 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004942 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004943 memset(&cro, '\0', sizeof(struct class_ro32_t));
4944 if (left < sizeof(struct class_ro32_t)) {
4945 memcpy(&cro, r, left);
4946 outs() << " (class_ro_t entends past the end of the section)\n";
4947 } else
4948 memcpy(&cro, r, sizeof(struct class_ro32_t));
4949 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4950 swapStruct(cro);
4951 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4952 if (cro.flags & RO_META)
4953 outs() << " RO_META";
4954 if (cro.flags & RO_ROOT)
4955 outs() << " RO_ROOT";
4956 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4957 outs() << " RO_HAS_CXX_STRUCTORS";
4958 outs() << "\n";
4959 outs() << " instanceStart " << cro.instanceStart << "\n";
4960 outs() << " instanceSize " << cro.instanceSize << "\n";
4961 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4962 << "\n";
4963 print_layout_map32(cro.ivarLayout, info);
4964
4965 outs() << " name " << format("0x%" PRIx32, cro.name);
4966 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4967 if (name != nullptr)
4968 outs() << format(" %.*s", left, name);
4969 outs() << "\n";
4970
4971 outs() << " baseMethods "
4972 << format("0x%" PRIx32, cro.baseMethods)
4973 << " (struct method_list_t *)\n";
4974 if (cro.baseMethods != 0)
4975 print_method_list32_t(cro.baseMethods, info, "");
4976
4977 outs() << " baseProtocols "
4978 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4979 if (cro.baseProtocols != 0)
4980 print_protocol_list32_t(cro.baseProtocols, info);
4981 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4982 << "\n";
4983 if (cro.ivars != 0)
4984 print_ivar_list32_t(cro.ivars, info);
4985 outs() << " weakIvarLayout "
4986 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4987 print_layout_map32(cro.weakIvarLayout, info);
4988 outs() << " baseProperties "
4989 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4990 if (cro.baseProperties != 0)
4991 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004992 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004993 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004994}
4995
Kevin Enderby0fc11822015-04-01 20:57:01 +00004996static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4997 struct class64_t c;
4998 const char *r;
4999 uint32_t offset, left;
5000 SectionRef S;
5001 const char *name;
5002 uint64_t isa_n_value, n_value;
5003
5004 r = get_pointer_64(p, offset, left, S, info);
5005 if (r == nullptr || left < sizeof(struct class64_t))
5006 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005007 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005008 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5009 swapStruct(c);
5010
5011 outs() << " isa " << format("0x%" PRIx64, c.isa);
5012 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5013 isa_n_value, c.isa);
5014 if (name != nullptr)
5015 outs() << " " << name;
5016 outs() << "\n";
5017
5018 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5019 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5020 n_value, c.superclass);
5021 if (name != nullptr)
5022 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005023 else {
5024 name = get_dyld_bind_info_symbolname(S.getAddress() +
5025 offset + offsetof(struct class64_t, superclass), info);
5026 if (name != nullptr)
5027 outs() << " " << name;
5028 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005029 outs() << "\n";
5030
5031 outs() << " cache " << format("0x%" PRIx64, c.cache);
5032 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5033 n_value, c.cache);
5034 if (name != nullptr)
5035 outs() << " " << name;
5036 outs() << "\n";
5037
5038 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5039 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5040 n_value, c.vtable);
5041 if (name != nullptr)
5042 outs() << " " << name;
5043 outs() << "\n";
5044
5045 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5046 n_value, c.data);
5047 outs() << " data ";
5048 if (n_value != 0) {
5049 if (info->verbose && name != nullptr)
5050 outs() << name;
5051 else
5052 outs() << format("0x%" PRIx64, n_value);
5053 if (c.data != 0)
5054 outs() << " + " << format("0x%" PRIx64, c.data);
5055 } else
5056 outs() << format("0x%" PRIx64, c.data);
5057 outs() << " (struct class_ro_t *)";
5058
5059 // This is a Swift class if some of the low bits of the pointer are set.
5060 if ((c.data + n_value) & 0x7)
5061 outs() << " Swift class";
5062 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005063 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005064 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5065 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005066
Kevin Enderbyaac75382015-10-08 16:56:35 +00005067 if (!is_meta_class &&
5068 c.isa + isa_n_value != p &&
5069 c.isa + isa_n_value != 0 &&
5070 info->depth < 100) {
5071 info->depth++;
5072 outs() << "Meta Class\n";
5073 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005074 }
5075}
5076
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005077static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5078 struct class32_t c;
5079 const char *r;
5080 uint32_t offset, left;
5081 SectionRef S;
5082 const char *name;
5083
5084 r = get_pointer_32(p, offset, left, S, info);
5085 if (r == nullptr)
5086 return;
5087 memset(&c, '\0', sizeof(struct class32_t));
5088 if (left < sizeof(struct class32_t)) {
5089 memcpy(&c, r, left);
5090 outs() << " (class_t entends past the end of the section)\n";
5091 } else
5092 memcpy(&c, r, sizeof(struct class32_t));
5093 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5094 swapStruct(c);
5095
5096 outs() << " isa " << format("0x%" PRIx32, c.isa);
5097 name =
5098 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5099 if (name != nullptr)
5100 outs() << " " << name;
5101 outs() << "\n";
5102
5103 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5104 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5105 c.superclass);
5106 if (name != nullptr)
5107 outs() << " " << name;
5108 outs() << "\n";
5109
5110 outs() << " cache " << format("0x%" PRIx32, c.cache);
5111 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5112 c.cache);
5113 if (name != nullptr)
5114 outs() << " " << name;
5115 outs() << "\n";
5116
5117 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5118 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5119 c.vtable);
5120 if (name != nullptr)
5121 outs() << " " << name;
5122 outs() << "\n";
5123
5124 name =
5125 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5126 outs() << " data " << format("0x%" PRIx32, c.data)
5127 << " (struct class_ro_t *)";
5128
5129 // This is a Swift class if some of the low bits of the pointer are set.
5130 if (c.data & 0x3)
5131 outs() << " Swift class";
5132 outs() << "\n";
5133 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005134 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5135 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005136
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005137 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005138 outs() << "Meta Class\n";
5139 print_class32_t(c.isa, info);
5140 }
5141}
5142
Kevin Enderby846c0002015-04-16 17:19:59 +00005143static void print_objc_class_t(struct objc_class_t *objc_class,
5144 struct DisassembleInfo *info) {
5145 uint32_t offset, left, xleft;
5146 const char *name, *p, *ivar_list;
5147 SectionRef S;
5148 int32_t i;
5149 struct objc_ivar_list_t objc_ivar_list;
5150 struct objc_ivar_t ivar;
5151
5152 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5153 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5154 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5155 if (name != nullptr)
5156 outs() << format(" %.*s", left, name);
5157 else
5158 outs() << " (not in an __OBJC section)";
5159 }
5160 outs() << "\n";
5161
5162 outs() << "\t super_class "
5163 << format("0x%08" PRIx32, objc_class->super_class);
5164 if (info->verbose) {
5165 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5166 if (name != nullptr)
5167 outs() << format(" %.*s", left, name);
5168 else
5169 outs() << " (not in an __OBJC section)";
5170 }
5171 outs() << "\n";
5172
5173 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5174 if (info->verbose) {
5175 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5176 if (name != nullptr)
5177 outs() << format(" %.*s", left, name);
5178 else
5179 outs() << " (not in an __OBJC section)";
5180 }
5181 outs() << "\n";
5182
5183 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5184 << "\n";
5185
5186 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5187 if (info->verbose) {
5188 if (CLS_GETINFO(objc_class, CLS_CLASS))
5189 outs() << " CLS_CLASS";
5190 else if (CLS_GETINFO(objc_class, CLS_META))
5191 outs() << " CLS_META";
5192 }
5193 outs() << "\n";
5194
5195 outs() << "\t instance_size "
5196 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5197
5198 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5199 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5200 if (p != nullptr) {
5201 if (left > sizeof(struct objc_ivar_list_t)) {
5202 outs() << "\n";
5203 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5204 } else {
5205 outs() << " (entends past the end of the section)\n";
5206 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5207 memcpy(&objc_ivar_list, p, left);
5208 }
5209 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5210 swapStruct(objc_ivar_list);
5211 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5212 ivar_list = p + sizeof(struct objc_ivar_list_t);
5213 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5214 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5215 outs() << "\t\t remaining ivar's extend past the of the section\n";
5216 break;
5217 }
5218 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5219 sizeof(struct objc_ivar_t));
5220 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5221 swapStruct(ivar);
5222
5223 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5224 if (info->verbose) {
5225 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5226 if (name != nullptr)
5227 outs() << format(" %.*s", xleft, name);
5228 else
5229 outs() << " (not in an __OBJC section)";
5230 }
5231 outs() << "\n";
5232
5233 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5234 if (info->verbose) {
5235 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5236 if (name != nullptr)
5237 outs() << format(" %.*s", xleft, name);
5238 else
5239 outs() << " (not in an __OBJC section)";
5240 }
5241 outs() << "\n";
5242
5243 outs() << "\t\t ivar_offset "
5244 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5245 }
5246 } else {
5247 outs() << " (not in an __OBJC section)\n";
5248 }
5249
5250 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5251 if (print_method_list(objc_class->methodLists, info))
5252 outs() << " (not in an __OBJC section)\n";
5253
5254 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5255 << "\n";
5256
5257 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5258 if (print_protocol_list(objc_class->protocols, 16, info))
5259 outs() << " (not in an __OBJC section)\n";
5260}
5261
5262static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5263 struct DisassembleInfo *info) {
5264 uint32_t offset, left;
5265 const char *name;
5266 SectionRef S;
5267
5268 outs() << "\t category name "
5269 << format("0x%08" PRIx32, objc_category->category_name);
5270 if (info->verbose) {
5271 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5272 true);
5273 if (name != nullptr)
5274 outs() << format(" %.*s", left, name);
5275 else
5276 outs() << " (not in an __OBJC section)";
5277 }
5278 outs() << "\n";
5279
5280 outs() << "\t\t class name "
5281 << format("0x%08" PRIx32, objc_category->class_name);
5282 if (info->verbose) {
5283 name =
5284 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5285 if (name != nullptr)
5286 outs() << format(" %.*s", left, name);
5287 else
5288 outs() << " (not in an __OBJC section)";
5289 }
5290 outs() << "\n";
5291
5292 outs() << "\t instance methods "
5293 << format("0x%08" PRIx32, objc_category->instance_methods);
5294 if (print_method_list(objc_category->instance_methods, info))
5295 outs() << " (not in an __OBJC section)\n";
5296
5297 outs() << "\t class methods "
5298 << format("0x%08" PRIx32, objc_category->class_methods);
5299 if (print_method_list(objc_category->class_methods, info))
5300 outs() << " (not in an __OBJC section)\n";
5301}
5302
Kevin Enderby0fc11822015-04-01 20:57:01 +00005303static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5304 struct category64_t c;
5305 const char *r;
5306 uint32_t offset, xoffset, left;
5307 SectionRef S, xS;
5308 const char *name, *sym_name;
5309 uint64_t n_value;
5310
5311 r = get_pointer_64(p, offset, left, S, info);
5312 if (r == nullptr)
5313 return;
5314 memset(&c, '\0', sizeof(struct category64_t));
5315 if (left < sizeof(struct category64_t)) {
5316 memcpy(&c, r, left);
5317 outs() << " (category_t entends past the end of the section)\n";
5318 } else
5319 memcpy(&c, r, sizeof(struct category64_t));
5320 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5321 swapStruct(c);
5322
5323 outs() << " name ";
5324 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5325 info, n_value, c.name);
5326 if (n_value != 0) {
5327 if (info->verbose && sym_name != nullptr)
5328 outs() << sym_name;
5329 else
5330 outs() << format("0x%" PRIx64, n_value);
5331 if (c.name != 0)
5332 outs() << " + " << format("0x%" PRIx64, c.name);
5333 } else
5334 outs() << format("0x%" PRIx64, c.name);
5335 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5336 if (name != nullptr)
5337 outs() << format(" %.*s", left, name);
5338 outs() << "\n";
5339
5340 outs() << " cls ";
5341 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5342 n_value, c.cls);
5343 if (n_value != 0) {
5344 if (info->verbose && sym_name != nullptr)
5345 outs() << sym_name;
5346 else
5347 outs() << format("0x%" PRIx64, n_value);
5348 if (c.cls != 0)
5349 outs() << " + " << format("0x%" PRIx64, c.cls);
5350 } else
5351 outs() << format("0x%" PRIx64, c.cls);
5352 outs() << "\n";
5353 if (c.cls + n_value != 0)
5354 print_class64_t(c.cls + n_value, info);
5355
5356 outs() << " instanceMethods ";
5357 sym_name =
5358 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5359 info, n_value, c.instanceMethods);
5360 if (n_value != 0) {
5361 if (info->verbose && sym_name != nullptr)
5362 outs() << sym_name;
5363 else
5364 outs() << format("0x%" PRIx64, n_value);
5365 if (c.instanceMethods != 0)
5366 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5367 } else
5368 outs() << format("0x%" PRIx64, c.instanceMethods);
5369 outs() << "\n";
5370 if (c.instanceMethods + n_value != 0)
5371 print_method_list64_t(c.instanceMethods + n_value, info, "");
5372
5373 outs() << " classMethods ";
5374 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5375 S, info, n_value, c.classMethods);
5376 if (n_value != 0) {
5377 if (info->verbose && sym_name != nullptr)
5378 outs() << sym_name;
5379 else
5380 outs() << format("0x%" PRIx64, n_value);
5381 if (c.classMethods != 0)
5382 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5383 } else
5384 outs() << format("0x%" PRIx64, c.classMethods);
5385 outs() << "\n";
5386 if (c.classMethods + n_value != 0)
5387 print_method_list64_t(c.classMethods + n_value, info, "");
5388
5389 outs() << " protocols ";
5390 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5391 info, n_value, c.protocols);
5392 if (n_value != 0) {
5393 if (info->verbose && sym_name != nullptr)
5394 outs() << sym_name;
5395 else
5396 outs() << format("0x%" PRIx64, n_value);
5397 if (c.protocols != 0)
5398 outs() << " + " << format("0x%" PRIx64, c.protocols);
5399 } else
5400 outs() << format("0x%" PRIx64, c.protocols);
5401 outs() << "\n";
5402 if (c.protocols + n_value != 0)
5403 print_protocol_list64_t(c.protocols + n_value, info);
5404
5405 outs() << "instanceProperties ";
5406 sym_name =
5407 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5408 S, info, n_value, c.instanceProperties);
5409 if (n_value != 0) {
5410 if (info->verbose && sym_name != nullptr)
5411 outs() << sym_name;
5412 else
5413 outs() << format("0x%" PRIx64, n_value);
5414 if (c.instanceProperties != 0)
5415 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5416 } else
5417 outs() << format("0x%" PRIx64, c.instanceProperties);
5418 outs() << "\n";
5419 if (c.instanceProperties + n_value != 0)
5420 print_objc_property_list64(c.instanceProperties + n_value, info);
5421}
5422
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005423static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5424 struct category32_t c;
5425 const char *r;
5426 uint32_t offset, left;
5427 SectionRef S, xS;
5428 const char *name;
5429
5430 r = get_pointer_32(p, offset, left, S, info);
5431 if (r == nullptr)
5432 return;
5433 memset(&c, '\0', sizeof(struct category32_t));
5434 if (left < sizeof(struct category32_t)) {
5435 memcpy(&c, r, left);
5436 outs() << " (category_t entends past the end of the section)\n";
5437 } else
5438 memcpy(&c, r, sizeof(struct category32_t));
5439 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5440 swapStruct(c);
5441
5442 outs() << " name " << format("0x%" PRIx32, c.name);
5443 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5444 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005445 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005446 outs() << " " << name;
5447 outs() << "\n";
5448
5449 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5450 if (c.cls != 0)
5451 print_class32_t(c.cls, info);
5452 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5453 << "\n";
5454 if (c.instanceMethods != 0)
5455 print_method_list32_t(c.instanceMethods, info, "");
5456 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5457 << "\n";
5458 if (c.classMethods != 0)
5459 print_method_list32_t(c.classMethods, info, "");
5460 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5461 if (c.protocols != 0)
5462 print_protocol_list32_t(c.protocols, info);
5463 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5464 << "\n";
5465 if (c.instanceProperties != 0)
5466 print_objc_property_list32(c.instanceProperties, info);
5467}
5468
Kevin Enderby0fc11822015-04-01 20:57:01 +00005469static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5470 uint32_t i, left, offset, xoffset;
5471 uint64_t p, n_value;
5472 struct message_ref64 mr;
5473 const char *name, *sym_name;
5474 const char *r;
5475 SectionRef xS;
5476
5477 if (S == SectionRef())
5478 return;
5479
5480 StringRef SectName;
5481 S.getName(SectName);
5482 DataRefImpl Ref = S.getRawDataRefImpl();
5483 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5484 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5485 offset = 0;
5486 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5487 p = S.getAddress() + i;
5488 r = get_pointer_64(p, offset, left, S, info);
5489 if (r == nullptr)
5490 return;
5491 memset(&mr, '\0', sizeof(struct message_ref64));
5492 if (left < sizeof(struct message_ref64)) {
5493 memcpy(&mr, r, left);
5494 outs() << " (message_ref entends past the end of the section)\n";
5495 } else
5496 memcpy(&mr, r, sizeof(struct message_ref64));
5497 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5498 swapStruct(mr);
5499
5500 outs() << " imp ";
5501 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5502 n_value, mr.imp);
5503 if (n_value != 0) {
5504 outs() << format("0x%" PRIx64, n_value) << " ";
5505 if (mr.imp != 0)
5506 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5507 } else
5508 outs() << format("0x%" PRIx64, mr.imp) << " ";
5509 if (name != nullptr)
5510 outs() << " " << name;
5511 outs() << "\n";
5512
5513 outs() << " sel ";
5514 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5515 info, n_value, mr.sel);
5516 if (n_value != 0) {
5517 if (info->verbose && sym_name != nullptr)
5518 outs() << sym_name;
5519 else
5520 outs() << format("0x%" PRIx64, n_value);
5521 if (mr.sel != 0)
5522 outs() << " + " << format("0x%" PRIx64, mr.sel);
5523 } else
5524 outs() << format("0x%" PRIx64, mr.sel);
5525 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5526 if (name != nullptr)
5527 outs() << format(" %.*s", left, name);
5528 outs() << "\n";
5529
5530 offset += sizeof(struct message_ref64);
5531 }
5532}
5533
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005534static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5535 uint32_t i, left, offset, xoffset, p;
5536 struct message_ref32 mr;
5537 const char *name, *r;
5538 SectionRef xS;
5539
5540 if (S == SectionRef())
5541 return;
5542
5543 StringRef SectName;
5544 S.getName(SectName);
5545 DataRefImpl Ref = S.getRawDataRefImpl();
5546 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5547 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5548 offset = 0;
5549 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5550 p = S.getAddress() + i;
5551 r = get_pointer_32(p, offset, left, S, info);
5552 if (r == nullptr)
5553 return;
5554 memset(&mr, '\0', sizeof(struct message_ref32));
5555 if (left < sizeof(struct message_ref32)) {
5556 memcpy(&mr, r, left);
5557 outs() << " (message_ref entends past the end of the section)\n";
5558 } else
5559 memcpy(&mr, r, sizeof(struct message_ref32));
5560 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5561 swapStruct(mr);
5562
5563 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5564 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5565 mr.imp);
5566 if (name != nullptr)
5567 outs() << " " << name;
5568 outs() << "\n";
5569
5570 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5571 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5572 if (name != nullptr)
5573 outs() << " " << name;
5574 outs() << "\n";
5575
5576 offset += sizeof(struct message_ref32);
5577 }
5578}
5579
Kevin Enderby0fc11822015-04-01 20:57:01 +00005580static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5581 uint32_t left, offset, swift_version;
5582 uint64_t p;
5583 struct objc_image_info64 o;
5584 const char *r;
5585
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005586 if (S == SectionRef())
5587 return;
5588
Kevin Enderby0fc11822015-04-01 20:57:01 +00005589 StringRef SectName;
5590 S.getName(SectName);
5591 DataRefImpl Ref = S.getRawDataRefImpl();
5592 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5593 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5594 p = S.getAddress();
5595 r = get_pointer_64(p, offset, left, S, info);
5596 if (r == nullptr)
5597 return;
5598 memset(&o, '\0', sizeof(struct objc_image_info64));
5599 if (left < sizeof(struct objc_image_info64)) {
5600 memcpy(&o, r, left);
5601 outs() << " (objc_image_info entends past the end of the section)\n";
5602 } else
5603 memcpy(&o, r, sizeof(struct objc_image_info64));
5604 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5605 swapStruct(o);
5606 outs() << " version " << o.version << "\n";
5607 outs() << " flags " << format("0x%" PRIx32, o.flags);
5608 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5609 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5610 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5611 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005612 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5613 outs() << " OBJC_IMAGE_IS_SIMULATED";
5614 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5615 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005616 swift_version = (o.flags >> 8) & 0xff;
5617 if (swift_version != 0) {
5618 if (swift_version == 1)
5619 outs() << " Swift 1.0";
5620 else if (swift_version == 2)
5621 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005622 else if(swift_version == 3)
5623 outs() << " Swift 2.0";
5624 else if(swift_version == 4)
5625 outs() << " Swift 3.0";
5626 else if(swift_version == 5)
5627 outs() << " Swift 4.0";
5628 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005629 outs() << " Swift 4.1/Swift 4.2";
5630 else if(swift_version == 7)
5631 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005632 else
5633 outs() << " unknown future Swift version (" << swift_version << ")";
5634 }
5635 outs() << "\n";
5636}
5637
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005638static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5639 uint32_t left, offset, swift_version, p;
5640 struct objc_image_info32 o;
5641 const char *r;
5642
Kevin Enderby19be2512016-04-21 19:49:29 +00005643 if (S == SectionRef())
5644 return;
5645
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005646 StringRef SectName;
5647 S.getName(SectName);
5648 DataRefImpl Ref = S.getRawDataRefImpl();
5649 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5650 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5651 p = S.getAddress();
5652 r = get_pointer_32(p, offset, left, S, info);
5653 if (r == nullptr)
5654 return;
5655 memset(&o, '\0', sizeof(struct objc_image_info32));
5656 if (left < sizeof(struct objc_image_info32)) {
5657 memcpy(&o, r, left);
5658 outs() << " (objc_image_info entends past the end of the section)\n";
5659 } else
5660 memcpy(&o, r, sizeof(struct objc_image_info32));
5661 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5662 swapStruct(o);
5663 outs() << " version " << o.version << "\n";
5664 outs() << " flags " << format("0x%" PRIx32, o.flags);
5665 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5666 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5667 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5668 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5669 swift_version = (o.flags >> 8) & 0xff;
5670 if (swift_version != 0) {
5671 if (swift_version == 1)
5672 outs() << " Swift 1.0";
5673 else if (swift_version == 2)
5674 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005675 else if(swift_version == 3)
5676 outs() << " Swift 2.0";
5677 else if(swift_version == 4)
5678 outs() << " Swift 3.0";
5679 else if(swift_version == 5)
5680 outs() << " Swift 4.0";
5681 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005682 outs() << " Swift 4.1/Swift 4.2";
5683 else if(swift_version == 7)
5684 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005685 else
5686 outs() << " unknown future Swift version (" << swift_version << ")";
5687 }
5688 outs() << "\n";
5689}
5690
Kevin Enderby846c0002015-04-16 17:19:59 +00005691static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5692 uint32_t left, offset, p;
5693 struct imageInfo_t o;
5694 const char *r;
5695
5696 StringRef SectName;
5697 S.getName(SectName);
5698 DataRefImpl Ref = S.getRawDataRefImpl();
5699 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5700 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5701 p = S.getAddress();
5702 r = get_pointer_32(p, offset, left, S, info);
5703 if (r == nullptr)
5704 return;
5705 memset(&o, '\0', sizeof(struct imageInfo_t));
5706 if (left < sizeof(struct imageInfo_t)) {
5707 memcpy(&o, r, left);
5708 outs() << " (imageInfo entends past the end of the section)\n";
5709 } else
5710 memcpy(&o, r, sizeof(struct imageInfo_t));
5711 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5712 swapStruct(o);
5713 outs() << " version " << o.version << "\n";
5714 outs() << " flags " << format("0x%" PRIx32, o.flags);
5715 if (o.flags & 0x1)
5716 outs() << " F&C";
5717 if (o.flags & 0x2)
5718 outs() << " GC";
5719 if (o.flags & 0x4)
5720 outs() << " GC-only";
5721 else
5722 outs() << " RR";
5723 outs() << "\n";
5724}
5725
Kevin Enderby0fc11822015-04-01 20:57:01 +00005726static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5727 SymbolAddressMap AddrMap;
5728 if (verbose)
5729 CreateSymbolAddressMap(O, &AddrMap);
5730
5731 std::vector<SectionRef> Sections;
5732 for (const SectionRef &Section : O->sections()) {
5733 StringRef SectName;
5734 Section.getName(SectName);
5735 Sections.push_back(Section);
5736 }
5737
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005738 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005739
Davide Italiano62507042015-12-11 22:27:59 +00005740 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5741 if (CL == SectionRef())
5742 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005743 if (CL == SectionRef())
5744 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5745 if (CL == SectionRef())
5746 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005747 info.S = CL;
5748 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005749
Davide Italiano62507042015-12-11 22:27:59 +00005750 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5751 if (CR == SectionRef())
5752 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005753 if (CR == SectionRef())
5754 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5755 if (CR == SectionRef())
5756 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005757 info.S = CR;
5758 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005759
Davide Italiano62507042015-12-11 22:27:59 +00005760 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5761 if (SR == SectionRef())
5762 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005763 if (SR == SectionRef())
5764 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5765 if (SR == SectionRef())
5766 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005767 info.S = SR;
5768 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005769
Davide Italiano62507042015-12-11 22:27:59 +00005770 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5771 if (CA == SectionRef())
5772 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005773 if (CA == SectionRef())
5774 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5775 if (CA == SectionRef())
5776 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005777 info.S = CA;
5778 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005779
Davide Italiano62507042015-12-11 22:27:59 +00005780 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5781 if (PL == SectionRef())
5782 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005783 if (PL == SectionRef())
5784 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5785 if (PL == SectionRef())
5786 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005787 info.S = PL;
5788 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005789
Davide Italiano62507042015-12-11 22:27:59 +00005790 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5791 if (MR == SectionRef())
5792 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005793 if (MR == SectionRef())
5794 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5795 if (MR == SectionRef())
5796 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005797 info.S = MR;
5798 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005799
Davide Italiano62507042015-12-11 22:27:59 +00005800 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5801 if (II == SectionRef())
5802 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005803 if (II == SectionRef())
5804 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5805 if (II == SectionRef())
5806 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005807 info.S = II;
5808 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005809}
5810
5811static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005812 SymbolAddressMap AddrMap;
5813 if (verbose)
5814 CreateSymbolAddressMap(O, &AddrMap);
5815
5816 std::vector<SectionRef> Sections;
5817 for (const SectionRef &Section : O->sections()) {
5818 StringRef SectName;
5819 Section.getName(SectName);
5820 Sections.push_back(Section);
5821 }
5822
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005823 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005824
Kevin Enderby5879a482017-02-09 17:56:26 +00005825 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5826 if (CL == SectionRef())
5827 CL = get_section(O, "__DATA", "__objc_classlist");
5828 if (CL == SectionRef())
5829 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5830 if (CL == SectionRef())
5831 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5832 info.S = CL;
5833 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005834
Kevin Enderby5879a482017-02-09 17:56:26 +00005835 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5836 if (CR == SectionRef())
5837 CR = get_section(O, "__DATA", "__objc_classrefs");
5838 if (CR == SectionRef())
5839 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5840 if (CR == SectionRef())
5841 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5842 info.S = CR;
5843 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005844
Kevin Enderby5879a482017-02-09 17:56:26 +00005845 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5846 if (SR == SectionRef())
5847 SR = get_section(O, "__DATA", "__objc_superrefs");
5848 if (SR == SectionRef())
5849 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5850 if (SR == SectionRef())
5851 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5852 info.S = SR;
5853 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005854
Kevin Enderby5879a482017-02-09 17:56:26 +00005855 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5856 if (CA == SectionRef())
5857 CA = get_section(O, "__DATA", "__objc_catlist");
5858 if (CA == SectionRef())
5859 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5860 if (CA == SectionRef())
5861 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5862 info.S = CA;
5863 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005864
Kevin Enderby5879a482017-02-09 17:56:26 +00005865 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5866 if (PL == SectionRef())
5867 PL = get_section(O, "__DATA", "__objc_protolist");
5868 if (PL == SectionRef())
5869 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5870 if (PL == SectionRef())
5871 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5872 info.S = PL;
5873 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005874
Kevin Enderby5879a482017-02-09 17:56:26 +00005875 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5876 if (MR == SectionRef())
5877 MR = get_section(O, "__DATA", "__objc_msgrefs");
5878 if (MR == SectionRef())
5879 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5880 if (MR == SectionRef())
5881 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5882 info.S = MR;
5883 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005884
Kevin Enderby5879a482017-02-09 17:56:26 +00005885 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5886 if (II == SectionRef())
5887 II = get_section(O, "__DATA", "__objc_imageinfo");
5888 if (II == SectionRef())
5889 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5890 if (II == SectionRef())
5891 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5892 info.S = II;
5893 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005894}
5895
5896static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005897 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5898 const char *r, *name, *defs;
5899 struct objc_module_t module;
5900 SectionRef S, xS;
5901 struct objc_symtab_t symtab;
5902 struct objc_class_t objc_class;
5903 struct objc_category_t objc_category;
5904
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005905 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005906 S = get_section(O, "__OBJC", "__module_info");
5907 if (S == SectionRef())
5908 return false;
5909
5910 SymbolAddressMap AddrMap;
5911 if (verbose)
5912 CreateSymbolAddressMap(O, &AddrMap);
5913
5914 std::vector<SectionRef> Sections;
5915 for (const SectionRef &Section : O->sections()) {
5916 StringRef SectName;
5917 Section.getName(SectName);
5918 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005919 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005920
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005921 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00005922
5923 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5924 p = S.getAddress() + i;
5925 r = get_pointer_32(p, offset, left, S, &info, true);
5926 if (r == nullptr)
5927 return true;
5928 memset(&module, '\0', sizeof(struct objc_module_t));
5929 if (left < sizeof(struct objc_module_t)) {
5930 memcpy(&module, r, left);
5931 outs() << " (module extends past end of __module_info section)\n";
5932 } else
5933 memcpy(&module, r, sizeof(struct objc_module_t));
5934 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5935 swapStruct(module);
5936
5937 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5938 outs() << " version " << module.version << "\n";
5939 outs() << " size " << module.size << "\n";
5940 outs() << " name ";
5941 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5942 if (name != nullptr)
5943 outs() << format("%.*s", left, name);
5944 else
5945 outs() << format("0x%08" PRIx32, module.name)
5946 << "(not in an __OBJC section)";
5947 outs() << "\n";
5948
5949 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5950 if (module.symtab == 0 || r == nullptr) {
5951 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5952 << " (not in an __OBJC section)\n";
5953 continue;
5954 }
5955 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5956 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5957 defs_left = 0;
5958 defs = nullptr;
5959 if (left < sizeof(struct objc_symtab_t)) {
5960 memcpy(&symtab, r, left);
5961 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5962 } else {
5963 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5964 if (left > sizeof(struct objc_symtab_t)) {
5965 defs_left = left - sizeof(struct objc_symtab_t);
5966 defs = r + sizeof(struct objc_symtab_t);
5967 }
5968 }
5969 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5970 swapStruct(symtab);
5971
5972 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5973 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5974 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5975 if (r == nullptr)
5976 outs() << " (not in an __OBJC section)";
5977 outs() << "\n";
5978 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5979 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5980 if (symtab.cls_def_cnt > 0)
5981 outs() << "\tClass Definitions\n";
5982 for (j = 0; j < symtab.cls_def_cnt; j++) {
5983 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5984 outs() << "\t(remaining class defs entries entends past the end of the "
5985 << "section)\n";
5986 break;
5987 }
5988 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5989 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5990 sys::swapByteOrder(def);
5991
5992 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5993 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5994 if (r != nullptr) {
5995 if (left > sizeof(struct objc_class_t)) {
5996 outs() << "\n";
5997 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5998 } else {
5999 outs() << " (entends past the end of the section)\n";
6000 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6001 memcpy(&objc_class, r, left);
6002 }
6003 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6004 swapStruct(objc_class);
6005 print_objc_class_t(&objc_class, &info);
6006 } else {
6007 outs() << "(not in an __OBJC section)\n";
6008 }
6009
6010 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6011 outs() << "\tMeta Class";
6012 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6013 if (r != nullptr) {
6014 if (left > sizeof(struct objc_class_t)) {
6015 outs() << "\n";
6016 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6017 } else {
6018 outs() << " (entends past the end of the section)\n";
6019 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6020 memcpy(&objc_class, r, left);
6021 }
6022 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6023 swapStruct(objc_class);
6024 print_objc_class_t(&objc_class, &info);
6025 } else {
6026 outs() << "(not in an __OBJC section)\n";
6027 }
6028 }
6029 }
6030 if (symtab.cat_def_cnt > 0)
6031 outs() << "\tCategory Definitions\n";
6032 for (j = 0; j < symtab.cat_def_cnt; j++) {
6033 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6034 outs() << "\t(remaining category defs entries entends past the end of "
6035 << "the section)\n";
6036 break;
6037 }
6038 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6039 sizeof(uint32_t));
6040 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6041 sys::swapByteOrder(def);
6042
6043 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6044 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6045 << format("0x%08" PRIx32, def);
6046 if (r != nullptr) {
6047 if (left > sizeof(struct objc_category_t)) {
6048 outs() << "\n";
6049 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6050 } else {
6051 outs() << " (entends past the end of the section)\n";
6052 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6053 memcpy(&objc_category, r, left);
6054 }
6055 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6056 swapStruct(objc_category);
6057 print_objc_objc_category_t(&objc_category, &info);
6058 } else {
6059 outs() << "(not in an __OBJC section)\n";
6060 }
6061 }
6062 }
6063 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6064 if (II != SectionRef())
6065 print_image_info(II, &info);
6066
6067 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006068}
6069
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006070static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6071 uint32_t size, uint32_t addr) {
6072 SymbolAddressMap AddrMap;
6073 CreateSymbolAddressMap(O, &AddrMap);
6074
6075 std::vector<SectionRef> Sections;
6076 for (const SectionRef &Section : O->sections()) {
6077 StringRef SectName;
6078 Section.getName(SectName);
6079 Sections.push_back(Section);
6080 }
6081
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006082 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006083
6084 const char *p;
6085 struct objc_protocol_t protocol;
6086 uint32_t left, paddr;
6087 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6088 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6089 left = size - (p - sect);
6090 if (left < sizeof(struct objc_protocol_t)) {
6091 outs() << "Protocol extends past end of __protocol section\n";
6092 memcpy(&protocol, p, left);
6093 } else
6094 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6095 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6096 swapStruct(protocol);
6097 paddr = addr + (p - sect);
6098 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6099 if (print_protocol(paddr, 0, &info))
6100 outs() << "(not in an __OBJC section)\n";
6101 }
6102}
6103
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006104#ifdef HAVE_LIBXAR
6105inline void swapStruct(struct xar_header &xar) {
6106 sys::swapByteOrder(xar.magic);
6107 sys::swapByteOrder(xar.size);
6108 sys::swapByteOrder(xar.version);
6109 sys::swapByteOrder(xar.toc_length_compressed);
6110 sys::swapByteOrder(xar.toc_length_uncompressed);
6111 sys::swapByteOrder(xar.cksum_alg);
6112}
6113
6114static void PrintModeVerbose(uint32_t mode) {
6115 switch(mode & S_IFMT){
6116 case S_IFDIR:
6117 outs() << "d";
6118 break;
6119 case S_IFCHR:
6120 outs() << "c";
6121 break;
6122 case S_IFBLK:
6123 outs() << "b";
6124 break;
6125 case S_IFREG:
6126 outs() << "-";
6127 break;
6128 case S_IFLNK:
6129 outs() << "l";
6130 break;
6131 case S_IFSOCK:
6132 outs() << "s";
6133 break;
6134 default:
6135 outs() << "?";
6136 break;
6137 }
6138
6139 /* owner permissions */
6140 if(mode & S_IREAD)
6141 outs() << "r";
6142 else
6143 outs() << "-";
6144 if(mode & S_IWRITE)
6145 outs() << "w";
6146 else
6147 outs() << "-";
6148 if(mode & S_ISUID)
6149 outs() << "s";
6150 else if(mode & S_IEXEC)
6151 outs() << "x";
6152 else
6153 outs() << "-";
6154
6155 /* group permissions */
6156 if(mode & (S_IREAD >> 3))
6157 outs() << "r";
6158 else
6159 outs() << "-";
6160 if(mode & (S_IWRITE >> 3))
6161 outs() << "w";
6162 else
6163 outs() << "-";
6164 if(mode & S_ISGID)
6165 outs() << "s";
6166 else if(mode & (S_IEXEC >> 3))
6167 outs() << "x";
6168 else
6169 outs() << "-";
6170
6171 /* other permissions */
6172 if(mode & (S_IREAD >> 6))
6173 outs() << "r";
6174 else
6175 outs() << "-";
6176 if(mode & (S_IWRITE >> 6))
6177 outs() << "w";
6178 else
6179 outs() << "-";
6180 if(mode & S_ISVTX)
6181 outs() << "t";
6182 else if(mode & (S_IEXEC >> 6))
6183 outs() << "x";
6184 else
6185 outs() << "-";
6186}
6187
6188static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006189 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006190 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6191 char *endp;
6192 uint32_t mode_value;
6193
Francis Ricci6f942972017-10-06 15:33:28 +00006194 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006195 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006196 WithColor::error(errs(), "llvm-objdump")
6197 << "can't obtain an xar iterator for xar archive " << XarFilename
6198 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006199 return;
6200 }
6201
6202 // Go through the xar's files.
6203 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006204 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006205 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006206 WithColor::error(errs(), "llvm-objdump")
6207 << "can't obtain an xar iterator for xar archive " << XarFilename
6208 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006209 return;
6210 }
6211 type = nullptr;
6212 mode = nullptr;
6213 user = nullptr;
6214 group = nullptr;
6215 size = nullptr;
6216 mtime = nullptr;
6217 name = nullptr;
6218 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006219 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006220 xar_prop_get(xf, key, &val);
6221#if 0 // Useful for debugging.
6222 outs() << "key: " << key << " value: " << val << "\n";
6223#endif
6224 if(strcmp(key, "type") == 0)
6225 type = val;
6226 if(strcmp(key, "mode") == 0)
6227 mode = val;
6228 if(strcmp(key, "user") == 0)
6229 user = val;
6230 if(strcmp(key, "group") == 0)
6231 group = val;
6232 if(strcmp(key, "data/size") == 0)
6233 size = val;
6234 if(strcmp(key, "mtime") == 0)
6235 mtime = val;
6236 if(strcmp(key, "name") == 0)
6237 name = val;
6238 }
6239 if(mode != nullptr){
6240 mode_value = strtoul(mode, &endp, 8);
6241 if(*endp != '\0')
6242 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6243 if(strcmp(type, "file") == 0)
6244 mode_value |= S_IFREG;
6245 PrintModeVerbose(mode_value);
6246 outs() << " ";
6247 }
6248 if(user != nullptr)
6249 outs() << format("%10s/", user);
6250 if(group != nullptr)
6251 outs() << format("%-10s ", group);
6252 if(size != nullptr)
6253 outs() << format("%7s ", size);
6254 if(mtime != nullptr){
6255 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6256 outs() << *m;
6257 if(*m == 'T')
6258 m++;
6259 outs() << " ";
6260 for( ; *m != 'Z' && *m != '\0'; m++)
6261 outs() << *m;
6262 outs() << " ";
6263 }
6264 if(name != nullptr)
6265 outs() << name;
6266 outs() << "\n";
6267 }
6268}
6269
6270static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6271 uint32_t size, bool verbose,
6272 bool PrintXarHeader, bool PrintXarFileHeaders,
6273 std::string XarMemberName) {
6274 if(size < sizeof(struct xar_header)) {
6275 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6276 "of struct xar_header)\n";
6277 return;
6278 }
6279 struct xar_header XarHeader;
6280 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6281 if (sys::IsLittleEndianHost)
6282 swapStruct(XarHeader);
6283 if (PrintXarHeader) {
6284 if (!XarMemberName.empty())
6285 outs() << "In xar member " << XarMemberName << ": ";
6286 else
6287 outs() << "For (__LLVM,__bundle) section: ";
6288 outs() << "xar header\n";
6289 if (XarHeader.magic == XAR_HEADER_MAGIC)
6290 outs() << " magic XAR_HEADER_MAGIC\n";
6291 else
6292 outs() << " magic "
6293 << format_hex(XarHeader.magic, 10, true)
6294 << " (not XAR_HEADER_MAGIC)\n";
6295 outs() << " size " << XarHeader.size << "\n";
6296 outs() << " version " << XarHeader.version << "\n";
6297 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6298 << "\n";
6299 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6300 << "\n";
6301 outs() << " cksum_alg ";
6302 switch (XarHeader.cksum_alg) {
6303 case XAR_CKSUM_NONE:
6304 outs() << "XAR_CKSUM_NONE\n";
6305 break;
6306 case XAR_CKSUM_SHA1:
6307 outs() << "XAR_CKSUM_SHA1\n";
6308 break;
6309 case XAR_CKSUM_MD5:
6310 outs() << "XAR_CKSUM_MD5\n";
6311 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006312#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006313 case XAR_CKSUM_SHA256:
6314 outs() << "XAR_CKSUM_SHA256\n";
6315 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006316#endif
6317#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006318 case XAR_CKSUM_SHA512:
6319 outs() << "XAR_CKSUM_SHA512\n";
6320 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006321#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006322 default:
6323 outs() << XarHeader.cksum_alg << "\n";
6324 }
6325 }
6326
6327 SmallString<128> XarFilename;
6328 int FD;
6329 std::error_code XarEC =
6330 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6331 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006332 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006333 return;
6334 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006335 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006336 raw_fd_ostream &XarOut = XarFile.os();
6337 StringRef XarContents(sect, size);
6338 XarOut << XarContents;
6339 XarOut.close();
6340 if (XarOut.has_error())
6341 return;
6342
Francis Ricci6f942972017-10-06 15:33:28 +00006343 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006344 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006345 WithColor::error(errs(), "llvm-objdump")
6346 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006347 return;
6348 }
6349
6350 SmallString<128> TocFilename;
6351 std::error_code TocEC =
6352 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6353 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006354 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006355 return;
6356 }
6357 xar_serialize(xar, TocFilename.c_str());
6358
6359 if (PrintXarFileHeaders) {
6360 if (!XarMemberName.empty())
6361 outs() << "In xar member " << XarMemberName << ": ";
6362 else
6363 outs() << "For (__LLVM,__bundle) section: ";
6364 outs() << "xar archive files:\n";
6365 PrintXarFilesSummary(XarFilename.c_str(), xar);
6366 }
6367
6368 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6369 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6370 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006371 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006372 return;
6373 }
6374 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6375
6376 if (!XarMemberName.empty())
6377 outs() << "In xar member " << XarMemberName << ": ";
6378 else
6379 outs() << "For (__LLVM,__bundle) section: ";
6380 outs() << "xar table of contents:\n";
6381 outs() << Buffer->getBuffer() << "\n";
6382
6383 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006384 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006385 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006386 WithColor::error(errs(), "llvm-objdump")
6387 << "can't obtain an xar iterator for xar archive "
6388 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006389 return;
6390 }
6391 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6392 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006393 const char *member_name, *member_type, *member_size_string;
6394 size_t member_size;
6395
Francis Ricci6f942972017-10-06 15:33:28 +00006396 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006397 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006398 WithColor::error(errs(), "llvm-objdump")
6399 << "can't obtain an xar iterator for xar archive "
6400 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006401 return;
6402 }
6403 member_name = NULL;
6404 member_type = NULL;
6405 member_size_string = NULL;
6406 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006407 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006408 xar_prop_get(xf, key, &val);
6409#if 0 // Useful for debugging.
6410 outs() << "key: " << key << " value: " << val << "\n";
6411#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006412 if (strcmp(key, "name") == 0)
6413 member_name = val;
6414 if (strcmp(key, "type") == 0)
6415 member_type = val;
6416 if (strcmp(key, "data/size") == 0)
6417 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006418 }
6419 /*
6420 * If we find a file with a name, date/size and type properties
6421 * and with the type being "file" see if that is a xar file.
6422 */
6423 if (member_name != NULL && member_type != NULL &&
6424 strcmp(member_type, "file") == 0 &&
6425 member_size_string != NULL){
6426 // Extract the file into a buffer.
6427 char *endptr;
6428 member_size = strtoul(member_size_string, &endptr, 10);
6429 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006430 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006431 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006432#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006433 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006434#endif
6435 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006436 std::string OldXarMemberName;
6437 // If XarMemberName is already set this is nested. So
6438 // save the old name and create the nested name.
6439 if (!XarMemberName.empty()) {
6440 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006441 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006442 (Twine("[") + XarMemberName + "]" + member_name).str();
6443 } else {
6444 OldXarMemberName = "";
6445 XarMemberName = member_name;
6446 }
6447 // See if this is could be a xar file (nested).
6448 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006449#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006450 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006451#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006452 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006453 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006454 swapStruct(XarHeader);
6455 if (XarHeader.magic == XAR_HEADER_MAGIC)
6456 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006457 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006458 XarMemberName);
6459 }
6460 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006461 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006462 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006463 }
6464 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006465 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006466}
6467#endif // defined(HAVE_LIBXAR)
6468
Kevin Enderby0fc11822015-04-01 20:57:01 +00006469static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6470 if (O->is64Bit())
6471 printObjc2_64bit_MetaData(O, verbose);
6472 else {
6473 MachO::mach_header H;
6474 H = O->getHeader();
6475 if (H.cputype == MachO::CPU_TYPE_ARM)
6476 printObjc2_32bit_MetaData(O, verbose);
6477 else {
6478 // This is the 32-bit non-arm cputype case. Which is normally
6479 // the first Objective-C ABI. But it may be the case of a
6480 // binary for the iOS simulator which is the second Objective-C
6481 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6482 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006483 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006484 printObjc2_32bit_MetaData(O, verbose);
6485 }
6486 }
6487}
6488
Kevin Enderbybf246f52014-09-24 23:08:22 +00006489// GuessLiteralPointer returns a string which for the item in the Mach-O file
6490// for the address passed in as ReferenceValue for printing as a comment with
6491// the instruction and also returns the corresponding type of that item
6492// indirectly through ReferenceType.
6493//
6494// If ReferenceValue is an address of literal cstring then a pointer to the
6495// cstring is returned and ReferenceType is set to
6496// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6497//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006498// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6499// Class ref that name is returned and the ReferenceType is set accordingly.
6500//
6501// Lastly, literals which are Symbol address in a literal pool are looked for
6502// and if found the symbol name is returned and ReferenceType is set to
6503// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6504//
6505// If there is no item in the Mach-O file for the address passed in as
6506// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006507static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6508 uint64_t ReferencePC,
6509 uint64_t *ReferenceType,
6510 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006511 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006512 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6513 uint64_t sect_addr = info->S.getAddress();
6514 uint64_t sect_offset = ReferencePC - sect_addr;
6515 bool reloc_found = false;
6516 DataRefImpl Rel;
6517 MachO::any_relocation_info RE;
6518 bool isExtern = false;
6519 SymbolRef Symbol;
6520 for (const RelocationRef &Reloc : info->S.relocations()) {
6521 uint64_t RelocOffset = Reloc.getOffset();
6522 if (RelocOffset == sect_offset) {
6523 Rel = Reloc.getRawDataRefImpl();
6524 RE = info->O->getRelocation(Rel);
6525 if (info->O->isRelocationScattered(RE))
6526 continue;
6527 isExtern = info->O->getPlainRelocationExternal(RE);
6528 if (isExtern) {
6529 symbol_iterator RelocSym = Reloc.getSymbol();
6530 Symbol = *RelocSym;
6531 }
6532 reloc_found = true;
6533 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006534 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006535 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006536 // If there is an external relocation entry for a symbol in a section
6537 // then used that symbol's value for the value of the reference.
6538 if (reloc_found && isExtern) {
6539 if (info->O->getAnyRelocationPCRel(RE)) {
6540 unsigned Type = info->O->getAnyRelocationType(RE);
6541 if (Type == MachO::X86_64_RELOC_SIGNED) {
6542 ReferenceValue = Symbol.getValue();
6543 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006544 }
6545 }
6546 }
6547
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006548 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6549 // Message refs and Class refs.
6550 bool classref, selref, msgref, cfstring;
6551 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6552 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006553 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006554 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6555 // And the pointer_value in that section is typically zero as it will be
6556 // set by dyld as part of the "bind information".
6557 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6558 if (name != nullptr) {
6559 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006560 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006561 if (class_name != nullptr && class_name[1] == '_' &&
6562 class_name[2] != '\0') {
6563 info->class_name = class_name + 2;
6564 return name;
6565 }
6566 }
6567 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006568
David Blaikie33dd45d02015-03-23 18:39:02 +00006569 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006570 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6571 const char *name =
6572 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6573 if (name != nullptr)
6574 info->class_name = name;
6575 else
6576 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006577 return name;
6578 }
6579
David Blaikie33dd45d02015-03-23 18:39:02 +00006580 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006581 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6582 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6583 return name;
6584 }
6585
David Blaikie33dd45d02015-03-23 18:39:02 +00006586 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006587 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6588
6589 if (pointer_value != 0)
6590 ReferenceValue = pointer_value;
6591
6592 const char *name = GuessCstringPointer(ReferenceValue, info);
6593 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006594 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006595 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6596 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006597 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006598 info->class_name = nullptr;
6599 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6600 info->selector_name = name;
6601 } else
6602 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6603 return name;
6604 }
6605
6606 // Lastly look for an indirect symbol with this ReferenceValue which is in
6607 // a literal pool. If found return that symbol name.
6608 name = GuessIndirectSymbol(ReferenceValue, info);
6609 if (name) {
6610 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6611 return name;
6612 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006613
6614 return nullptr;
6615}
6616
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006617// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006618// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006619// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6620// is created and returns the symbol name that matches the ReferenceValue or
6621// nullptr if none. The ReferenceType is passed in for the IN type of
6622// reference the instruction is making from the values in defined in the header
6623// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6624// Out type and the ReferenceName will also be set which is added as a comment
6625// to the disassembled instruction.
6626//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006627// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006628// returned through ReferenceName and ReferenceType is set to
6629// LLVMDisassembler_ReferenceType_DeMangled_Name .
6630//
6631// When this is called to get a symbol name for a branch target then the
6632// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6633// SymbolValue will be looked for in the indirect symbol table to determine if
6634// it is an address for a symbol stub. If so then the symbol name for that
6635// stub is returned indirectly through ReferenceName and then ReferenceType is
6636// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6637//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006638// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006639// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6640// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6641// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006642// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006643static const char *SymbolizerSymbolLookUp(void *DisInfo,
6644 uint64_t ReferenceValue,
6645 uint64_t *ReferenceType,
6646 uint64_t ReferencePC,
6647 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006648 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006649 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006650 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006651 *ReferenceName = nullptr;
6652 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006653 return nullptr;
6654 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006655
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006656 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006657
Kevin Enderby85974882014-09-26 22:20:44 +00006658 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6659 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006660 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006661 method_reference(info, ReferenceType, ReferenceName);
6662 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6663 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006664 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006665 if (info->demangled_name != nullptr)
6666 free(info->demangled_name);
6667 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006668 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006669 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006670 if (info->demangled_name != nullptr) {
6671 *ReferenceName = info->demangled_name;
6672 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6673 } else
6674 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6675 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006676 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6677 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6678 *ReferenceName =
6679 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006680 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006681 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006682 else
6683 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006684 // If this is arm64 and the reference is an adrp instruction save the
6685 // instruction, passed in ReferenceValue and the address of the instruction
6686 // for use later if we see and add immediate instruction.
6687 } else if (info->O->getArch() == Triple::aarch64 &&
6688 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6689 info->adrp_inst = ReferenceValue;
6690 info->adrp_addr = ReferencePC;
6691 SymbolName = nullptr;
6692 *ReferenceName = nullptr;
6693 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6694 // If this is arm64 and reference is an add immediate instruction and we
6695 // have
6696 // seen an adrp instruction just before it and the adrp's Xd register
6697 // matches
6698 // this add's Xn register reconstruct the value being referenced and look to
6699 // see if it is a literal pointer. Note the add immediate instruction is
6700 // passed in ReferenceValue.
6701 } else if (info->O->getArch() == Triple::aarch64 &&
6702 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6703 ReferencePC - 4 == info->adrp_addr &&
6704 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6705 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6706 uint32_t addxri_inst;
6707 uint64_t adrp_imm, addxri_imm;
6708
6709 adrp_imm =
6710 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6711 if (info->adrp_inst & 0x0200000)
6712 adrp_imm |= 0xfffffffffc000000LL;
6713
6714 addxri_inst = ReferenceValue;
6715 addxri_imm = (addxri_inst >> 10) & 0xfff;
6716 if (((addxri_inst >> 22) & 0x3) == 1)
6717 addxri_imm <<= 12;
6718
6719 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6720 (adrp_imm << 12) + addxri_imm;
6721
6722 *ReferenceName =
6723 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6724 if (*ReferenceName == nullptr)
6725 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6726 // If this is arm64 and the reference is a load register instruction and we
6727 // have seen an adrp instruction just before it and the adrp's Xd register
6728 // matches this add's Xn register reconstruct the value being referenced and
6729 // look to see if it is a literal pointer. Note the load register
6730 // instruction is passed in ReferenceValue.
6731 } else if (info->O->getArch() == Triple::aarch64 &&
6732 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6733 ReferencePC - 4 == info->adrp_addr &&
6734 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6735 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6736 uint32_t ldrxui_inst;
6737 uint64_t adrp_imm, ldrxui_imm;
6738
6739 adrp_imm =
6740 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6741 if (info->adrp_inst & 0x0200000)
6742 adrp_imm |= 0xfffffffffc000000LL;
6743
6744 ldrxui_inst = ReferenceValue;
6745 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6746
6747 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6748 (adrp_imm << 12) + (ldrxui_imm << 3);
6749
6750 *ReferenceName =
6751 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6752 if (*ReferenceName == nullptr)
6753 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6754 }
6755 // If this arm64 and is an load register (PC-relative) instruction the
6756 // ReferenceValue is the PC plus the immediate value.
6757 else if (info->O->getArch() == Triple::aarch64 &&
6758 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6759 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6760 *ReferenceName =
6761 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6762 if (*ReferenceName == nullptr)
6763 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006764 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006765 if (info->demangled_name != nullptr)
6766 free(info->demangled_name);
6767 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006768 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006769 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006770 if (info->demangled_name != nullptr) {
6771 *ReferenceName = info->demangled_name;
6772 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6773 }
6774 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006775 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006776 *ReferenceName = nullptr;
6777 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6778 }
6779
6780 return SymbolName;
6781}
6782
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006783/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006784/// Each comment in the CommentStream must end with a newline.
6785static void emitComments(raw_svector_ostream &CommentStream,
6786 SmallString<128> &CommentsToEmit,
6787 formatted_raw_ostream &FormattedOS,
6788 const MCAsmInfo &MAI) {
6789 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006790 StringRef Comments = CommentsToEmit.str();
6791 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006792 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006793 unsigned CommentColumn = MAI.getCommentColumn();
6794 bool IsFirst = true;
6795 while (!Comments.empty()) {
6796 if (!IsFirst)
6797 FormattedOS << '\n';
6798 // Emit a line of comments.
6799 FormattedOS.PadToColumn(CommentColumn);
6800 size_t Position = Comments.find('\n');
6801 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6802 // Move after the newline character.
6803 Comments = Comments.substr(Position + 1);
6804 IsFirst = false;
6805 }
6806 FormattedOS.flush();
6807
6808 // Tell the comment stream that the vector changed underneath it.
6809 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006810}
6811
Kevin Enderby95df54c2015-02-04 01:01:38 +00006812static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6813 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006814 const char *McpuDefault = nullptr;
6815 const Target *ThumbTarget = nullptr;
6816 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006817 if (!TheTarget) {
6818 // GetTarget prints out stuff.
6819 return;
6820 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00006821 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006822 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00006823 MachOMCPU = McpuDefault;
6824 else
6825 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006826
Ahmed Charles56440fd2014-03-06 05:51:42 +00006827 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006828 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006829 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006830 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006831
Kevin Enderbyc9595622014-08-06 23:24:41 +00006832 // Package up features to be passed to target/subtarget
6833 std::string FeaturesStr;
6834 if (MAttrs.size()) {
6835 SubtargetFeatures Features;
6836 for (unsigned i = 0; i != MAttrs.size(); ++i)
6837 Features.AddFeature(MAttrs[i]);
6838 FeaturesStr = Features.getString();
6839 }
6840
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006841 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006842 std::unique_ptr<const MCRegisterInfo> MRI(
6843 TheTarget->createMCRegInfo(TripleName));
6844 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006845 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006846 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006847 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006848 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006849 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006850 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006851 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006852 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006853 std::unique_ptr<MCRelocationInfo> RelInfo(
6854 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6855 if (RelInfo) {
6856 Symbolizer.reset(TheTarget->createMCSymbolizer(
6857 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006858 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006859 DisAsm->setSymbolizer(std::move(Symbolizer));
6860 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006861 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006862 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006863 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006864 // Set the display preference for hex vs. decimal immediates.
6865 IP->setPrintImmHex(PrintImmHex);
6866 // Comment stream and backing vector.
6867 SmallString<128> CommentsToEmit;
6868 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006869 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6870 // if it is done then arm64 comments for string literals don't get printed
6871 // and some constant get printed instead and not setting it causes intel
6872 // (32-bit and 64-bit) comments printed with different spacing before the
6873 // comment causing different diffs with the 'C' disassembler library API.
6874 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006875
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006876 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006877 WithColor::error(errs(), "llvm-objdump")
6878 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006879 return;
6880 }
6881
Tim Northover09ca33e2016-04-22 23:23:31 +00006882 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006883 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6884 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6885 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006886 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006887 std::unique_ptr<MCInstPrinter> ThumbIP;
6888 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006889 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006890 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006891 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006892 if (ThumbTarget) {
6893 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6894 ThumbAsmInfo.reset(
6895 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6896 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006897 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6898 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006899 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6900 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006901 MCContext *PtrThumbCtx = ThumbCtx.get();
6902 ThumbRelInfo.reset(
6903 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6904 if (ThumbRelInfo) {
6905 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6906 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006907 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006908 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6909 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006910 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6911 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006912 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6913 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006914 // Set the display preference for hex vs. decimal immediates.
6915 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006916 }
6917
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006918 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006919 WithColor::error(errs(), "llvm-objdump")
6920 << "couldn't initialize disassembler for target " << ThumbTripleName
6921 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006922 return;
6923 }
6924
Charles Davis8bdfafd2013-09-01 04:28:48 +00006925 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006926
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006927 // FIXME: Using the -cfg command line option, this code used to be able to
6928 // annotate relocations with the referenced symbol's name, and if this was
6929 // inside a __[cf]string section, the data it points to. This is now replaced
6930 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006931 std::vector<SectionRef> Sections;
6932 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006933 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006934 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006935
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006936 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006937 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006938
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006939 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00006940 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006941
Kevin Enderby273ae012013-06-06 17:20:50 +00006942 // Build a data in code table that is sorted on by the address of each entry.
6943 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006944 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006945 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006946 else
6947 BaseAddress = BaseSegmentAddress;
6948 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006949 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006950 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006951 uint32_t Offset;
6952 DI->getOffset(Offset);
6953 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6954 }
6955 array_pod_sort(Dices.begin(), Dices.end());
6956
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006957#ifndef NDEBUG
6958 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6959#else
6960 raw_ostream &DebugOut = nulls();
6961#endif
6962
Ahmed Charles56440fd2014-03-06 05:51:42 +00006963 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006964 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00006965 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006966 // Try to find debug info and set up the DIContext for it.
6967 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006968 // A separate DSym file path was specified, parse it as a macho file,
6969 // get the sections and supply it to the section name parsing machinery.
6970 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006971 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006972 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006973 if (std::error_code EC = BufOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006974 WithColor::error(errs(), "llvm-objdump")
6975 << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006976 return;
6977 }
Gerolf Hoflehnerbf26d542018-04-19 20:48:35 +00006978 Expected<std::unique_ptr<MachOObjectFile>> DbgObjCheck =
6979 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef());
6980
6981 if (DbgObjCheck.takeError())
6982 report_error(MachOOF->getFileName(), DbgObjCheck.takeError());
6983 DbgObj = DbgObjCheck.get().release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00006984 // We need to keep the file alive, because we're replacing DbgObj with it.
6985 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00006986 }
6987
Eric Christopher7370b552012-11-12 21:40:38 +00006988 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00006989 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00006990 }
6991
Colin LeMahieufcc32762015-07-29 19:08:10 +00006992 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006993 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006994
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006995 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006996 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006997 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6998 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006999
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007000 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007001
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007002 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007003 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007004 continue;
7005
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007006 StringRef BytesStr;
7007 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00007008 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
7009 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00007010 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007011
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007012 bool symbolTableWorked = false;
7013
Kevin Enderbybf246f52014-09-24 23:08:22 +00007014 // Create a map of symbol addresses to symbol names for use by
7015 // the SymbolizerSymbolLookUp() routine.
7016 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007017 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007018 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007019 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007020 if (!STOrErr)
7021 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007022 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007023 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7024 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007025 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007026 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007027 if (!SymNameOrErr)
7028 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007029 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007030 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007031 if (!DisSymName.empty() && DisSymName == SymName)
7032 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007033 }
7034 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007035 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007036 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7037 return;
7038 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007039 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007040 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007041 SymbolizerInfo.O = MachOOF;
7042 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007043 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007044 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007045 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007046 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007047 ThumbSymbolizerInfo.O = MachOOF;
7048 ThumbSymbolizerInfo.S = Sections[SectIdx];
7049 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7050 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007051
Kevin Enderby4b627be2016-04-28 20:14:13 +00007052 unsigned int Arch = MachOOF->getArch();
7053
Tim Northoverf203ab52016-07-14 22:13:32 +00007054 // Skip all symbols if this is a stubs file.
7055 if (Bytes.size() == 0)
7056 return;
7057
Kevin Enderbyc138da32017-02-06 18:43:18 +00007058 // If the section has symbols but no symbol at the start of the section
7059 // these are used to make sure the bytes before the first symbol are
7060 // disassembled.
7061 bool FirstSymbol = true;
7062 bool FirstSymbolAtSectionStart = true;
7063
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007064 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007065 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007066 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007067 if (!SymNameOrErr)
7068 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007069 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007070
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007071 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007072 if (!STOrErr)
7073 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007074 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007075 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007076 continue;
7077
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007078 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007079 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007080 if (!containsSym) {
7081 if (!DisSymName.empty() && DisSymName == SymName) {
7082 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7083 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007084 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007085 continue;
7086 }
7087 // The __mh_execute_header is special and we need to deal with that fact
7088 // this symbol is before the start of the (__TEXT,__text) section and at the
7089 // address of the start of the __TEXT segment. This is because this symbol
7090 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7091 // start of the section in a standard MH_EXECUTE filetype.
7092 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7093 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7094 return;
7095 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007096 // When this code is trying to disassemble a symbol at a time and in the
7097 // case there is only the __mh_execute_header symbol left as in a stripped
7098 // executable, we need to deal with this by ignoring this symbol so the
7099 // whole section is disassembled and this symbol is then not displayed.
7100 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7101 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7102 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007103 continue;
7104
Kevin Enderby6a221752015-03-17 17:10:57 +00007105 // If we are only disassembling one symbol see if this is that symbol.
7106 if (!DisSymName.empty() && DisSymName != SymName)
7107 continue;
7108
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007109 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007110 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007111 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007112 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007113 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007114
Tim Northoverf203ab52016-07-14 22:13:32 +00007115 if (Start > SectSize) {
7116 outs() << "section data ends, " << SymName
7117 << " lies outside valid range\n";
7118 return;
7119 }
7120
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007121 // Stop disassembling either at the beginning of the next symbol or at
7122 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007123 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007124 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007125 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007126 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007127 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007128 if (!STOrErr)
7129 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007130 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007131 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007132 containsNextSym =
7133 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007134 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007135 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007136 break;
7137 }
7138 ++NextSymIdx;
7139 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007140
Tim Northoverf203ab52016-07-14 22:13:32 +00007141 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007142 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007143
7144 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007145
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007146 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007147 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7148
7149 // We only need the dedicated Thumb target if there's a real choice
7150 // (i.e. we're not targeting M-class) and the function is Thumb.
7151 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007152
Kevin Enderbyc138da32017-02-06 18:43:18 +00007153 // If we are not specifying a symbol to start disassembly with and this
7154 // is the first symbol in the section but not at the start of the section
7155 // then move the disassembly index to the start of the section and
7156 // don't print the symbol name just yet. This is so the bytes before the
7157 // first symbol are disassembled.
7158 uint64_t SymbolStart = Start;
7159 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7160 FirstSymbolAtSectionStart = false;
7161 Start = 0;
7162 }
7163 else
7164 outs() << SymName << ":\n";
7165
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007166 DILineInfo lastLine;
7167 for (uint64_t Index = Start; Index < End; Index += Size) {
7168 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007169
Kevin Enderbyc138da32017-02-06 18:43:18 +00007170 // If this is the first symbol in the section and it was not at the
7171 // start of the section, see if we are at its Index now and if so print
7172 // the symbol name.
7173 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7174 outs() << SymName << ":\n";
7175
Kevin Enderbybf246f52014-09-24 23:08:22 +00007176 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007177 if (!NoLeadingAddr) {
7178 if (FullLeadingAddr) {
7179 if (MachOOF->is64Bit())
7180 outs() << format("%016" PRIx64, PC);
7181 else
7182 outs() << format("%08" PRIx64, PC);
7183 } else {
7184 outs() << format("%8" PRIx64 ":", PC);
7185 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007186 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007187 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007188 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007189
7190 // Check the data in code table here to see if this is data not an
7191 // instruction to be disassembled.
7192 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007193 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007194 dice_table_iterator DTI =
7195 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7196 compareDiceTableEntries);
7197 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007198 uint16_t Length;
7199 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007200 uint16_t Kind;
7201 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007202 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007203 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7204 (PC == (DTI->first + Length - 1)) && (Length & 1))
7205 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007206 continue;
7207 }
7208
Kevin Enderbybf246f52014-09-24 23:08:22 +00007209 SmallVector<char, 64> AnnotationsBytes;
7210 raw_svector_ostream Annotations(AnnotationsBytes);
7211
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007212 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007213 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007214 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007215 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007216 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007217 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007218 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007219 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007220 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007221 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007222 }
7223 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007224 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007225 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007226 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007227 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007228 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007229 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007230
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007231 // Print debug info.
7232 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007233 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007234 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007235 if (dli != lastLine && dli.Line != 0)
7236 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7237 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007238 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007239 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007240 outs() << "\n";
7241 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007242 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007243 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007244 outs() << format("\t.byte 0x%02x #bad opcode\n",
7245 *(Bytes.data() + Index) & 0xff);
7246 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007247 } else if (Arch == Triple::aarch64 ||
7248 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007249 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7250 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7251 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7252 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7253 outs() << format("\t.long\t0x%08x\n", opcode);
7254 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007255 } else if (Arch == Triple::arm) {
7256 assert(IsThumb && "ARM mode should have been dealt with above");
7257 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7258 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7259 outs() << format("\t.short\t0x%04x\n", opcode);
7260 Size = 2;
7261 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007262 WithColor::warning(errs(), "llvm-objdump")
7263 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007264 if (Size == 0)
7265 Size = 1; // skip illegible bytes
7266 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007267 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007268 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007269 // Now that we are done disassembled the first symbol set the bool that
7270 // were doing this to false.
7271 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007272 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007273 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007274 // Reading the symbol table didn't work, disassemble the whole section.
7275 uint64_t SectAddress = Sections[SectIdx].getAddress();
7276 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007277 uint64_t InstSize;
7278 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007279 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007280
Kevin Enderbybf246f52014-09-24 23:08:22 +00007281 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007282 SmallVector<char, 64> AnnotationsBytes;
7283 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007284 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007285 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007286 if (!NoLeadingAddr) {
7287 if (FullLeadingAddr) {
7288 if (MachOOF->is64Bit())
7289 outs() << format("%016" PRIx64, PC);
7290 else
7291 outs() << format("%08" PRIx64, PC);
7292 } else {
7293 outs() << format("%8" PRIx64 ":", PC);
7294 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007295 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007296 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007297 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007298 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007299 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007300 StringRef AnnotationsStr = Annotations.str();
7301 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007302 outs() << "\n";
7303 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007304 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007305 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007306 outs() << format("\t.byte 0x%02x #bad opcode\n",
7307 *(Bytes.data() + Index) & 0xff);
7308 InstSize = 1; // skip exactly one illegible byte and move on.
7309 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007310 WithColor::warning(errs(), "llvm-objdump")
7311 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007312 if (InstSize == 0)
7313 InstSize = 1; // skip illegible bytes
7314 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007315 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007316 }
7317 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007318 // The TripleName's need to be reset if we are called again for a different
7319 // archtecture.
7320 TripleName = "";
7321 ThumbTripleName = "";
7322
Kevin Enderby04bf6932014-10-28 23:39:46 +00007323 if (SymbolizerInfo.demangled_name != nullptr)
7324 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007325 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7326 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007327 }
7328}
Tim Northover4bd286a2014-08-01 13:07:19 +00007329
Tim Northover39c70bb2014-08-12 11:52:59 +00007330//===----------------------------------------------------------------------===//
7331// __compact_unwind section dumping
7332//===----------------------------------------------------------------------===//
7333
Tim Northover4bd286a2014-08-01 13:07:19 +00007334namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007335
Tim Northover3a4e1c72018-01-23 13:51:57 +00007336template <typename T>
7337static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007338 using llvm::support::little;
7339 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007340
Tim Northover3a4e1c72018-01-23 13:51:57 +00007341 if (Offset + sizeof(T) > Contents.size()) {
7342 outs() << "warning: attempt to read past end of buffer\n";
7343 return T();
7344 }
7345
7346 uint64_t Val =
7347 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7348 return Val;
7349}
7350
7351template <typename T>
7352static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7353 T Val = read<T>(Contents, Offset);
7354 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007355 return Val;
7356}
Tim Northover39c70bb2014-08-12 11:52:59 +00007357
Tim Northover4bd286a2014-08-01 13:07:19 +00007358struct CompactUnwindEntry {
7359 uint32_t OffsetInSection;
7360
7361 uint64_t FunctionAddr;
7362 uint32_t Length;
7363 uint32_t CompactEncoding;
7364 uint64_t PersonalityAddr;
7365 uint64_t LSDAAddr;
7366
7367 RelocationRef FunctionReloc;
7368 RelocationRef PersonalityReloc;
7369 RelocationRef LSDAReloc;
7370
7371 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007372 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007373 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007374 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007375 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007376 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007377 }
7378
7379private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007380 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7381 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7382 Length = readNext<uint32_t>(Contents, Offset);
7383 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7384 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7385 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007386 }
7387};
7388}
7389
7390/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7391/// and data being relocated, determine the best base Name and Addend to use for
7392/// display purposes.
7393///
7394/// 1. An Extern relocation will directly reference a symbol (and the data is
7395/// then already an addend), so use that.
7396/// 2. Otherwise the data is an offset in the object file's layout; try to find
7397// a symbol before it in the same section, and use the offset from there.
7398/// 3. Finally, if all that fails, fall back to an offset from the start of the
7399/// referenced section.
7400static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7401 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007402 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007403 StringRef &Name, uint64_t &Addend) {
7404 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007405 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007406 if (!NameOrErr)
7407 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007408 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007409 Addend = Addr;
7410 return;
7411 }
7412
7413 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007414 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007415
Rafael Espindola80291272014-10-08 15:28:58 +00007416 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007417
7418 auto Sym = Symbols.upper_bound(Addr);
7419 if (Sym == Symbols.begin()) {
7420 // The first symbol in the object is after this reference, the best we can
7421 // do is section-relative notation.
7422 RelocSection.getName(Name);
7423 Addend = Addr - SectionAddr;
7424 return;
7425 }
7426
7427 // Go back one so that SymbolAddress <= Addr.
7428 --Sym;
7429
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007430 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007431 if (!SectOrErr)
7432 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007433 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007434 if (RelocSection == *SymSection) {
7435 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007436 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007437 if (!NameOrErr)
7438 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007439 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007440 Addend = Addr - Sym->first;
7441 return;
7442 }
7443
7444 // There is a symbol before this reference, but it's in a different
7445 // section. Probably not helpful to mention it, so use the section name.
7446 RelocSection.getName(Name);
7447 Addend = Addr - SectionAddr;
7448}
7449
7450static void printUnwindRelocDest(const MachOObjectFile *Obj,
7451 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007452 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007453 StringRef Name;
7454 uint64_t Addend;
7455
Rafael Espindola854038e2015-06-26 14:51:16 +00007456 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007457 return;
7458
Tim Northover4bd286a2014-08-01 13:07:19 +00007459 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7460
7461 outs() << Name;
7462 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007463 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007464}
7465
7466static void
7467printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7468 std::map<uint64_t, SymbolRef> &Symbols,
7469 const SectionRef &CompactUnwind) {
7470
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007471 if (!Obj->isLittleEndian()) {
7472 outs() << "Skipping big-endian __compact_unwind section\n";
7473 return;
7474 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007475
7476 bool Is64 = Obj->is64Bit();
7477 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7478 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7479
7480 StringRef Contents;
7481 CompactUnwind.getContents(Contents);
7482
7483 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7484
7485 // First populate the initial raw offsets, encodings and so on from the entry.
7486 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007487 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007488 CompactUnwinds.push_back(Entry);
7489 }
7490
7491 // Next we need to look at the relocations to find out what objects are
7492 // actually being referred to.
7493 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007494 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007495
7496 uint32_t EntryIdx = RelocAddress / EntrySize;
7497 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7498 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7499
7500 if (OffsetInEntry == 0)
7501 Entry.FunctionReloc = Reloc;
7502 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7503 Entry.PersonalityReloc = Reloc;
7504 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7505 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007506 else {
7507 outs() << "Invalid relocation in __compact_unwind section\n";
7508 return;
7509 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007510 }
7511
7512 // Finally, we're ready to print the data we've gathered.
7513 outs() << "Contents of __compact_unwind section:\n";
7514 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007515 outs() << " Entry at offset "
7516 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007517
7518 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007519 outs() << " start: " << format("0x%" PRIx64,
7520 Entry.FunctionAddr) << ' ';
7521 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007522 outs() << '\n';
7523
7524 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007525 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7526 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007527 // 3. The 32-bit compact encoding.
7528 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007529 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007530
7531 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007532 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007533 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007534 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007535 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7536 Entry.PersonalityAddr);
7537 outs() << '\n';
7538 }
7539
7540 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007541 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007542 outs() << " LSDA: " << format("0x%" PRIx64,
7543 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007544 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7545 outs() << '\n';
7546 }
7547 }
7548}
7549
Tim Northover39c70bb2014-08-12 11:52:59 +00007550//===----------------------------------------------------------------------===//
7551// __unwind_info section dumping
7552//===----------------------------------------------------------------------===//
7553
Tim Northover3a4e1c72018-01-23 13:51:57 +00007554static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7555 ptrdiff_t Pos = 0;
7556 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007557 (void)Kind;
7558 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7559
Tim Northover3a4e1c72018-01-23 13:51:57 +00007560 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7561 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007562
Tim Northover3a4e1c72018-01-23 13:51:57 +00007563 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007564 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007565 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7566 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007567
7568 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007569 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7570 << ", "
7571 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007572 }
7573}
7574
7575static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007576 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007577 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007578 ptrdiff_t Pos = 0;
7579 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007580 (void)Kind;
7581 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7582
Tim Northover3a4e1c72018-01-23 13:51:57 +00007583 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7584 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007585
Tim Northover3a4e1c72018-01-23 13:51:57 +00007586 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7587 readNext<uint16_t>(PageData, Pos);
7588 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007589
Tim Northover3a4e1c72018-01-23 13:51:57 +00007590 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007591 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007592 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007593 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7594 uint32_t EncodingIdx = Entry >> 24;
7595
7596 uint32_t Encoding;
7597 if (EncodingIdx < CommonEncodings.size())
7598 Encoding = CommonEncodings[EncodingIdx];
7599 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007600 Encoding = read<uint32_t>(PageEncodings,
7601 sizeof(uint32_t) *
7602 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007603
7604 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007605 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7606 << ", "
7607 << "encoding[" << EncodingIdx
7608 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007609 }
7610}
7611
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007612static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7613 std::map<uint64_t, SymbolRef> &Symbols,
7614 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007615
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007616 if (!Obj->isLittleEndian()) {
7617 outs() << "Skipping big-endian __unwind_info section\n";
7618 return;
7619 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007620
7621 outs() << "Contents of __unwind_info section:\n";
7622
7623 StringRef Contents;
7624 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007625 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007626
7627 //===----------------------------------
7628 // Section header
7629 //===----------------------------------
7630
Tim Northover3a4e1c72018-01-23 13:51:57 +00007631 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007632 outs() << " Version: "
7633 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007634 if (Version != 1) {
7635 outs() << " Skipping section with unknown version\n";
7636 return;
7637 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007638
Tim Northover3a4e1c72018-01-23 13:51:57 +00007639 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007640 outs() << " Common encodings array section offset: "
7641 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007642 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007643 outs() << " Number of common encodings in array: "
7644 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7645
Tim Northover3a4e1c72018-01-23 13:51:57 +00007646 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007647 outs() << " Personality function array section offset: "
7648 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007649 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007650 outs() << " Number of personality functions in array: "
7651 << format("0x%" PRIx32, NumPersonalities) << '\n';
7652
Tim Northover3a4e1c72018-01-23 13:51:57 +00007653 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007654 outs() << " Index array section offset: "
7655 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007656 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007657 outs() << " Number of indices in array: "
7658 << format("0x%" PRIx32, NumIndices) << '\n';
7659
7660 //===----------------------------------
7661 // A shared list of common encodings
7662 //===----------------------------------
7663
7664 // These occupy indices in the range [0, N] whenever an encoding is referenced
7665 // from a compressed 2nd level index table. In practice the linker only
7666 // creates ~128 of these, so that indices are available to embed encodings in
7667 // the 2nd level index.
7668
7669 SmallVector<uint32_t, 64> CommonEncodings;
7670 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007671 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007672 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007673 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007674 CommonEncodings.push_back(Encoding);
7675
7676 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7677 << '\n';
7678 }
7679
Tim Northover39c70bb2014-08-12 11:52:59 +00007680 //===----------------------------------
7681 // Personality functions used in this executable
7682 //===----------------------------------
7683
7684 // There should be only a handful of these (one per source language,
7685 // roughly). Particularly since they only get 2 bits in the compact encoding.
7686
7687 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007688 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007689 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007690 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007691 outs() << " personality[" << i + 1
7692 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7693 }
7694
7695 //===----------------------------------
7696 // The level 1 index entries
7697 //===----------------------------------
7698
7699 // These specify an approximate place to start searching for the more detailed
7700 // information, sorted by PC.
7701
7702 struct IndexEntry {
7703 uint32_t FunctionOffset;
7704 uint32_t SecondLevelPageStart;
7705 uint32_t LSDAStart;
7706 };
7707
7708 SmallVector<IndexEntry, 4> IndexEntries;
7709
7710 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007711 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007712 for (unsigned i = 0; i < NumIndices; ++i) {
7713 IndexEntry Entry;
7714
Tim Northover3a4e1c72018-01-23 13:51:57 +00007715 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7716 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7717 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007718 IndexEntries.push_back(Entry);
7719
7720 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007721 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7722 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007723 << "2nd level page offset="
7724 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007725 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007726 }
7727
Tim Northover39c70bb2014-08-12 11:52:59 +00007728 //===----------------------------------
7729 // Next come the LSDA tables
7730 //===----------------------------------
7731
7732 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7733 // the first top-level index's LSDAOffset to the last (sentinel).
7734
7735 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007736 Pos = IndexEntries[0].LSDAStart;
7737 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7738 int NumLSDAs =
7739 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7740
Tim Northover39c70bb2014-08-12 11:52:59 +00007741 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007742 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7743 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007744 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007745 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7746 << ", "
7747 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007748 }
7749
7750 //===----------------------------------
7751 // Finally, the 2nd level indices
7752 //===----------------------------------
7753
7754 // Generally these are 4K in size, and have 2 possible forms:
7755 // + Regular stores up to 511 entries with disparate encodings
7756 // + Compressed stores up to 1021 entries if few enough compact encoding
7757 // values are used.
7758 outs() << " Second level indices:\n";
7759 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7760 // The final sentinel top-level index has no associated 2nd level page
7761 if (IndexEntries[i].SecondLevelPageStart == 0)
7762 break;
7763
7764 outs() << " Second level index[" << i << "]: "
7765 << "offset in section="
7766 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7767 << ", "
7768 << "base function offset="
7769 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7770
Tim Northover3a4e1c72018-01-23 13:51:57 +00007771 Pos = IndexEntries[i].SecondLevelPageStart;
7772 if (Pos + sizeof(uint32_t) > Contents.size()) {
7773 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7774 continue;
7775 }
7776
7777 uint32_t Kind =
7778 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007779 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007780 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007781 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007782 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7783 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007784 CommonEncodings);
7785 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007786 outs() << " Skipping 2nd level page with unknown kind " << Kind
7787 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007788 }
7789}
7790
Tim Northover4bd286a2014-08-01 13:07:19 +00007791void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7792 std::map<uint64_t, SymbolRef> Symbols;
7793 for (const SymbolRef &SymRef : Obj->symbols()) {
7794 // Discard any undefined or absolute symbols. They're not going to take part
7795 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007796 auto SectOrErr = SymRef.getSection();
7797 if (!SectOrErr) {
7798 // TODO: Actually report errors helpfully.
7799 consumeError(SectOrErr.takeError());
7800 continue;
7801 }
7802 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007803 if (Section == Obj->section_end())
7804 continue;
7805
Rafael Espindoladea00162015-07-03 17:44:18 +00007806 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007807 Symbols.insert(std::make_pair(Addr, SymRef));
7808 }
7809
7810 for (const SectionRef &Section : Obj->sections()) {
7811 StringRef SectName;
7812 Section.getName(SectName);
7813 if (SectName == "__compact_unwind")
7814 printMachOCompactUnwindSection(Obj, Symbols, Section);
7815 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007816 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007817 }
7818}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007819
7820static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7821 uint32_t cpusubtype, uint32_t filetype,
7822 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7823 bool verbose) {
7824 outs() << "Mach header\n";
7825 outs() << " magic cputype cpusubtype caps filetype ncmds "
7826 "sizeofcmds flags\n";
7827 if (verbose) {
7828 if (magic == MachO::MH_MAGIC)
7829 outs() << " MH_MAGIC";
7830 else if (magic == MachO::MH_MAGIC_64)
7831 outs() << "MH_MAGIC_64";
7832 else
7833 outs() << format(" 0x%08" PRIx32, magic);
7834 switch (cputype) {
7835 case MachO::CPU_TYPE_I386:
7836 outs() << " I386";
7837 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7838 case MachO::CPU_SUBTYPE_I386_ALL:
7839 outs() << " ALL";
7840 break;
7841 default:
7842 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7843 break;
7844 }
7845 break;
7846 case MachO::CPU_TYPE_X86_64:
7847 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007848 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7849 case MachO::CPU_SUBTYPE_X86_64_ALL:
7850 outs() << " ALL";
7851 break;
7852 case MachO::CPU_SUBTYPE_X86_64_H:
7853 outs() << " Haswell";
7854 break;
7855 default:
7856 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7857 break;
7858 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007859 break;
7860 case MachO::CPU_TYPE_ARM:
7861 outs() << " ARM";
7862 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7863 case MachO::CPU_SUBTYPE_ARM_ALL:
7864 outs() << " ALL";
7865 break;
7866 case MachO::CPU_SUBTYPE_ARM_V4T:
7867 outs() << " V4T";
7868 break;
7869 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7870 outs() << " V5TEJ";
7871 break;
7872 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7873 outs() << " XSCALE";
7874 break;
7875 case MachO::CPU_SUBTYPE_ARM_V6:
7876 outs() << " V6";
7877 break;
7878 case MachO::CPU_SUBTYPE_ARM_V6M:
7879 outs() << " V6M";
7880 break;
7881 case MachO::CPU_SUBTYPE_ARM_V7:
7882 outs() << " V7";
7883 break;
7884 case MachO::CPU_SUBTYPE_ARM_V7EM:
7885 outs() << " V7EM";
7886 break;
7887 case MachO::CPU_SUBTYPE_ARM_V7K:
7888 outs() << " V7K";
7889 break;
7890 case MachO::CPU_SUBTYPE_ARM_V7M:
7891 outs() << " V7M";
7892 break;
7893 case MachO::CPU_SUBTYPE_ARM_V7S:
7894 outs() << " V7S";
7895 break;
7896 default:
7897 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7898 break;
7899 }
7900 break;
7901 case MachO::CPU_TYPE_ARM64:
7902 outs() << " ARM64";
7903 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7904 case MachO::CPU_SUBTYPE_ARM64_ALL:
7905 outs() << " ALL";
7906 break;
7907 default:
7908 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7909 break;
7910 }
7911 break;
7912 case MachO::CPU_TYPE_POWERPC:
7913 outs() << " PPC";
7914 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7915 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7916 outs() << " ALL";
7917 break;
7918 default:
7919 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7920 break;
7921 }
7922 break;
7923 case MachO::CPU_TYPE_POWERPC64:
7924 outs() << " PPC64";
7925 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7926 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7927 outs() << " ALL";
7928 break;
7929 default:
7930 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7931 break;
7932 }
7933 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007934 default:
7935 outs() << format(" %7d", cputype);
7936 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7937 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007938 }
7939 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007940 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007941 } else {
7942 outs() << format(" 0x%02" PRIx32,
7943 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7944 }
7945 switch (filetype) {
7946 case MachO::MH_OBJECT:
7947 outs() << " OBJECT";
7948 break;
7949 case MachO::MH_EXECUTE:
7950 outs() << " EXECUTE";
7951 break;
7952 case MachO::MH_FVMLIB:
7953 outs() << " FVMLIB";
7954 break;
7955 case MachO::MH_CORE:
7956 outs() << " CORE";
7957 break;
7958 case MachO::MH_PRELOAD:
7959 outs() << " PRELOAD";
7960 break;
7961 case MachO::MH_DYLIB:
7962 outs() << " DYLIB";
7963 break;
7964 case MachO::MH_DYLIB_STUB:
7965 outs() << " DYLIB_STUB";
7966 break;
7967 case MachO::MH_DYLINKER:
7968 outs() << " DYLINKER";
7969 break;
7970 case MachO::MH_BUNDLE:
7971 outs() << " BUNDLE";
7972 break;
7973 case MachO::MH_DSYM:
7974 outs() << " DSYM";
7975 break;
7976 case MachO::MH_KEXT_BUNDLE:
7977 outs() << " KEXTBUNDLE";
7978 break;
7979 default:
7980 outs() << format(" %10u", filetype);
7981 break;
7982 }
7983 outs() << format(" %5u", ncmds);
7984 outs() << format(" %10u", sizeofcmds);
7985 uint32_t f = flags;
7986 if (f & MachO::MH_NOUNDEFS) {
7987 outs() << " NOUNDEFS";
7988 f &= ~MachO::MH_NOUNDEFS;
7989 }
7990 if (f & MachO::MH_INCRLINK) {
7991 outs() << " INCRLINK";
7992 f &= ~MachO::MH_INCRLINK;
7993 }
7994 if (f & MachO::MH_DYLDLINK) {
7995 outs() << " DYLDLINK";
7996 f &= ~MachO::MH_DYLDLINK;
7997 }
7998 if (f & MachO::MH_BINDATLOAD) {
7999 outs() << " BINDATLOAD";
8000 f &= ~MachO::MH_BINDATLOAD;
8001 }
8002 if (f & MachO::MH_PREBOUND) {
8003 outs() << " PREBOUND";
8004 f &= ~MachO::MH_PREBOUND;
8005 }
8006 if (f & MachO::MH_SPLIT_SEGS) {
8007 outs() << " SPLIT_SEGS";
8008 f &= ~MachO::MH_SPLIT_SEGS;
8009 }
8010 if (f & MachO::MH_LAZY_INIT) {
8011 outs() << " LAZY_INIT";
8012 f &= ~MachO::MH_LAZY_INIT;
8013 }
8014 if (f & MachO::MH_TWOLEVEL) {
8015 outs() << " TWOLEVEL";
8016 f &= ~MachO::MH_TWOLEVEL;
8017 }
8018 if (f & MachO::MH_FORCE_FLAT) {
8019 outs() << " FORCE_FLAT";
8020 f &= ~MachO::MH_FORCE_FLAT;
8021 }
8022 if (f & MachO::MH_NOMULTIDEFS) {
8023 outs() << " NOMULTIDEFS";
8024 f &= ~MachO::MH_NOMULTIDEFS;
8025 }
8026 if (f & MachO::MH_NOFIXPREBINDING) {
8027 outs() << " NOFIXPREBINDING";
8028 f &= ~MachO::MH_NOFIXPREBINDING;
8029 }
8030 if (f & MachO::MH_PREBINDABLE) {
8031 outs() << " PREBINDABLE";
8032 f &= ~MachO::MH_PREBINDABLE;
8033 }
8034 if (f & MachO::MH_ALLMODSBOUND) {
8035 outs() << " ALLMODSBOUND";
8036 f &= ~MachO::MH_ALLMODSBOUND;
8037 }
8038 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8039 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8040 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8041 }
8042 if (f & MachO::MH_CANONICAL) {
8043 outs() << " CANONICAL";
8044 f &= ~MachO::MH_CANONICAL;
8045 }
8046 if (f & MachO::MH_WEAK_DEFINES) {
8047 outs() << " WEAK_DEFINES";
8048 f &= ~MachO::MH_WEAK_DEFINES;
8049 }
8050 if (f & MachO::MH_BINDS_TO_WEAK) {
8051 outs() << " BINDS_TO_WEAK";
8052 f &= ~MachO::MH_BINDS_TO_WEAK;
8053 }
8054 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8055 outs() << " ALLOW_STACK_EXECUTION";
8056 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8057 }
8058 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8059 outs() << " DEAD_STRIPPABLE_DYLIB";
8060 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8061 }
8062 if (f & MachO::MH_PIE) {
8063 outs() << " PIE";
8064 f &= ~MachO::MH_PIE;
8065 }
8066 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8067 outs() << " NO_REEXPORTED_DYLIBS";
8068 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8069 }
8070 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8071 outs() << " MH_HAS_TLV_DESCRIPTORS";
8072 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8073 }
8074 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8075 outs() << " MH_NO_HEAP_EXECUTION";
8076 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8077 }
8078 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8079 outs() << " APP_EXTENSION_SAFE";
8080 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8081 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008082 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8083 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8084 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8085 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008086 if (f != 0 || flags == 0)
8087 outs() << format(" 0x%08" PRIx32, f);
8088 } else {
8089 outs() << format(" 0x%08" PRIx32, magic);
8090 outs() << format(" %7d", cputype);
8091 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8092 outs() << format(" 0x%02" PRIx32,
8093 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8094 outs() << format(" %10u", filetype);
8095 outs() << format(" %5u", ncmds);
8096 outs() << format(" %10u", sizeofcmds);
8097 outs() << format(" 0x%08" PRIx32, flags);
8098 }
8099 outs() << "\n";
8100}
8101
Kevin Enderby956366c2014-08-29 22:30:52 +00008102static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8103 StringRef SegName, uint64_t vmaddr,
8104 uint64_t vmsize, uint64_t fileoff,
8105 uint64_t filesize, uint32_t maxprot,
8106 uint32_t initprot, uint32_t nsects,
8107 uint32_t flags, uint32_t object_size,
8108 bool verbose) {
8109 uint64_t expected_cmdsize;
8110 if (cmd == MachO::LC_SEGMENT) {
8111 outs() << " cmd LC_SEGMENT\n";
8112 expected_cmdsize = nsects;
8113 expected_cmdsize *= sizeof(struct MachO::section);
8114 expected_cmdsize += sizeof(struct MachO::segment_command);
8115 } else {
8116 outs() << " cmd LC_SEGMENT_64\n";
8117 expected_cmdsize = nsects;
8118 expected_cmdsize *= sizeof(struct MachO::section_64);
8119 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8120 }
8121 outs() << " cmdsize " << cmdsize;
8122 if (cmdsize != expected_cmdsize)
8123 outs() << " Inconsistent size\n";
8124 else
8125 outs() << "\n";
8126 outs() << " segname " << SegName << "\n";
8127 if (cmd == MachO::LC_SEGMENT_64) {
8128 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8129 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8130 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008131 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8132 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008133 }
8134 outs() << " fileoff " << fileoff;
8135 if (fileoff > object_size)
8136 outs() << " (past end of file)\n";
8137 else
8138 outs() << "\n";
8139 outs() << " filesize " << filesize;
8140 if (fileoff + filesize > object_size)
8141 outs() << " (past end of file)\n";
8142 else
8143 outs() << "\n";
8144 if (verbose) {
8145 if ((maxprot &
8146 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8147 MachO::VM_PROT_EXECUTE)) != 0)
8148 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8149 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008150 outs() << " maxprot ";
8151 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8152 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8153 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008154 }
8155 if ((initprot &
8156 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8157 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008158 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008159 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008160 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008161 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8162 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8163 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008164 }
8165 } else {
8166 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8167 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8168 }
8169 outs() << " nsects " << nsects << "\n";
8170 if (verbose) {
8171 outs() << " flags";
8172 if (flags == 0)
8173 outs() << " (none)\n";
8174 else {
8175 if (flags & MachO::SG_HIGHVM) {
8176 outs() << " HIGHVM";
8177 flags &= ~MachO::SG_HIGHVM;
8178 }
8179 if (flags & MachO::SG_FVMLIB) {
8180 outs() << " FVMLIB";
8181 flags &= ~MachO::SG_FVMLIB;
8182 }
8183 if (flags & MachO::SG_NORELOC) {
8184 outs() << " NORELOC";
8185 flags &= ~MachO::SG_NORELOC;
8186 }
8187 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8188 outs() << " PROTECTED_VERSION_1";
8189 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8190 }
8191 if (flags)
8192 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8193 else
8194 outs() << "\n";
8195 }
8196 } else {
8197 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8198 }
8199}
8200
8201static void PrintSection(const char *sectname, const char *segname,
8202 uint64_t addr, uint64_t size, uint32_t offset,
8203 uint32_t align, uint32_t reloff, uint32_t nreloc,
8204 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8205 uint32_t cmd, const char *sg_segname,
8206 uint32_t filetype, uint32_t object_size,
8207 bool verbose) {
8208 outs() << "Section\n";
8209 outs() << " sectname " << format("%.16s\n", sectname);
8210 outs() << " segname " << format("%.16s", segname);
8211 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8212 outs() << " (does not match segment)\n";
8213 else
8214 outs() << "\n";
8215 if (cmd == MachO::LC_SEGMENT_64) {
8216 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8217 outs() << " size " << format("0x%016" PRIx64, size);
8218 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008219 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8220 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008221 }
8222 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8223 outs() << " (past end of file)\n";
8224 else
8225 outs() << "\n";
8226 outs() << " offset " << offset;
8227 if (offset > object_size)
8228 outs() << " (past end of file)\n";
8229 else
8230 outs() << "\n";
8231 uint32_t align_shifted = 1 << align;
8232 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8233 outs() << " reloff " << reloff;
8234 if (reloff > object_size)
8235 outs() << " (past end of file)\n";
8236 else
8237 outs() << "\n";
8238 outs() << " nreloc " << nreloc;
8239 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8240 outs() << " (past end of file)\n";
8241 else
8242 outs() << "\n";
8243 uint32_t section_type = flags & MachO::SECTION_TYPE;
8244 if (verbose) {
8245 outs() << " type";
8246 if (section_type == MachO::S_REGULAR)
8247 outs() << " S_REGULAR\n";
8248 else if (section_type == MachO::S_ZEROFILL)
8249 outs() << " S_ZEROFILL\n";
8250 else if (section_type == MachO::S_CSTRING_LITERALS)
8251 outs() << " S_CSTRING_LITERALS\n";
8252 else if (section_type == MachO::S_4BYTE_LITERALS)
8253 outs() << " S_4BYTE_LITERALS\n";
8254 else if (section_type == MachO::S_8BYTE_LITERALS)
8255 outs() << " S_8BYTE_LITERALS\n";
8256 else if (section_type == MachO::S_16BYTE_LITERALS)
8257 outs() << " S_16BYTE_LITERALS\n";
8258 else if (section_type == MachO::S_LITERAL_POINTERS)
8259 outs() << " S_LITERAL_POINTERS\n";
8260 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8261 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8262 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8263 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8264 else if (section_type == MachO::S_SYMBOL_STUBS)
8265 outs() << " S_SYMBOL_STUBS\n";
8266 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8267 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8268 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8269 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8270 else if (section_type == MachO::S_COALESCED)
8271 outs() << " S_COALESCED\n";
8272 else if (section_type == MachO::S_INTERPOSING)
8273 outs() << " S_INTERPOSING\n";
8274 else if (section_type == MachO::S_DTRACE_DOF)
8275 outs() << " S_DTRACE_DOF\n";
8276 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8277 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8278 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8279 outs() << " S_THREAD_LOCAL_REGULAR\n";
8280 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8281 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8282 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8283 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8284 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8285 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8286 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8287 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8288 else
8289 outs() << format("0x%08" PRIx32, section_type) << "\n";
8290 outs() << "attributes";
8291 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8292 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8293 outs() << " PURE_INSTRUCTIONS";
8294 if (section_attributes & MachO::S_ATTR_NO_TOC)
8295 outs() << " NO_TOC";
8296 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8297 outs() << " STRIP_STATIC_SYMS";
8298 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8299 outs() << " NO_DEAD_STRIP";
8300 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8301 outs() << " LIVE_SUPPORT";
8302 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8303 outs() << " SELF_MODIFYING_CODE";
8304 if (section_attributes & MachO::S_ATTR_DEBUG)
8305 outs() << " DEBUG";
8306 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8307 outs() << " SOME_INSTRUCTIONS";
8308 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8309 outs() << " EXT_RELOC";
8310 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8311 outs() << " LOC_RELOC";
8312 if (section_attributes == 0)
8313 outs() << " (none)";
8314 outs() << "\n";
8315 } else
8316 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8317 outs() << " reserved1 " << reserved1;
8318 if (section_type == MachO::S_SYMBOL_STUBS ||
8319 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8320 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8321 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8322 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8323 outs() << " (index into indirect symbol table)\n";
8324 else
8325 outs() << "\n";
8326 outs() << " reserved2 " << reserved2;
8327 if (section_type == MachO::S_SYMBOL_STUBS)
8328 outs() << " (size of stubs)\n";
8329 else
8330 outs() << "\n";
8331}
8332
David Majnemer73cc6ff2014-11-13 19:48:56 +00008333static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008334 uint32_t object_size) {
8335 outs() << " cmd LC_SYMTAB\n";
8336 outs() << " cmdsize " << st.cmdsize;
8337 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8338 outs() << " Incorrect size\n";
8339 else
8340 outs() << "\n";
8341 outs() << " symoff " << st.symoff;
8342 if (st.symoff > object_size)
8343 outs() << " (past end of file)\n";
8344 else
8345 outs() << "\n";
8346 outs() << " nsyms " << st.nsyms;
8347 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008348 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008349 big_size = st.nsyms;
8350 big_size *= sizeof(struct MachO::nlist_64);
8351 big_size += st.symoff;
8352 if (big_size > object_size)
8353 outs() << " (past end of file)\n";
8354 else
8355 outs() << "\n";
8356 } else {
8357 big_size = st.nsyms;
8358 big_size *= sizeof(struct MachO::nlist);
8359 big_size += st.symoff;
8360 if (big_size > object_size)
8361 outs() << " (past end of file)\n";
8362 else
8363 outs() << "\n";
8364 }
8365 outs() << " stroff " << st.stroff;
8366 if (st.stroff > object_size)
8367 outs() << " (past end of file)\n";
8368 else
8369 outs() << "\n";
8370 outs() << " strsize " << st.strsize;
8371 big_size = st.stroff;
8372 big_size += st.strsize;
8373 if (big_size > object_size)
8374 outs() << " (past end of file)\n";
8375 else
8376 outs() << "\n";
8377}
8378
8379static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8380 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008381 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008382 outs() << " cmd LC_DYSYMTAB\n";
8383 outs() << " cmdsize " << dyst.cmdsize;
8384 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8385 outs() << " Incorrect size\n";
8386 else
8387 outs() << "\n";
8388 outs() << " ilocalsym " << dyst.ilocalsym;
8389 if (dyst.ilocalsym > nsyms)
8390 outs() << " (greater than the number of symbols)\n";
8391 else
8392 outs() << "\n";
8393 outs() << " nlocalsym " << dyst.nlocalsym;
8394 uint64_t big_size;
8395 big_size = dyst.ilocalsym;
8396 big_size += dyst.nlocalsym;
8397 if (big_size > nsyms)
8398 outs() << " (past the end of the symbol table)\n";
8399 else
8400 outs() << "\n";
8401 outs() << " iextdefsym " << dyst.iextdefsym;
8402 if (dyst.iextdefsym > nsyms)
8403 outs() << " (greater than the number of symbols)\n";
8404 else
8405 outs() << "\n";
8406 outs() << " nextdefsym " << dyst.nextdefsym;
8407 big_size = dyst.iextdefsym;
8408 big_size += dyst.nextdefsym;
8409 if (big_size > nsyms)
8410 outs() << " (past the end of the symbol table)\n";
8411 else
8412 outs() << "\n";
8413 outs() << " iundefsym " << dyst.iundefsym;
8414 if (dyst.iundefsym > nsyms)
8415 outs() << " (greater than the number of symbols)\n";
8416 else
8417 outs() << "\n";
8418 outs() << " nundefsym " << dyst.nundefsym;
8419 big_size = dyst.iundefsym;
8420 big_size += dyst.nundefsym;
8421 if (big_size > nsyms)
8422 outs() << " (past the end of the symbol table)\n";
8423 else
8424 outs() << "\n";
8425 outs() << " tocoff " << dyst.tocoff;
8426 if (dyst.tocoff > object_size)
8427 outs() << " (past end of file)\n";
8428 else
8429 outs() << "\n";
8430 outs() << " ntoc " << dyst.ntoc;
8431 big_size = dyst.ntoc;
8432 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8433 big_size += dyst.tocoff;
8434 if (big_size > object_size)
8435 outs() << " (past end of file)\n";
8436 else
8437 outs() << "\n";
8438 outs() << " modtaboff " << dyst.modtaboff;
8439 if (dyst.modtaboff > object_size)
8440 outs() << " (past end of file)\n";
8441 else
8442 outs() << "\n";
8443 outs() << " nmodtab " << dyst.nmodtab;
8444 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008445 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008446 modtabend = dyst.nmodtab;
8447 modtabend *= sizeof(struct MachO::dylib_module_64);
8448 modtabend += dyst.modtaboff;
8449 } else {
8450 modtabend = dyst.nmodtab;
8451 modtabend *= sizeof(struct MachO::dylib_module);
8452 modtabend += dyst.modtaboff;
8453 }
8454 if (modtabend > object_size)
8455 outs() << " (past end of file)\n";
8456 else
8457 outs() << "\n";
8458 outs() << " extrefsymoff " << dyst.extrefsymoff;
8459 if (dyst.extrefsymoff > object_size)
8460 outs() << " (past end of file)\n";
8461 else
8462 outs() << "\n";
8463 outs() << " nextrefsyms " << dyst.nextrefsyms;
8464 big_size = dyst.nextrefsyms;
8465 big_size *= sizeof(struct MachO::dylib_reference);
8466 big_size += dyst.extrefsymoff;
8467 if (big_size > object_size)
8468 outs() << " (past end of file)\n";
8469 else
8470 outs() << "\n";
8471 outs() << " indirectsymoff " << dyst.indirectsymoff;
8472 if (dyst.indirectsymoff > object_size)
8473 outs() << " (past end of file)\n";
8474 else
8475 outs() << "\n";
8476 outs() << " nindirectsyms " << dyst.nindirectsyms;
8477 big_size = dyst.nindirectsyms;
8478 big_size *= sizeof(uint32_t);
8479 big_size += dyst.indirectsymoff;
8480 if (big_size > object_size)
8481 outs() << " (past end of file)\n";
8482 else
8483 outs() << "\n";
8484 outs() << " extreloff " << dyst.extreloff;
8485 if (dyst.extreloff > object_size)
8486 outs() << " (past end of file)\n";
8487 else
8488 outs() << "\n";
8489 outs() << " nextrel " << dyst.nextrel;
8490 big_size = dyst.nextrel;
8491 big_size *= sizeof(struct MachO::relocation_info);
8492 big_size += dyst.extreloff;
8493 if (big_size > object_size)
8494 outs() << " (past end of file)\n";
8495 else
8496 outs() << "\n";
8497 outs() << " locreloff " << dyst.locreloff;
8498 if (dyst.locreloff > object_size)
8499 outs() << " (past end of file)\n";
8500 else
8501 outs() << "\n";
8502 outs() << " nlocrel " << dyst.nlocrel;
8503 big_size = dyst.nlocrel;
8504 big_size *= sizeof(struct MachO::relocation_info);
8505 big_size += dyst.locreloff;
8506 if (big_size > object_size)
8507 outs() << " (past end of file)\n";
8508 else
8509 outs() << "\n";
8510}
8511
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008512static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8513 uint32_t object_size) {
8514 if (dc.cmd == MachO::LC_DYLD_INFO)
8515 outs() << " cmd LC_DYLD_INFO\n";
8516 else
8517 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8518 outs() << " cmdsize " << dc.cmdsize;
8519 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8520 outs() << " Incorrect size\n";
8521 else
8522 outs() << "\n";
8523 outs() << " rebase_off " << dc.rebase_off;
8524 if (dc.rebase_off > object_size)
8525 outs() << " (past end of file)\n";
8526 else
8527 outs() << "\n";
8528 outs() << " rebase_size " << dc.rebase_size;
8529 uint64_t big_size;
8530 big_size = dc.rebase_off;
8531 big_size += dc.rebase_size;
8532 if (big_size > object_size)
8533 outs() << " (past end of file)\n";
8534 else
8535 outs() << "\n";
8536 outs() << " bind_off " << dc.bind_off;
8537 if (dc.bind_off > object_size)
8538 outs() << " (past end of file)\n";
8539 else
8540 outs() << "\n";
8541 outs() << " bind_size " << dc.bind_size;
8542 big_size = dc.bind_off;
8543 big_size += dc.bind_size;
8544 if (big_size > object_size)
8545 outs() << " (past end of file)\n";
8546 else
8547 outs() << "\n";
8548 outs() << " weak_bind_off " << dc.weak_bind_off;
8549 if (dc.weak_bind_off > object_size)
8550 outs() << " (past end of file)\n";
8551 else
8552 outs() << "\n";
8553 outs() << " weak_bind_size " << dc.weak_bind_size;
8554 big_size = dc.weak_bind_off;
8555 big_size += dc.weak_bind_size;
8556 if (big_size > object_size)
8557 outs() << " (past end of file)\n";
8558 else
8559 outs() << "\n";
8560 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8561 if (dc.lazy_bind_off > object_size)
8562 outs() << " (past end of file)\n";
8563 else
8564 outs() << "\n";
8565 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8566 big_size = dc.lazy_bind_off;
8567 big_size += dc.lazy_bind_size;
8568 if (big_size > object_size)
8569 outs() << " (past end of file)\n";
8570 else
8571 outs() << "\n";
8572 outs() << " export_off " << dc.export_off;
8573 if (dc.export_off > object_size)
8574 outs() << " (past end of file)\n";
8575 else
8576 outs() << "\n";
8577 outs() << " export_size " << dc.export_size;
8578 big_size = dc.export_off;
8579 big_size += dc.export_size;
8580 if (big_size > object_size)
8581 outs() << " (past end of file)\n";
8582 else
8583 outs() << "\n";
8584}
8585
8586static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8587 const char *Ptr) {
8588 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8589 outs() << " cmd LC_ID_DYLINKER\n";
8590 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8591 outs() << " cmd LC_LOAD_DYLINKER\n";
8592 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8593 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8594 else
8595 outs() << " cmd ?(" << dyld.cmd << ")\n";
8596 outs() << " cmdsize " << dyld.cmdsize;
8597 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8598 outs() << " Incorrect size\n";
8599 else
8600 outs() << "\n";
8601 if (dyld.name >= dyld.cmdsize)
8602 outs() << " name ?(bad offset " << dyld.name << ")\n";
8603 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008604 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008605 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8606 }
8607}
8608
8609static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8610 outs() << " cmd LC_UUID\n";
8611 outs() << " cmdsize " << uuid.cmdsize;
8612 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8613 outs() << " Incorrect size\n";
8614 else
8615 outs() << "\n";
8616 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008617 for (int i = 0; i < 16; ++i) {
8618 outs() << format("%02" PRIX32, uuid.uuid[i]);
8619 if (i == 3 || i == 5 || i == 7 || i == 9)
8620 outs() << "-";
8621 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008622 outs() << "\n";
8623}
8624
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008625static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008626 outs() << " cmd LC_RPATH\n";
8627 outs() << " cmdsize " << rpath.cmdsize;
8628 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8629 outs() << " Incorrect size\n";
8630 else
8631 outs() << "\n";
8632 if (rpath.path >= rpath.cmdsize)
8633 outs() << " path ?(bad offset " << rpath.path << ")\n";
8634 else {
8635 const char *P = (const char *)(Ptr) + rpath.path;
8636 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8637 }
8638}
8639
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008640static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008641 StringRef LoadCmdName;
8642 switch (vd.cmd) {
8643 case MachO::LC_VERSION_MIN_MACOSX:
8644 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8645 break;
8646 case MachO::LC_VERSION_MIN_IPHONEOS:
8647 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8648 break;
8649 case MachO::LC_VERSION_MIN_TVOS:
8650 LoadCmdName = "LC_VERSION_MIN_TVOS";
8651 break;
8652 case MachO::LC_VERSION_MIN_WATCHOS:
8653 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8654 break;
8655 default:
8656 llvm_unreachable("Unknown version min load command");
8657 }
8658
8659 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008660 outs() << " cmdsize " << vd.cmdsize;
8661 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8662 outs() << " Incorrect size\n";
8663 else
8664 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008665 outs() << " version "
8666 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8667 << MachOObjectFile::getVersionMinMinor(vd, false);
8668 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8669 if (Update != 0)
8670 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008671 outs() << "\n";
8672 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008673 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008674 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008675 outs() << " sdk "
8676 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8677 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008678 }
Davide Italiano56baef32015-08-26 12:26:11 +00008679 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8680 if (Update != 0)
8681 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008682 outs() << "\n";
8683}
8684
Kevin Enderbya4579c42017-01-19 17:36:31 +00008685static void PrintNoteLoadCommand(MachO::note_command Nt) {
8686 outs() << " cmd LC_NOTE\n";
8687 outs() << " cmdsize " << Nt.cmdsize;
8688 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8689 outs() << " Incorrect size\n";
8690 else
8691 outs() << "\n";
8692 const char *d = Nt.data_owner;
8693 outs() << "data_owner " << format("%.16s\n", d);
8694 outs() << " offset " << Nt.offset << "\n";
8695 outs() << " size " << Nt.size << "\n";
8696}
8697
Steven Wu5b54a422017-01-23 20:07:55 +00008698static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8699 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8700 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8701 << "\n";
8702}
8703
8704static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8705 MachO::build_version_command bd) {
8706 outs() << " cmd LC_BUILD_VERSION\n";
8707 outs() << " cmdsize " << bd.cmdsize;
8708 if (bd.cmdsize !=
8709 sizeof(struct MachO::build_version_command) +
8710 bd.ntools * sizeof(struct MachO::build_tool_version))
8711 outs() << " Incorrect size\n";
8712 else
8713 outs() << "\n";
8714 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8715 << "\n";
8716 if (bd.sdk)
8717 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8718 << "\n";
8719 else
8720 outs() << " sdk n/a\n";
8721 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8722 << "\n";
8723 outs() << " ntools " << bd.ntools << "\n";
8724 for (unsigned i = 0; i < bd.ntools; ++i) {
8725 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8726 PrintBuildToolVersion(bv);
8727 }
8728}
8729
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008730static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8731 outs() << " cmd LC_SOURCE_VERSION\n";
8732 outs() << " cmdsize " << sd.cmdsize;
8733 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8734 outs() << " Incorrect size\n";
8735 else
8736 outs() << "\n";
8737 uint64_t a = (sd.version >> 40) & 0xffffff;
8738 uint64_t b = (sd.version >> 30) & 0x3ff;
8739 uint64_t c = (sd.version >> 20) & 0x3ff;
8740 uint64_t d = (sd.version >> 10) & 0x3ff;
8741 uint64_t e = sd.version & 0x3ff;
8742 outs() << " version " << a << "." << b;
8743 if (e != 0)
8744 outs() << "." << c << "." << d << "." << e;
8745 else if (d != 0)
8746 outs() << "." << c << "." << d;
8747 else if (c != 0)
8748 outs() << "." << c;
8749 outs() << "\n";
8750}
8751
8752static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8753 outs() << " cmd LC_MAIN\n";
8754 outs() << " cmdsize " << ep.cmdsize;
8755 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8756 outs() << " Incorrect size\n";
8757 else
8758 outs() << "\n";
8759 outs() << " entryoff " << ep.entryoff << "\n";
8760 outs() << " stacksize " << ep.stacksize << "\n";
8761}
8762
Kevin Enderby0804f4672014-12-16 23:25:52 +00008763static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8764 uint32_t object_size) {
8765 outs() << " cmd LC_ENCRYPTION_INFO\n";
8766 outs() << " cmdsize " << ec.cmdsize;
8767 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8768 outs() << " Incorrect size\n";
8769 else
8770 outs() << "\n";
8771 outs() << " cryptoff " << ec.cryptoff;
8772 if (ec.cryptoff > object_size)
8773 outs() << " (past end of file)\n";
8774 else
8775 outs() << "\n";
8776 outs() << " cryptsize " << ec.cryptsize;
8777 if (ec.cryptsize > object_size)
8778 outs() << " (past end of file)\n";
8779 else
8780 outs() << "\n";
8781 outs() << " cryptid " << ec.cryptid << "\n";
8782}
8783
Kevin Enderby57538292014-12-17 01:01:30 +00008784static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008785 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008786 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8787 outs() << " cmdsize " << ec.cmdsize;
8788 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8789 outs() << " Incorrect size\n";
8790 else
8791 outs() << "\n";
8792 outs() << " cryptoff " << ec.cryptoff;
8793 if (ec.cryptoff > object_size)
8794 outs() << " (past end of file)\n";
8795 else
8796 outs() << "\n";
8797 outs() << " cryptsize " << ec.cryptsize;
8798 if (ec.cryptsize > object_size)
8799 outs() << " (past end of file)\n";
8800 else
8801 outs() << "\n";
8802 outs() << " cryptid " << ec.cryptid << "\n";
8803 outs() << " pad " << ec.pad << "\n";
8804}
8805
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008806static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8807 const char *Ptr) {
8808 outs() << " cmd LC_LINKER_OPTION\n";
8809 outs() << " cmdsize " << lo.cmdsize;
8810 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8811 outs() << " Incorrect size\n";
8812 else
8813 outs() << "\n";
8814 outs() << " count " << lo.count << "\n";
8815 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8816 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8817 uint32_t i = 0;
8818 while (left > 0) {
8819 while (*string == '\0' && left > 0) {
8820 string++;
8821 left--;
8822 }
8823 if (left > 0) {
8824 i++;
8825 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008826 uint32_t NullPos = StringRef(string, left).find('\0');
8827 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008828 string += len;
8829 left -= len;
8830 }
8831 }
8832 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008833 outs() << " count " << lo.count << " does not match number of strings "
8834 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008835}
8836
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008837static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8838 const char *Ptr) {
8839 outs() << " cmd LC_SUB_FRAMEWORK\n";
8840 outs() << " cmdsize " << sub.cmdsize;
8841 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8842 outs() << " Incorrect size\n";
8843 else
8844 outs() << "\n";
8845 if (sub.umbrella < sub.cmdsize) {
8846 const char *P = Ptr + sub.umbrella;
8847 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8848 } else {
8849 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8850 }
8851}
8852
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008853static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8854 const char *Ptr) {
8855 outs() << " cmd LC_SUB_UMBRELLA\n";
8856 outs() << " cmdsize " << sub.cmdsize;
8857 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8858 outs() << " Incorrect size\n";
8859 else
8860 outs() << "\n";
8861 if (sub.sub_umbrella < sub.cmdsize) {
8862 const char *P = Ptr + sub.sub_umbrella;
8863 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8864 } else {
8865 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8866 }
8867}
8868
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008869static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008870 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008871 outs() << " cmd LC_SUB_LIBRARY\n";
8872 outs() << " cmdsize " << sub.cmdsize;
8873 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8874 outs() << " Incorrect size\n";
8875 else
8876 outs() << "\n";
8877 if (sub.sub_library < sub.cmdsize) {
8878 const char *P = Ptr + sub.sub_library;
8879 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8880 } else {
8881 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8882 }
8883}
8884
Kevin Enderby186eac32014-12-19 21:06:24 +00008885static void PrintSubClientCommand(MachO::sub_client_command sub,
8886 const char *Ptr) {
8887 outs() << " cmd LC_SUB_CLIENT\n";
8888 outs() << " cmdsize " << sub.cmdsize;
8889 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8890 outs() << " Incorrect size\n";
8891 else
8892 outs() << "\n";
8893 if (sub.client < sub.cmdsize) {
8894 const char *P = Ptr + sub.client;
8895 outs() << " client " << P << " (offset " << sub.client << ")\n";
8896 } else {
8897 outs() << " client ?(bad offset " << sub.client << ")\n";
8898 }
8899}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008900
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008901static void PrintRoutinesCommand(MachO::routines_command r) {
8902 outs() << " cmd LC_ROUTINES\n";
8903 outs() << " cmdsize " << r.cmdsize;
8904 if (r.cmdsize != sizeof(struct MachO::routines_command))
8905 outs() << " Incorrect size\n";
8906 else
8907 outs() << "\n";
8908 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8909 outs() << " init_module " << r.init_module << "\n";
8910 outs() << " reserved1 " << r.reserved1 << "\n";
8911 outs() << " reserved2 " << r.reserved2 << "\n";
8912 outs() << " reserved3 " << r.reserved3 << "\n";
8913 outs() << " reserved4 " << r.reserved4 << "\n";
8914 outs() << " reserved5 " << r.reserved5 << "\n";
8915 outs() << " reserved6 " << r.reserved6 << "\n";
8916}
8917
8918static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8919 outs() << " cmd LC_ROUTINES_64\n";
8920 outs() << " cmdsize " << r.cmdsize;
8921 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8922 outs() << " Incorrect size\n";
8923 else
8924 outs() << "\n";
8925 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8926 outs() << " init_module " << r.init_module << "\n";
8927 outs() << " reserved1 " << r.reserved1 << "\n";
8928 outs() << " reserved2 " << r.reserved2 << "\n";
8929 outs() << " reserved3 " << r.reserved3 << "\n";
8930 outs() << " reserved4 " << r.reserved4 << "\n";
8931 outs() << " reserved5 " << r.reserved5 << "\n";
8932 outs() << " reserved6 " << r.reserved6 << "\n";
8933}
8934
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008935static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8936 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8937 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8938 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8939 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8940 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8941 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8942 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8943 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8944 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8945 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8946 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8947 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8948 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8949 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8950 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8951 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8952}
8953
Kevin Enderby48ef5342014-12-23 22:56:39 +00008954static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8955 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8956 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8957 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8958 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8959 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8960 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8961 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8962 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8963 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8964 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8965 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8966 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8967 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8968 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8969 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8970 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8971 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8972 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8973 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8974 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8975 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8976}
8977
Kevin Enderby227df342014-12-23 23:43:59 +00008978static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008979 uint32_t f;
8980 outs() << "\t mmst_reg ";
8981 for (f = 0; f < 10; f++)
8982 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8983 outs() << "\n";
8984 outs() << "\t mmst_rsrv ";
8985 for (f = 0; f < 6; f++)
8986 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8987 outs() << "\n";
8988}
8989
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008990static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008991 uint32_t f;
8992 outs() << "\t xmm_reg ";
8993 for (f = 0; f < 16; f++)
8994 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8995 outs() << "\n";
8996}
8997
8998static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8999 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9000 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9001 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9002 outs() << " denorm " << fpu.fpu_fcw.denorm;
9003 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9004 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9005 outs() << " undfl " << fpu.fpu_fcw.undfl;
9006 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9007 outs() << "\t\t pc ";
9008 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9009 outs() << "FP_PREC_24B ";
9010 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9011 outs() << "FP_PREC_53B ";
9012 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9013 outs() << "FP_PREC_64B ";
9014 else
9015 outs() << fpu.fpu_fcw.pc << " ";
9016 outs() << "rc ";
9017 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9018 outs() << "FP_RND_NEAR ";
9019 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9020 outs() << "FP_RND_DOWN ";
9021 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9022 outs() << "FP_RND_UP ";
9023 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009024 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009025 outs() << "\n";
9026 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9027 outs() << " denorm " << fpu.fpu_fsw.denorm;
9028 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9029 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9030 outs() << " undfl " << fpu.fpu_fsw.undfl;
9031 outs() << " precis " << fpu.fpu_fsw.precis;
9032 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9033 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9034 outs() << " c0 " << fpu.fpu_fsw.c0;
9035 outs() << " c1 " << fpu.fpu_fsw.c1;
9036 outs() << " c2 " << fpu.fpu_fsw.c2;
9037 outs() << " tos " << fpu.fpu_fsw.tos;
9038 outs() << " c3 " << fpu.fpu_fsw.c3;
9039 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9040 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9041 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9042 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9043 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9044 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9045 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9046 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9047 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9048 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9049 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9050 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9051 outs() << "\n";
9052 outs() << "\t fpu_stmm0:\n";
9053 Print_mmst_reg(fpu.fpu_stmm0);
9054 outs() << "\t fpu_stmm1:\n";
9055 Print_mmst_reg(fpu.fpu_stmm1);
9056 outs() << "\t fpu_stmm2:\n";
9057 Print_mmst_reg(fpu.fpu_stmm2);
9058 outs() << "\t fpu_stmm3:\n";
9059 Print_mmst_reg(fpu.fpu_stmm3);
9060 outs() << "\t fpu_stmm4:\n";
9061 Print_mmst_reg(fpu.fpu_stmm4);
9062 outs() << "\t fpu_stmm5:\n";
9063 Print_mmst_reg(fpu.fpu_stmm5);
9064 outs() << "\t fpu_stmm6:\n";
9065 Print_mmst_reg(fpu.fpu_stmm6);
9066 outs() << "\t fpu_stmm7:\n";
9067 Print_mmst_reg(fpu.fpu_stmm7);
9068 outs() << "\t fpu_xmm0:\n";
9069 Print_xmm_reg(fpu.fpu_xmm0);
9070 outs() << "\t fpu_xmm1:\n";
9071 Print_xmm_reg(fpu.fpu_xmm1);
9072 outs() << "\t fpu_xmm2:\n";
9073 Print_xmm_reg(fpu.fpu_xmm2);
9074 outs() << "\t fpu_xmm3:\n";
9075 Print_xmm_reg(fpu.fpu_xmm3);
9076 outs() << "\t fpu_xmm4:\n";
9077 Print_xmm_reg(fpu.fpu_xmm4);
9078 outs() << "\t fpu_xmm5:\n";
9079 Print_xmm_reg(fpu.fpu_xmm5);
9080 outs() << "\t fpu_xmm6:\n";
9081 Print_xmm_reg(fpu.fpu_xmm6);
9082 outs() << "\t fpu_xmm7:\n";
9083 Print_xmm_reg(fpu.fpu_xmm7);
9084 outs() << "\t fpu_xmm8:\n";
9085 Print_xmm_reg(fpu.fpu_xmm8);
9086 outs() << "\t fpu_xmm9:\n";
9087 Print_xmm_reg(fpu.fpu_xmm9);
9088 outs() << "\t fpu_xmm10:\n";
9089 Print_xmm_reg(fpu.fpu_xmm10);
9090 outs() << "\t fpu_xmm11:\n";
9091 Print_xmm_reg(fpu.fpu_xmm11);
9092 outs() << "\t fpu_xmm12:\n";
9093 Print_xmm_reg(fpu.fpu_xmm12);
9094 outs() << "\t fpu_xmm13:\n";
9095 Print_xmm_reg(fpu.fpu_xmm13);
9096 outs() << "\t fpu_xmm14:\n";
9097 Print_xmm_reg(fpu.fpu_xmm14);
9098 outs() << "\t fpu_xmm15:\n";
9099 Print_xmm_reg(fpu.fpu_xmm15);
9100 outs() << "\t fpu_rsrv4:\n";
9101 for (uint32_t f = 0; f < 6; f++) {
9102 outs() << "\t ";
9103 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009104 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009105 outs() << "\n";
9106 }
9107 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9108 outs() << "\n";
9109}
9110
9111static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9112 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9113 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9114 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9115}
9116
Kevin Enderby41c9c002016-10-21 18:22:35 +00009117static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9118 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9119 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9120 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9121 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9122 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9123 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9124 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9125 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9126 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9127 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9128 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9129 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9130 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9131 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9132 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9133 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9134 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9135}
9136
Kevin Enderby7747cb52016-11-03 20:51:28 +00009137static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9138 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9139 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9140 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9141 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9142 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9143 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9144 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9145 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9146 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9147 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9148 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9149 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9150 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9151 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9152 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9153 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9154 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9155 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9156 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9157 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9158 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9159 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9160 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9161 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9162 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9163 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9164 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9165 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9166 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9167 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9168 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9169 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9170 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9171 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9172}
9173
Kevin Enderby48ef5342014-12-23 22:56:39 +00009174static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9175 bool isLittleEndian, uint32_t cputype) {
9176 if (t.cmd == MachO::LC_THREAD)
9177 outs() << " cmd LC_THREAD\n";
9178 else if (t.cmd == MachO::LC_UNIXTHREAD)
9179 outs() << " cmd LC_UNIXTHREAD\n";
9180 else
9181 outs() << " cmd " << t.cmd << " (unknown)\n";
9182 outs() << " cmdsize " << t.cmdsize;
9183 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9184 outs() << " Incorrect size\n";
9185 else
9186 outs() << "\n";
9187
9188 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9189 const char *end = Ptr + t.cmdsize;
9190 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009191 if (cputype == MachO::CPU_TYPE_I386) {
9192 while (begin < end) {
9193 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9194 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9195 begin += sizeof(uint32_t);
9196 } else {
9197 flavor = 0;
9198 begin = end;
9199 }
9200 if (isLittleEndian != sys::IsLittleEndianHost)
9201 sys::swapByteOrder(flavor);
9202 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9203 memcpy((char *)&count, begin, sizeof(uint32_t));
9204 begin += sizeof(uint32_t);
9205 } else {
9206 count = 0;
9207 begin = end;
9208 }
9209 if (isLittleEndian != sys::IsLittleEndianHost)
9210 sys::swapByteOrder(count);
9211 if (flavor == MachO::x86_THREAD_STATE32) {
9212 outs() << " flavor i386_THREAD_STATE\n";
9213 if (count == MachO::x86_THREAD_STATE32_COUNT)
9214 outs() << " count i386_THREAD_STATE_COUNT\n";
9215 else
9216 outs() << " count " << count
9217 << " (not x86_THREAD_STATE32_COUNT)\n";
9218 MachO::x86_thread_state32_t cpu32;
9219 left = end - begin;
9220 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9221 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9222 begin += sizeof(MachO::x86_thread_state32_t);
9223 } else {
9224 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9225 memcpy(&cpu32, begin, left);
9226 begin += left;
9227 }
9228 if (isLittleEndian != sys::IsLittleEndianHost)
9229 swapStruct(cpu32);
9230 Print_x86_thread_state32_t(cpu32);
9231 } else if (flavor == MachO::x86_THREAD_STATE) {
9232 outs() << " flavor x86_THREAD_STATE\n";
9233 if (count == MachO::x86_THREAD_STATE_COUNT)
9234 outs() << " count x86_THREAD_STATE_COUNT\n";
9235 else
9236 outs() << " count " << count
9237 << " (not x86_THREAD_STATE_COUNT)\n";
9238 struct MachO::x86_thread_state_t ts;
9239 left = end - begin;
9240 if (left >= sizeof(MachO::x86_thread_state_t)) {
9241 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9242 begin += sizeof(MachO::x86_thread_state_t);
9243 } else {
9244 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9245 memcpy(&ts, begin, left);
9246 begin += left;
9247 }
9248 if (isLittleEndian != sys::IsLittleEndianHost)
9249 swapStruct(ts);
9250 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9251 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9252 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9253 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9254 else
9255 outs() << "tsh.count " << ts.tsh.count
9256 << " (not x86_THREAD_STATE32_COUNT\n";
9257 Print_x86_thread_state32_t(ts.uts.ts32);
9258 } else {
9259 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9260 << ts.tsh.count << "\n";
9261 }
9262 } else {
9263 outs() << " flavor " << flavor << " (unknown)\n";
9264 outs() << " count " << count << "\n";
9265 outs() << " state (unknown)\n";
9266 begin += count * sizeof(uint32_t);
9267 }
9268 }
9269 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009270 while (begin < end) {
9271 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9272 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9273 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009274 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009275 flavor = 0;
9276 begin = end;
9277 }
9278 if (isLittleEndian != sys::IsLittleEndianHost)
9279 sys::swapByteOrder(flavor);
9280 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9281 memcpy((char *)&count, begin, sizeof(uint32_t));
9282 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009283 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009284 count = 0;
9285 begin = end;
9286 }
9287 if (isLittleEndian != sys::IsLittleEndianHost)
9288 sys::swapByteOrder(count);
9289 if (flavor == MachO::x86_THREAD_STATE64) {
9290 outs() << " flavor x86_THREAD_STATE64\n";
9291 if (count == MachO::x86_THREAD_STATE64_COUNT)
9292 outs() << " count x86_THREAD_STATE64_COUNT\n";
9293 else
9294 outs() << " count " << count
9295 << " (not x86_THREAD_STATE64_COUNT)\n";
9296 MachO::x86_thread_state64_t cpu64;
9297 left = end - begin;
9298 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9299 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9300 begin += sizeof(MachO::x86_thread_state64_t);
9301 } else {
9302 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9303 memcpy(&cpu64, begin, left);
9304 begin += left;
9305 }
9306 if (isLittleEndian != sys::IsLittleEndianHost)
9307 swapStruct(cpu64);
9308 Print_x86_thread_state64_t(cpu64);
9309 } else if (flavor == MachO::x86_THREAD_STATE) {
9310 outs() << " flavor x86_THREAD_STATE\n";
9311 if (count == MachO::x86_THREAD_STATE_COUNT)
9312 outs() << " count x86_THREAD_STATE_COUNT\n";
9313 else
9314 outs() << " count " << count
9315 << " (not x86_THREAD_STATE_COUNT)\n";
9316 struct MachO::x86_thread_state_t ts;
9317 left = end - begin;
9318 if (left >= sizeof(MachO::x86_thread_state_t)) {
9319 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9320 begin += sizeof(MachO::x86_thread_state_t);
9321 } else {
9322 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9323 memcpy(&ts, begin, left);
9324 begin += left;
9325 }
9326 if (isLittleEndian != sys::IsLittleEndianHost)
9327 swapStruct(ts);
9328 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9329 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9330 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9331 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9332 else
9333 outs() << "tsh.count " << ts.tsh.count
9334 << " (not x86_THREAD_STATE64_COUNT\n";
9335 Print_x86_thread_state64_t(ts.uts.ts64);
9336 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009337 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9338 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009339 }
9340 } else if (flavor == MachO::x86_FLOAT_STATE) {
9341 outs() << " flavor x86_FLOAT_STATE\n";
9342 if (count == MachO::x86_FLOAT_STATE_COUNT)
9343 outs() << " count x86_FLOAT_STATE_COUNT\n";
9344 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009345 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009346 struct MachO::x86_float_state_t fs;
9347 left = end - begin;
9348 if (left >= sizeof(MachO::x86_float_state_t)) {
9349 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9350 begin += sizeof(MachO::x86_float_state_t);
9351 } else {
9352 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9353 memcpy(&fs, begin, left);
9354 begin += left;
9355 }
9356 if (isLittleEndian != sys::IsLittleEndianHost)
9357 swapStruct(fs);
9358 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9359 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009360 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009361 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9362 else
9363 outs() << "fsh.count " << fs.fsh.count
9364 << " (not x86_FLOAT_STATE64_COUNT\n";
9365 Print_x86_float_state_t(fs.ufs.fs64);
9366 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009367 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9368 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009369 }
9370 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9371 outs() << " flavor x86_EXCEPTION_STATE\n";
9372 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9373 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9374 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009375 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009376 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9377 struct MachO::x86_exception_state_t es;
9378 left = end - begin;
9379 if (left >= sizeof(MachO::x86_exception_state_t)) {
9380 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9381 begin += sizeof(MachO::x86_exception_state_t);
9382 } else {
9383 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9384 memcpy(&es, begin, left);
9385 begin += left;
9386 }
9387 if (isLittleEndian != sys::IsLittleEndianHost)
9388 swapStruct(es);
9389 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9390 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009391 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009392 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9393 else
9394 outs() << "\t esh.count " << es.esh.count
9395 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9396 Print_x86_exception_state_t(es.ues.es64);
9397 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009398 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9399 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009400 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009401 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9402 outs() << " flavor x86_EXCEPTION_STATE64\n";
9403 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9404 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9405 else
9406 outs() << " count " << count
9407 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9408 struct MachO::x86_exception_state64_t es64;
9409 left = end - begin;
9410 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9411 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9412 begin += sizeof(MachO::x86_exception_state64_t);
9413 } else {
9414 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9415 memcpy(&es64, begin, left);
9416 begin += left;
9417 }
9418 if (isLittleEndian != sys::IsLittleEndianHost)
9419 swapStruct(es64);
9420 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009421 } else {
9422 outs() << " flavor " << flavor << " (unknown)\n";
9423 outs() << " count " << count << "\n";
9424 outs() << " state (unknown)\n";
9425 begin += count * sizeof(uint32_t);
9426 }
9427 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009428 } else if (cputype == MachO::CPU_TYPE_ARM) {
9429 while (begin < end) {
9430 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9431 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9432 begin += sizeof(uint32_t);
9433 } else {
9434 flavor = 0;
9435 begin = end;
9436 }
9437 if (isLittleEndian != sys::IsLittleEndianHost)
9438 sys::swapByteOrder(flavor);
9439 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9440 memcpy((char *)&count, begin, sizeof(uint32_t));
9441 begin += sizeof(uint32_t);
9442 } else {
9443 count = 0;
9444 begin = end;
9445 }
9446 if (isLittleEndian != sys::IsLittleEndianHost)
9447 sys::swapByteOrder(count);
9448 if (flavor == MachO::ARM_THREAD_STATE) {
9449 outs() << " flavor ARM_THREAD_STATE\n";
9450 if (count == MachO::ARM_THREAD_STATE_COUNT)
9451 outs() << " count ARM_THREAD_STATE_COUNT\n";
9452 else
9453 outs() << " count " << count
9454 << " (not ARM_THREAD_STATE_COUNT)\n";
9455 MachO::arm_thread_state32_t cpu32;
9456 left = end - begin;
9457 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9458 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9459 begin += sizeof(MachO::arm_thread_state32_t);
9460 } else {
9461 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9462 memcpy(&cpu32, begin, left);
9463 begin += left;
9464 }
9465 if (isLittleEndian != sys::IsLittleEndianHost)
9466 swapStruct(cpu32);
9467 Print_arm_thread_state32_t(cpu32);
9468 } else {
9469 outs() << " flavor " << flavor << " (unknown)\n";
9470 outs() << " count " << count << "\n";
9471 outs() << " state (unknown)\n";
9472 begin += count * sizeof(uint32_t);
9473 }
9474 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009475 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9476 while (begin < end) {
9477 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9478 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9479 begin += sizeof(uint32_t);
9480 } else {
9481 flavor = 0;
9482 begin = end;
9483 }
9484 if (isLittleEndian != sys::IsLittleEndianHost)
9485 sys::swapByteOrder(flavor);
9486 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9487 memcpy((char *)&count, begin, sizeof(uint32_t));
9488 begin += sizeof(uint32_t);
9489 } else {
9490 count = 0;
9491 begin = end;
9492 }
9493 if (isLittleEndian != sys::IsLittleEndianHost)
9494 sys::swapByteOrder(count);
9495 if (flavor == MachO::ARM_THREAD_STATE64) {
9496 outs() << " flavor ARM_THREAD_STATE64\n";
9497 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9498 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9499 else
9500 outs() << " count " << count
9501 << " (not ARM_THREAD_STATE64_COUNT)\n";
9502 MachO::arm_thread_state64_t cpu64;
9503 left = end - begin;
9504 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9505 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9506 begin += sizeof(MachO::arm_thread_state64_t);
9507 } else {
9508 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9509 memcpy(&cpu64, begin, left);
9510 begin += left;
9511 }
9512 if (isLittleEndian != sys::IsLittleEndianHost)
9513 swapStruct(cpu64);
9514 Print_arm_thread_state64_t(cpu64);
9515 } else {
9516 outs() << " flavor " << flavor << " (unknown)\n";
9517 outs() << " count " << count << "\n";
9518 outs() << " state (unknown)\n";
9519 begin += count * sizeof(uint32_t);
9520 }
9521 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009522 } else {
9523 while (begin < end) {
9524 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9525 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9526 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009527 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009528 flavor = 0;
9529 begin = end;
9530 }
9531 if (isLittleEndian != sys::IsLittleEndianHost)
9532 sys::swapByteOrder(flavor);
9533 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9534 memcpy((char *)&count, begin, sizeof(uint32_t));
9535 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009536 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009537 count = 0;
9538 begin = end;
9539 }
9540 if (isLittleEndian != sys::IsLittleEndianHost)
9541 sys::swapByteOrder(count);
9542 outs() << " flavor " << flavor << "\n";
9543 outs() << " count " << count << "\n";
9544 outs() << " state (Unknown cputype/cpusubtype)\n";
9545 begin += count * sizeof(uint32_t);
9546 }
9547 }
9548}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009549
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009550static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9551 if (dl.cmd == MachO::LC_ID_DYLIB)
9552 outs() << " cmd LC_ID_DYLIB\n";
9553 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9554 outs() << " cmd LC_LOAD_DYLIB\n";
9555 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9556 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9557 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9558 outs() << " cmd LC_REEXPORT_DYLIB\n";
9559 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9560 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9561 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9562 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9563 else
9564 outs() << " cmd " << dl.cmd << " (unknown)\n";
9565 outs() << " cmdsize " << dl.cmdsize;
9566 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9567 outs() << " Incorrect size\n";
9568 else
9569 outs() << "\n";
9570 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009571 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009572 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9573 } else {
9574 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9575 }
9576 outs() << " time stamp " << dl.dylib.timestamp << " ";
9577 time_t t = dl.dylib.timestamp;
9578 outs() << ctime(&t);
9579 outs() << " current version ";
9580 if (dl.dylib.current_version == 0xffffffff)
9581 outs() << "n/a\n";
9582 else
9583 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9584 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9585 << (dl.dylib.current_version & 0xff) << "\n";
9586 outs() << "compatibility version ";
9587 if (dl.dylib.compatibility_version == 0xffffffff)
9588 outs() << "n/a\n";
9589 else
9590 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9591 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9592 << (dl.dylib.compatibility_version & 0xff) << "\n";
9593}
9594
9595static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9596 uint32_t object_size) {
9597 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009598 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009599 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9600 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9601 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9602 outs() << " cmd LC_FUNCTION_STARTS\n";
9603 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9604 outs() << " cmd LC_DATA_IN_CODE\n";
9605 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9606 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9607 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9608 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9609 else
9610 outs() << " cmd " << ld.cmd << " (?)\n";
9611 outs() << " cmdsize " << ld.cmdsize;
9612 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9613 outs() << " Incorrect size\n";
9614 else
9615 outs() << "\n";
9616 outs() << " dataoff " << ld.dataoff;
9617 if (ld.dataoff > object_size)
9618 outs() << " (past end of file)\n";
9619 else
9620 outs() << "\n";
9621 outs() << " datasize " << ld.datasize;
9622 uint64_t big_size = ld.dataoff;
9623 big_size += ld.datasize;
9624 if (big_size > object_size)
9625 outs() << " (past end of file)\n";
9626 else
9627 outs() << "\n";
9628}
9629
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009630static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9631 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009632 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009633 unsigned Index = 0;
9634 for (const auto &Command : Obj->load_commands()) {
9635 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009636 if (Command.C.cmd == MachO::LC_SEGMENT) {
9637 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9638 const char *sg_segname = SLC.segname;
9639 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9640 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9641 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9642 verbose);
9643 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009644 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009645 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9646 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9647 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9648 }
9649 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9650 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9651 const char *sg_segname = SLC_64.segname;
9652 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9653 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9654 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9655 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9656 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9657 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9658 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9659 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9660 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9661 sg_segname, filetype, Buf.size(), verbose);
9662 }
9663 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9664 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009665 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009666 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9667 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9668 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009669 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9670 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009671 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9672 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9673 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9674 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9675 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9676 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9677 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9678 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9679 PrintDyldLoadCommand(Dyld, Command.Ptr);
9680 } else if (Command.C.cmd == MachO::LC_UUID) {
9681 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9682 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009683 } else if (Command.C.cmd == MachO::LC_RPATH) {
9684 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9685 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009686 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009687 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9688 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9689 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009690 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9691 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009692 } else if (Command.C.cmd == MachO::LC_NOTE) {
9693 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9694 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009695 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9696 MachO::build_version_command Bv =
9697 Obj->getBuildVersionLoadCommand(Command);
9698 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009699 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9700 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9701 PrintSourceVersionCommand(Sd);
9702 } else if (Command.C.cmd == MachO::LC_MAIN) {
9703 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9704 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009705 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009706 MachO::encryption_info_command Ei =
9707 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009708 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009709 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009710 MachO::encryption_info_command_64 Ei =
9711 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009712 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009713 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009714 MachO::linker_option_command Lo =
9715 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009716 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009717 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9718 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9719 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009720 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9721 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9722 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009723 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9724 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9725 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009726 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9727 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9728 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009729 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9730 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9731 PrintRoutinesCommand(Rc);
9732 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9733 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9734 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009735 } else if (Command.C.cmd == MachO::LC_THREAD ||
9736 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9737 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9738 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009739 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9740 Command.C.cmd == MachO::LC_ID_DYLIB ||
9741 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9742 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9743 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9744 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009745 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9746 PrintDylibCommand(Dl, Command.Ptr);
9747 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9748 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9749 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9750 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9751 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9752 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9753 MachO::linkedit_data_command Ld =
9754 Obj->getLinkeditDataLoadCommand(Command);
9755 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009756 } else {
9757 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9758 << ")\n";
9759 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9760 // TODO: get and print the raw bytes of the load command.
9761 }
9762 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009763 }
9764}
9765
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009766static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009767 if (Obj->is64Bit()) {
9768 MachO::mach_header_64 H_64;
9769 H_64 = Obj->getHeader64();
9770 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9771 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9772 } else {
9773 MachO::mach_header H;
9774 H = Obj->getHeader();
9775 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9776 H.sizeofcmds, H.flags, verbose);
9777 }
9778}
9779
9780void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9781 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009782 PrintMachHeader(file, !NonVerbose);
9783}
9784
9785void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9786 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009787 uint32_t filetype = 0;
9788 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009789 if (file->is64Bit()) {
9790 MachO::mach_header_64 H_64;
9791 H_64 = file->getHeader64();
9792 filetype = H_64.filetype;
9793 cputype = H_64.cputype;
9794 } else {
9795 MachO::mach_header H;
9796 H = file->getHeader();
9797 filetype = H.filetype;
9798 cputype = H.cputype;
9799 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009800 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009801}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009802
9803//===----------------------------------------------------------------------===//
9804// export trie dumping
9805//===----------------------------------------------------------------------===//
9806
9807void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009808 uint64_t BaseSegmentAddress = 0;
9809 for (const auto &Command : Obj->load_commands()) {
9810 if (Command.C.cmd == MachO::LC_SEGMENT) {
9811 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9812 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9813 BaseSegmentAddress = Seg.vmaddr;
9814 break;
9815 }
9816 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9817 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9818 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9819 BaseSegmentAddress = Seg.vmaddr;
9820 break;
9821 }
9822 }
9823 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009824 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +00009825 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009826 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009827 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9828 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9829 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9830 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9831 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9832 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9833 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9834 if (ReExport)
9835 outs() << "[re-export] ";
9836 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009837 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009838 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009839 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009840 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009841 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009842 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009843 if (WeakDef) {
9844 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009845 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009846 }
9847 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009848 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009849 outs() << ", ";
9850 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009851 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009852 }
9853 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009854 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009855 outs() << ", ";
9856 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009857 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009858 }
9859 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009860 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009861 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009862 outs() << format("resolver=0x%08llX", Entry.other());
9863 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009864 }
9865 outs() << "]";
9866 }
9867 if (ReExport) {
9868 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009869 int Ordinal = Entry.other() - 1;
9870 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9871 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009872 outs() << " (from " << DylibName << ")";
9873 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009874 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009875 }
9876 outs() << "\n";
9877 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009878 if (Err)
9879 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +00009880}
Nick Kledzikac431442014-09-12 21:34:15 +00009881
Nick Kledzikac431442014-09-12 21:34:15 +00009882//===----------------------------------------------------------------------===//
9883// rebase table dumping
9884//===----------------------------------------------------------------------===//
9885
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009886void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009887 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009888 Error Err = Error::success();
9889 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9890 StringRef SegmentName = Entry.segmentName();
9891 StringRef SectionName = Entry.sectionName();
9892 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009893
9894 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009895 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9896 SegmentName.str().c_str(), SectionName.str().c_str(),
9897 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009898 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009899 if (Err)
9900 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009901}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009902
9903static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9904 StringRef DylibName;
9905 switch (Ordinal) {
9906 case MachO::BIND_SPECIAL_DYLIB_SELF:
9907 return "this-image";
9908 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9909 return "main-executable";
9910 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9911 return "flat-namespace";
9912 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009913 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009914 std::error_code EC =
9915 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009916 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009917 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009918 return DylibName;
9919 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009920 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009921 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009922}
9923
9924//===----------------------------------------------------------------------===//
9925// bind table dumping
9926//===----------------------------------------------------------------------===//
9927
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009928void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009929 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009930 outs() << "segment section address type "
9931 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009932 Error Err = Error::success();
9933 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009934 StringRef SegmentName = Entry.segmentName();
9935 StringRef SectionName = Entry.sectionName();
9936 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009937
9938 // Table lines look like:
9939 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009940 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009941 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009942 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009943 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009944 << left_justify(SectionName, 18) << " "
9945 << format_hex(Address, 10, true) << " "
9946 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009947 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009948 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009949 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009950 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009951 if (Err)
9952 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009953}
9954
9955//===----------------------------------------------------------------------===//
9956// lazy bind table dumping
9957//===----------------------------------------------------------------------===//
9958
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009959void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009960 outs() << "segment section address "
9961 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009962 Error Err = Error::success();
9963 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009964 StringRef SegmentName = Entry.segmentName();
9965 StringRef SectionName = Entry.sectionName();
9966 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009967
9968 // Table lines look like:
9969 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009970 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009971 << left_justify(SectionName, 18) << " "
9972 << format_hex(Address, 10, true) << " "
9973 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009974 << Entry.symbolName() << "\n";
9975 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009976 if (Err)
9977 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009978}
9979
Nick Kledzik56ebef42014-09-16 01:41:51 +00009980//===----------------------------------------------------------------------===//
9981// weak bind table dumping
9982//===----------------------------------------------------------------------===//
9983
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009984void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009985 outs() << "segment section address "
9986 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009987 Error Err = Error::success();
9988 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009989 // Strong symbols don't have a location to update.
9990 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009991 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009992 << Entry.symbolName() << "\n";
9993 continue;
9994 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009995 StringRef SegmentName = Entry.segmentName();
9996 StringRef SectionName = Entry.sectionName();
9997 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009998
9999 // Table lines look like:
10000 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010001 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010002 << left_justify(SectionName, 18) << " "
10003 << format_hex(Address, 10, true) << " "
10004 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010005 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10006 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010007 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010008 if (Err)
10009 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +000010010}
10011
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010012// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10013// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10014// information for that address. If the address is found its binding symbol
10015// name is returned. If not nullptr is returned.
10016static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10017 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010018 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010019 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010020 Error Err = Error::success();
10021 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010022 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010023 StringRef name = Entry.symbolName();
10024 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010025 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010026 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010027 if (Err)
10028 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010029 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010030 auto name = info->bindtable->lookup(ReferenceValue);
10031 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010032}
Michael Trent1854ecc2017-12-05 07:50:00 +000010033