blob: 4edff8e6ae0a8cb56786321a22edeb6069c11e47 [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
George Rimarc1964882019-01-18 11:33:26 +0000345static void printRelocationTargetName(const MachOObjectFile *O,
346 const MachO::any_relocation_info &RE,
347 raw_string_ostream &Fmt) {
348 // Target of a scattered relocation is an address. In the interest of
349 // generating pretty output, scan through the symbol table looking for a
350 // symbol that aligns with that address. If we find one, print it.
351 // Otherwise, we just print the hex address of the target.
352 if (O->isRelocationScattered(RE)) {
353 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
354
355 for (const SymbolRef &Symbol : O->symbols()) {
356 Expected<uint64_t> Addr = Symbol.getAddress();
357 if (!Addr)
358 report_error(O->getFileName(), Addr.takeError());
359 if (*Addr != Val)
360 continue;
361 Expected<StringRef> Name = Symbol.getName();
362 if (!Name)
363 report_error(O->getFileName(), Name.takeError());
364 Fmt << *Name;
365 return;
366 }
367
368 // If we couldn't find a symbol that this relocation refers to, try
369 // to find a section beginning instead.
370 for (const SectionRef &Section : ToolSectionFilter(*O)) {
371 std::error_code ec;
372
373 StringRef Name;
374 uint64_t Addr = Section.getAddress();
375 if (Addr != Val)
376 continue;
377 if ((ec = Section.getName(Name)))
378 report_error(O->getFileName(), ec);
379 Fmt << Name;
380 return;
381 }
382
383 Fmt << format("0x%x", Val);
384 return;
385 }
386
387 StringRef S;
388 bool isExtern = O->getPlainRelocationExternal(RE);
389 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
390
391 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
392 Fmt << format("0x%0" PRIx64, Val);
393 return;
394 }
395
396 if (isExtern) {
397 symbol_iterator SI = O->symbol_begin();
398 advance(SI, Val);
399 Expected<StringRef> SOrErr = SI->getName();
400 if (!SOrErr)
401 report_error(O->getFileName(), SOrErr.takeError());
402 S = *SOrErr;
403 } else {
404 section_iterator SI = O->section_begin();
405 // Adjust for the fact that sections are 1-indexed.
406 if (Val == 0) {
407 Fmt << "0 (?,?)";
408 return;
409 }
410 uint32_t I = Val - 1;
411 while (I != 0 && SI != O->section_end()) {
412 --I;
413 advance(SI, 1);
414 }
415 if (SI == O->section_end())
416 Fmt << Val << " (?,?)";
417 else
418 SI->getName(S);
419 }
420
421 Fmt << S;
422}
423
424std::error_code
425llvm::getMachORelocationValueString(const MachOObjectFile *Obj,
426 const RelocationRef &RelRef,
427 SmallVectorImpl<char> &Result) {
428 DataRefImpl Rel = RelRef.getRawDataRefImpl();
429 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
430
431 unsigned Arch = Obj->getArch();
432
433 std::string FmtBuf;
434 raw_string_ostream Fmt(FmtBuf);
435 unsigned Type = Obj->getAnyRelocationType(RE);
436 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
437
438 // Determine any addends that should be displayed with the relocation.
439 // These require decoding the relocation type, which is triple-specific.
440
441 // X86_64 has entirely custom relocation types.
442 if (Arch == Triple::x86_64) {
443 switch (Type) {
444 case MachO::X86_64_RELOC_GOT_LOAD:
445 case MachO::X86_64_RELOC_GOT: {
446 printRelocationTargetName(Obj, RE, Fmt);
447 Fmt << "@GOT";
448 if (IsPCRel)
449 Fmt << "PCREL";
450 break;
451 }
452 case MachO::X86_64_RELOC_SUBTRACTOR: {
453 DataRefImpl RelNext = Rel;
454 Obj->moveRelocationNext(RelNext);
455 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
456
457 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
458 // X86_64_RELOC_UNSIGNED.
459 // NOTE: Scattered relocations don't exist on x86_64.
460 unsigned RType = Obj->getAnyRelocationType(RENext);
461 if (RType != MachO::X86_64_RELOC_UNSIGNED)
462 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
463 "X86_64_RELOC_SUBTRACTOR.");
464
465 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
466 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
467 printRelocationTargetName(Obj, RENext, Fmt);
468 Fmt << "-";
469 printRelocationTargetName(Obj, RE, Fmt);
470 break;
471 }
472 case MachO::X86_64_RELOC_TLV:
473 printRelocationTargetName(Obj, RE, Fmt);
474 Fmt << "@TLV";
475 if (IsPCRel)
476 Fmt << "P";
477 break;
478 case MachO::X86_64_RELOC_SIGNED_1:
479 printRelocationTargetName(Obj, RE, Fmt);
480 Fmt << "-1";
481 break;
482 case MachO::X86_64_RELOC_SIGNED_2:
483 printRelocationTargetName(Obj, RE, Fmt);
484 Fmt << "-2";
485 break;
486 case MachO::X86_64_RELOC_SIGNED_4:
487 printRelocationTargetName(Obj, RE, Fmt);
488 Fmt << "-4";
489 break;
490 default:
491 printRelocationTargetName(Obj, RE, Fmt);
492 break;
493 }
494 // X86 and ARM share some relocation types in common.
495 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
496 Arch == Triple::ppc) {
497 // Generic relocation types...
498 switch (Type) {
499 case MachO::GENERIC_RELOC_PAIR: // prints no info
500 return std::error_code();
501 case MachO::GENERIC_RELOC_SECTDIFF: {
502 DataRefImpl RelNext = Rel;
503 Obj->moveRelocationNext(RelNext);
504 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
505
506 // X86 sect diff's must be followed by a relocation of type
507 // GENERIC_RELOC_PAIR.
508 unsigned RType = Obj->getAnyRelocationType(RENext);
509
510 if (RType != MachO::GENERIC_RELOC_PAIR)
511 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
512 "GENERIC_RELOC_SECTDIFF.");
513
514 printRelocationTargetName(Obj, RE, Fmt);
515 Fmt << "-";
516 printRelocationTargetName(Obj, RENext, Fmt);
517 break;
518 }
519 }
520
521 if (Arch == Triple::x86 || Arch == Triple::ppc) {
522 switch (Type) {
523 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
524 DataRefImpl RelNext = Rel;
525 Obj->moveRelocationNext(RelNext);
526 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
527
528 // X86 sect diff's must be followed by a relocation of type
529 // GENERIC_RELOC_PAIR.
530 unsigned RType = Obj->getAnyRelocationType(RENext);
531 if (RType != MachO::GENERIC_RELOC_PAIR)
532 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
533 "GENERIC_RELOC_LOCAL_SECTDIFF.");
534
535 printRelocationTargetName(Obj, RE, Fmt);
536 Fmt << "-";
537 printRelocationTargetName(Obj, RENext, Fmt);
538 break;
539 }
540 case MachO::GENERIC_RELOC_TLV: {
541 printRelocationTargetName(Obj, RE, Fmt);
542 Fmt << "@TLV";
543 if (IsPCRel)
544 Fmt << "P";
545 break;
546 }
547 default:
548 printRelocationTargetName(Obj, RE, Fmt);
549 }
550 } else { // ARM-specific relocations
551 switch (Type) {
552 case MachO::ARM_RELOC_HALF:
553 case MachO::ARM_RELOC_HALF_SECTDIFF: {
554 // Half relocations steal a bit from the length field to encode
555 // whether this is an upper16 or a lower16 relocation.
556 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
557
558 if (isUpper)
559 Fmt << ":upper16:(";
560 else
561 Fmt << ":lower16:(";
562 printRelocationTargetName(Obj, RE, Fmt);
563
564 DataRefImpl RelNext = Rel;
565 Obj->moveRelocationNext(RelNext);
566 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
567
568 // ARM half relocs must be followed by a relocation of type
569 // ARM_RELOC_PAIR.
570 unsigned RType = Obj->getAnyRelocationType(RENext);
571 if (RType != MachO::ARM_RELOC_PAIR)
572 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
573 "ARM_RELOC_HALF");
574
575 // NOTE: The half of the target virtual address is stashed in the
576 // address field of the secondary relocation, but we can't reverse
577 // engineer the constant offset from it without decoding the movw/movt
578 // instruction to find the other half in its immediate field.
579
580 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
581 // symbol/section pointer of the follow-on relocation.
582 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
583 Fmt << "-";
584 printRelocationTargetName(Obj, RENext, Fmt);
585 }
586
587 Fmt << ")";
588 break;
589 }
590 default: {
591 printRelocationTargetName(Obj, RE, Fmt);
592 }
593 }
594 }
595 } else
596 printRelocationTargetName(Obj, RE, Fmt);
597
598 Fmt.flush();
599 Result.append(FmtBuf.begin(), FmtBuf.end());
600 return std::error_code();
601}
602
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000603static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
604 uint32_t n, uint32_t count,
605 uint32_t stride, uint64_t addr) {
606 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
607 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
608 if (n > nindirectsyms)
609 outs() << " (entries start past the end of the indirect symbol "
610 "table) (reserved1 field greater than the table size)";
611 else if (n + count > nindirectsyms)
612 outs() << " (entries extends past the end of the indirect symbol "
613 "table)";
614 outs() << "\n";
615 uint32_t cputype = O->getHeader().cputype;
616 if (cputype & MachO::CPU_ARCH_ABI64)
617 outs() << "address index";
618 else
619 outs() << "address index";
620 if (verbose)
621 outs() << " name\n";
622 else
623 outs() << "\n";
624 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
625 if (cputype & MachO::CPU_ARCH_ABI64)
626 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
627 else
Tim Northover43978372016-04-26 18:29:16 +0000628 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000629 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
630 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
631 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
632 outs() << "LOCAL\n";
633 continue;
634 }
635 if (indirect_symbol ==
636 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
637 outs() << "LOCAL ABSOLUTE\n";
638 continue;
639 }
640 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
641 outs() << "ABSOLUTE\n";
642 continue;
643 }
644 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000645 if (verbose) {
646 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
647 if (indirect_symbol < Symtab.nsyms) {
648 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
649 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000650 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000651 if (!SymName)
652 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000653 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000654 } else {
655 outs() << "?";
656 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000657 }
658 outs() << "\n";
659 }
660}
661
662static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000663 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000664 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
665 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
666 for (unsigned J = 0; J < Seg.nsects; ++J) {
667 MachO::section_64 Sec = O->getSection64(Load, J);
668 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
669 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
670 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
671 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
672 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
673 section_type == MachO::S_SYMBOL_STUBS) {
674 uint32_t stride;
675 if (section_type == MachO::S_SYMBOL_STUBS)
676 stride = Sec.reserved2;
677 else
678 stride = 8;
679 if (stride == 0) {
680 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
681 << Sec.sectname << ") "
682 << "(size of stubs in reserved2 field is zero)\n";
683 continue;
684 }
685 uint32_t count = Sec.size / stride;
686 outs() << "Indirect symbols for (" << Sec.segname << ","
687 << Sec.sectname << ") " << count << " entries";
688 uint32_t n = Sec.reserved1;
689 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
690 }
691 }
692 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
693 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
694 for (unsigned J = 0; J < Seg.nsects; ++J) {
695 MachO::section Sec = O->getSection(Load, J);
696 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
697 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
698 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
699 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
700 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
701 section_type == MachO::S_SYMBOL_STUBS) {
702 uint32_t stride;
703 if (section_type == MachO::S_SYMBOL_STUBS)
704 stride = Sec.reserved2;
705 else
706 stride = 4;
707 if (stride == 0) {
708 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
709 << Sec.sectname << ") "
710 << "(size of stubs in reserved2 field is zero)\n";
711 continue;
712 }
713 uint32_t count = Sec.size / stride;
714 outs() << "Indirect symbols for (" << Sec.segname << ","
715 << Sec.sectname << ") " << count << " entries";
716 uint32_t n = Sec.reserved1;
717 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
718 }
719 }
720 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000721 }
722}
723
Michael Trenta1703b12017-12-15 17:57:40 +0000724static void PrintRType(const uint64_t cputype, const unsigned r_type) {
725 static char const *generic_r_types[] = {
726 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
727 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
728 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
729 };
730 static char const *x86_64_r_types[] = {
731 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
732 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
733 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
734 };
735 static char const *arm_r_types[] = {
736 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
737 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
738 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
739 };
740 static char const *arm64_r_types[] = {
741 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
742 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
743 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
744 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000745
Michael Trenta1703b12017-12-15 17:57:40 +0000746 if (r_type > 0xf){
747 outs() << format("%-7u", r_type) << " ";
748 return;
749 }
750 switch (cputype) {
751 case MachO::CPU_TYPE_I386:
752 outs() << generic_r_types[r_type];
753 break;
754 case MachO::CPU_TYPE_X86_64:
755 outs() << x86_64_r_types[r_type];
756 break;
757 case MachO::CPU_TYPE_ARM:
758 outs() << arm_r_types[r_type];
759 break;
760 case MachO::CPU_TYPE_ARM64:
761 outs() << arm64_r_types[r_type];
762 break;
763 default:
764 outs() << format("%-7u ", r_type);
765 }
766}
767
768static void PrintRLength(const uint64_t cputype, const unsigned r_type,
769 const unsigned r_length, const bool previous_arm_half){
770 if (cputype == MachO::CPU_TYPE_ARM &&
771 (r_type == llvm::MachO::ARM_RELOC_HALF ||
772 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
773 previous_arm_half == true)) {
774 if ((r_length & 0x1) == 0)
775 outs() << "lo/";
776 else
777 outs() << "hi/";
778 if ((r_length & 0x1) == 0)
779 outs() << "arm ";
780 else
781 outs() << "thm ";
782 } else {
783 switch (r_length) {
784 case 0:
785 outs() << "byte ";
786 break;
787 case 1:
788 outs() << "word ";
789 break;
790 case 2:
791 outs() << "long ";
792 break;
793 case 3:
794 if (cputype == MachO::CPU_TYPE_X86_64)
795 outs() << "quad ";
796 else
797 outs() << format("?(%2d) ", r_length);
798 break;
799 default:
800 outs() << format("?(%2d) ", r_length);
801 }
802 }
803}
804
805static void PrintRelocationEntries(const MachOObjectFile *O,
806 const relocation_iterator Begin,
807 const relocation_iterator End,
808 const uint64_t cputype,
809 const bool verbose) {
810 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
811 bool previous_arm_half = false;
812 bool previous_sectdiff = false;
813 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000814
Michael Trenta1703b12017-12-15 17:57:40 +0000815 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
816 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
817 const MachO::any_relocation_info RE = O->getRelocation(Rel);
818 const unsigned r_type = O->getAnyRelocationType(RE);
819 const bool r_scattered = O->isRelocationScattered(RE);
820 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
821 const unsigned r_length = O->getAnyRelocationLength(RE);
822 const unsigned r_address = O->getAnyRelocationAddress(RE);
823 const bool r_extern = (r_scattered ? false :
824 O->getPlainRelocationExternal(RE));
825 const uint32_t r_value = (r_scattered ?
826 O->getScatteredRelocationValue(RE) : 0);
827 const unsigned r_symbolnum = (r_scattered ? 0 :
828 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000829
Michael Trenta1703b12017-12-15 17:57:40 +0000830 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
831 if (verbose) {
832 // scattered: address
833 if ((cputype == MachO::CPU_TYPE_I386 &&
834 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
835 (cputype == MachO::CPU_TYPE_ARM &&
836 r_type == llvm::MachO::ARM_RELOC_PAIR))
837 outs() << " ";
838 else
839 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000840
Michael Trenta1703b12017-12-15 17:57:40 +0000841 // scattered: pcrel
842 if (r_pcrel)
843 outs() << "True ";
844 else
845 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000846
Michael Trenta1703b12017-12-15 17:57:40 +0000847 // scattered: length
848 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000849
Michael Trenta1703b12017-12-15 17:57:40 +0000850 // scattered: extern & type
851 outs() << "n/a ";
852 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000853
Michael Trenta1703b12017-12-15 17:57:40 +0000854 // scattered: scattered & value
855 outs() << format("True 0x%08x", (unsigned int)r_value);
856 if (previous_sectdiff == false) {
857 if ((cputype == MachO::CPU_TYPE_ARM &&
858 r_type == llvm::MachO::ARM_RELOC_PAIR))
859 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
860 }
861 else if (cputype == MachO::CPU_TYPE_ARM &&
862 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
863 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
864 if ((cputype == MachO::CPU_TYPE_I386 &&
865 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
866 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
867 (cputype == MachO::CPU_TYPE_ARM &&
868 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
869 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
870 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
871 previous_sectdiff = true;
872 sectdiff_r_type = r_type;
873 }
874 else {
875 previous_sectdiff = false;
876 sectdiff_r_type = 0;
877 }
878 if (cputype == MachO::CPU_TYPE_ARM &&
879 (r_type == llvm::MachO::ARM_RELOC_HALF ||
880 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
881 previous_arm_half = true;
882 else
883 previous_arm_half = false;
884 outs() << "\n";
885 }
886 else {
887 // scattered: address pcrel length extern type scattered value
888 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
889 (unsigned int)r_address, r_pcrel, r_length, r_type,
890 (unsigned int)r_value);
891 }
892 }
893 else {
894 if (verbose) {
895 // plain: address
896 if (cputype == MachO::CPU_TYPE_ARM &&
897 r_type == llvm::MachO::ARM_RELOC_PAIR)
898 outs() << " ";
899 else
900 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000901
Michael Trenta1703b12017-12-15 17:57:40 +0000902 // plain: pcrel
903 if (r_pcrel)
904 outs() << "True ";
905 else
906 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000907
Michael Trenta1703b12017-12-15 17:57:40 +0000908 // plain: length
909 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000910
Michael Trenta1703b12017-12-15 17:57:40 +0000911 if (r_extern) {
912 // plain: extern & type & scattered
913 outs() << "True ";
914 PrintRType(cputype, r_type);
915 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000916
Michael Trenta1703b12017-12-15 17:57:40 +0000917 // plain: symbolnum/value
918 if (r_symbolnum > Symtab.nsyms)
919 outs() << format("?(%d)\n", r_symbolnum);
920 else {
921 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
922 Expected<StringRef> SymNameNext = Symbol.getName();
923 const char *name = NULL;
924 if (SymNameNext)
925 name = SymNameNext->data();
926 if (name == NULL)
927 outs() << format("?(%d)\n", r_symbolnum);
928 else
929 outs() << name << "\n";
930 }
931 }
932 else {
933 // plain: extern & type & scattered
934 outs() << "False ";
935 PrintRType(cputype, r_type);
936 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000937
Michael Trenta1703b12017-12-15 17:57:40 +0000938 // plain: symbolnum/value
939 if (cputype == MachO::CPU_TYPE_ARM &&
940 r_type == llvm::MachO::ARM_RELOC_PAIR)
941 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
942 else if (cputype == MachO::CPU_TYPE_ARM64 &&
943 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
944 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
945 else {
946 outs() << format("%d ", r_symbolnum);
947 if (r_symbolnum == llvm::MachO::R_ABS)
948 outs() << "R_ABS\n";
949 else {
950 // in this case, r_symbolnum is actually a 1-based section number
951 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
952 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
953 llvm::object::DataRefImpl DRI;
954 DRI.d.a = r_symbolnum-1;
955 StringRef SegName = O->getSectionFinalSegmentName(DRI);
956 StringRef SectName;
957 if (O->getSectionName(DRI, SectName))
958 outs() << "(?,?)\n";
959 else
960 outs() << "(" << SegName << "," << SectName << ")\n";
961 }
962 else {
963 outs() << "(?,?)\n";
964 }
965 }
966 }
967 }
968 if (cputype == MachO::CPU_TYPE_ARM &&
969 (r_type == llvm::MachO::ARM_RELOC_HALF ||
970 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
971 previous_arm_half = true;
972 else
973 previous_arm_half = false;
974 }
975 else {
976 // plain: address pcrel length extern type scattered symbolnum/section
977 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
978 (unsigned int)r_address, r_pcrel, r_length, r_extern,
979 r_type, r_symbolnum);
980 }
981 }
982 }
983}
984
985static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
986 const uint64_t cputype = O->getHeader().cputype;
987 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
988 if (Dysymtab.nextrel != 0) {
989 outs() << "External relocation information " << Dysymtab.nextrel
990 << " entries";
991 outs() << "\naddress pcrel length extern type scattered "
992 "symbolnum/value\n";
993 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
994 verbose);
995 }
996 if (Dysymtab.nlocrel != 0) {
997 outs() << format("Local relocation information %u entries",
998 Dysymtab.nlocrel);
999 outs() << "\naddress pcrel length extern type scattered "
1000 "symbolnum/value\n";
1001 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1002 verbose);
1003 }
1004 for (const auto &Load : O->load_commands()) {
1005 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1006 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1007 for (unsigned J = 0; J < Seg.nsects; ++J) {
1008 const MachO::section_64 Sec = O->getSection64(Load, J);
1009 if (Sec.nreloc != 0) {
1010 DataRefImpl DRI;
1011 DRI.d.a = J;
1012 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1013 StringRef SectName;
1014 if (O->getSectionName(DRI, SectName))
1015 outs() << "Relocation information (" << SegName << ",?) "
1016 << format("%u entries", Sec.nreloc);
1017 else
1018 outs() << "Relocation information (" << SegName << ","
1019 << SectName << format(") %u entries", Sec.nreloc);
1020 outs() << "\naddress pcrel length extern type scattered "
1021 "symbolnum/value\n";
1022 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1023 O->section_rel_end(DRI), cputype, verbose);
1024 }
1025 }
1026 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1027 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1028 for (unsigned J = 0; J < Seg.nsects; ++J) {
1029 const MachO::section Sec = O->getSection(Load, J);
1030 if (Sec.nreloc != 0) {
1031 DataRefImpl DRI;
1032 DRI.d.a = J;
1033 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1034 StringRef SectName;
1035 if (O->getSectionName(DRI, SectName))
1036 outs() << "Relocation information (" << SegName << ",?) "
1037 << format("%u entries", Sec.nreloc);
1038 else
1039 outs() << "Relocation information (" << SegName << ","
1040 << SectName << format(") %u entries", Sec.nreloc);
1041 outs() << "\naddress pcrel length extern type scattered "
1042 "symbolnum/value\n";
1043 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1044 O->section_rel_end(DRI), cputype, verbose);
1045 }
1046 }
1047 }
1048 }
1049}
1050
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001051static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1052 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1053 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1054 outs() << "Data in code table (" << nentries << " entries)\n";
1055 outs() << "offset length kind\n";
1056 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1057 ++DI) {
1058 uint32_t Offset;
1059 DI->getOffset(Offset);
1060 outs() << format("0x%08" PRIx32, Offset) << " ";
1061 uint16_t Length;
1062 DI->getLength(Length);
1063 outs() << format("%6u", Length) << " ";
1064 uint16_t Kind;
1065 DI->getKind(Kind);
1066 if (verbose) {
1067 switch (Kind) {
1068 case MachO::DICE_KIND_DATA:
1069 outs() << "DATA";
1070 break;
1071 case MachO::DICE_KIND_JUMP_TABLE8:
1072 outs() << "JUMP_TABLE8";
1073 break;
1074 case MachO::DICE_KIND_JUMP_TABLE16:
1075 outs() << "JUMP_TABLE16";
1076 break;
1077 case MachO::DICE_KIND_JUMP_TABLE32:
1078 outs() << "JUMP_TABLE32";
1079 break;
1080 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1081 outs() << "ABS_JUMP_TABLE32";
1082 break;
1083 default:
1084 outs() << format("0x%04" PRIx32, Kind);
1085 break;
1086 }
1087 } else
1088 outs() << format("0x%04" PRIx32, Kind);
1089 outs() << "\n";
1090 }
1091}
1092
Kevin Enderby9a509442015-01-27 21:28:24 +00001093static void PrintLinkOptHints(MachOObjectFile *O) {
1094 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1095 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1096 uint32_t nloh = LohLC.datasize;
1097 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1098 for (uint32_t i = 0; i < nloh;) {
1099 unsigned n;
1100 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1101 i += n;
1102 outs() << " identifier " << identifier << " ";
1103 if (i >= nloh)
1104 return;
1105 switch (identifier) {
1106 case 1:
1107 outs() << "AdrpAdrp\n";
1108 break;
1109 case 2:
1110 outs() << "AdrpLdr\n";
1111 break;
1112 case 3:
1113 outs() << "AdrpAddLdr\n";
1114 break;
1115 case 4:
1116 outs() << "AdrpLdrGotLdr\n";
1117 break;
1118 case 5:
1119 outs() << "AdrpAddStr\n";
1120 break;
1121 case 6:
1122 outs() << "AdrpLdrGotStr\n";
1123 break;
1124 case 7:
1125 outs() << "AdrpAdd\n";
1126 break;
1127 case 8:
1128 outs() << "AdrpLdrGot\n";
1129 break;
1130 default:
1131 outs() << "Unknown identifier value\n";
1132 break;
1133 }
1134 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1135 i += n;
1136 outs() << " narguments " << narguments << "\n";
1137 if (i >= nloh)
1138 return;
1139
1140 for (uint32_t j = 0; j < narguments; j++) {
1141 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1142 i += n;
1143 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1144 if (i >= nloh)
1145 return;
1146 }
1147 }
1148}
1149
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001150static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001151 unsigned Index = 0;
1152 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001153 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1154 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1155 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1156 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1157 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1158 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1159 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1160 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1161 if (dl.dylib.name < dl.cmdsize) {
1162 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1163 if (JustId)
1164 outs() << p << "\n";
1165 else {
1166 outs() << "\t" << p;
1167 outs() << " (compatibility version "
1168 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1169 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1170 << (dl.dylib.compatibility_version & 0xff) << ",";
1171 outs() << " current version "
1172 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1173 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1174 << (dl.dylib.current_version & 0xff) << ")\n";
1175 }
1176 } else {
1177 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1178 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1179 outs() << "LC_ID_DYLIB ";
1180 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1181 outs() << "LC_LOAD_DYLIB ";
1182 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1183 outs() << "LC_LOAD_WEAK_DYLIB ";
1184 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1185 outs() << "LC_LAZY_LOAD_DYLIB ";
1186 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1187 outs() << "LC_REEXPORT_DYLIB ";
1188 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1189 outs() << "LC_LOAD_UPWARD_DYLIB ";
1190 else
1191 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001192 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001193 }
1194 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001195 }
1196}
1197
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001198typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1199
1200static void CreateSymbolAddressMap(MachOObjectFile *O,
1201 SymbolAddressMap *AddrMap) {
1202 // Create a map of symbol addresses to symbol names.
1203 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001204 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001205 if (!STOrErr)
1206 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001207 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001208 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1209 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00001210 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001211 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001212 if (!SymNameOrErr)
1213 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001214 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +00001215 if (!SymName.startswith(".objc"))
1216 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001217 }
1218 }
1219}
1220
1221// GuessSymbolName is passed the address of what might be a symbol and a
1222// pointer to the SymbolAddressMap. It returns the name of a symbol
1223// with that address or nullptr if no symbol is found with that address.
1224static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1225 const char *SymbolName = nullptr;
1226 // A DenseMap can't lookup up some values.
1227 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1228 StringRef name = AddrMap->lookup(value);
1229 if (!name.empty())
1230 SymbolName = name.data();
1231 }
1232 return SymbolName;
1233}
1234
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001235static void DumpCstringChar(const char c) {
1236 char p[2];
1237 p[0] = c;
1238 p[1] = '\0';
1239 outs().write_escaped(p);
1240}
1241
Kevin Enderby10ba0412015-02-04 21:38:42 +00001242static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1243 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001244 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +00001245 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001246 if (print_addresses) {
1247 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001248 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001249 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001250 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001251 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001252 for (; i < sect_size && sect[i] != '\0'; i++)
1253 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001254 if (i < sect_size && sect[i] == '\0')
1255 outs() << "\n";
1256 }
1257}
1258
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001259static void DumpLiteral4(uint32_t l, float f) {
1260 outs() << format("0x%08" PRIx32, l);
1261 if ((l & 0x7f800000) != 0x7f800000)
1262 outs() << format(" (%.16e)\n", f);
1263 else {
1264 if (l == 0x7f800000)
1265 outs() << " (+Infinity)\n";
1266 else if (l == 0xff800000)
1267 outs() << " (-Infinity)\n";
1268 else if ((l & 0x00400000) == 0x00400000)
1269 outs() << " (non-signaling Not-a-Number)\n";
1270 else
1271 outs() << " (signaling Not-a-Number)\n";
1272 }
1273}
1274
1275static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1276 uint32_t sect_size, uint64_t sect_addr,
1277 bool print_addresses) {
1278 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1279 if (print_addresses) {
1280 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001281 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001282 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001283 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001284 }
1285 float f;
1286 memcpy(&f, sect + i, sizeof(float));
1287 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1288 sys::swapByteOrder(f);
1289 uint32_t l;
1290 memcpy(&l, sect + i, sizeof(uint32_t));
1291 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1292 sys::swapByteOrder(l);
1293 DumpLiteral4(l, f);
1294 }
1295}
1296
1297static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1298 double d) {
1299 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1300 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001301 Hi = (O->isLittleEndian()) ? l1 : l0;
1302 Lo = (O->isLittleEndian()) ? l0 : l1;
1303
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001304 // Hi is the high word, so this is equivalent to if(isfinite(d))
1305 if ((Hi & 0x7ff00000) != 0x7ff00000)
1306 outs() << format(" (%.16e)\n", d);
1307 else {
1308 if (Hi == 0x7ff00000 && Lo == 0)
1309 outs() << " (+Infinity)\n";
1310 else if (Hi == 0xfff00000 && Lo == 0)
1311 outs() << " (-Infinity)\n";
1312 else if ((Hi & 0x00080000) == 0x00080000)
1313 outs() << " (non-signaling Not-a-Number)\n";
1314 else
1315 outs() << " (signaling Not-a-Number)\n";
1316 }
1317}
1318
1319static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1320 uint32_t sect_size, uint64_t sect_addr,
1321 bool print_addresses) {
1322 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1323 if (print_addresses) {
1324 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001325 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001326 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001327 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001328 }
1329 double d;
1330 memcpy(&d, sect + i, sizeof(double));
1331 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1332 sys::swapByteOrder(d);
1333 uint32_t l0, l1;
1334 memcpy(&l0, sect + i, sizeof(uint32_t));
1335 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1336 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1337 sys::swapByteOrder(l0);
1338 sys::swapByteOrder(l1);
1339 }
1340 DumpLiteral8(O, l0, l1, d);
1341 }
1342}
1343
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001344static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1345 outs() << format("0x%08" PRIx32, l0) << " ";
1346 outs() << format("0x%08" PRIx32, l1) << " ";
1347 outs() << format("0x%08" PRIx32, l2) << " ";
1348 outs() << format("0x%08" PRIx32, l3) << "\n";
1349}
1350
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001351static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1352 uint32_t sect_size, uint64_t sect_addr,
1353 bool print_addresses) {
1354 for (uint32_t i = 0; i < sect_size; i += 16) {
1355 if (print_addresses) {
1356 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001357 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001358 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001359 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001360 }
1361 uint32_t l0, l1, l2, l3;
1362 memcpy(&l0, sect + i, sizeof(uint32_t));
1363 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1364 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1365 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1366 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1367 sys::swapByteOrder(l0);
1368 sys::swapByteOrder(l1);
1369 sys::swapByteOrder(l2);
1370 sys::swapByteOrder(l3);
1371 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001372 DumpLiteral16(l0, l1, l2, l3);
1373 }
1374}
1375
1376static void DumpLiteralPointerSection(MachOObjectFile *O,
1377 const SectionRef &Section,
1378 const char *sect, uint32_t sect_size,
1379 uint64_t sect_addr,
1380 bool print_addresses) {
1381 // Collect the literal sections in this Mach-O file.
1382 std::vector<SectionRef> LiteralSections;
1383 for (const SectionRef &Section : O->sections()) {
1384 DataRefImpl Ref = Section.getRawDataRefImpl();
1385 uint32_t section_type;
1386 if (O->is64Bit()) {
1387 const MachO::section_64 Sec = O->getSection64(Ref);
1388 section_type = Sec.flags & MachO::SECTION_TYPE;
1389 } else {
1390 const MachO::section Sec = O->getSection(Ref);
1391 section_type = Sec.flags & MachO::SECTION_TYPE;
1392 }
1393 if (section_type == MachO::S_CSTRING_LITERALS ||
1394 section_type == MachO::S_4BYTE_LITERALS ||
1395 section_type == MachO::S_8BYTE_LITERALS ||
1396 section_type == MachO::S_16BYTE_LITERALS)
1397 LiteralSections.push_back(Section);
1398 }
1399
1400 // Set the size of the literal pointer.
1401 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1402
Eric Christopher572e03a2015-06-19 01:53:21 +00001403 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001404 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1405 for (const RelocationRef &Reloc : Section.relocations()) {
1406 DataRefImpl Rel;
1407 MachO::any_relocation_info RE;
1408 bool isExtern = false;
1409 Rel = Reloc.getRawDataRefImpl();
1410 RE = O->getRelocation(Rel);
1411 isExtern = O->getPlainRelocationExternal(RE);
1412 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001413 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001414 symbol_iterator RelocSym = Reloc.getSymbol();
1415 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1416 }
1417 }
1418 array_pod_sort(Relocs.begin(), Relocs.end());
1419
1420 // Dump each literal pointer.
1421 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1422 if (print_addresses) {
1423 if (O->is64Bit())
1424 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1425 else
1426 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1427 }
1428 uint64_t lp;
1429 if (O->is64Bit()) {
1430 memcpy(&lp, sect + i, sizeof(uint64_t));
1431 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1432 sys::swapByteOrder(lp);
1433 } else {
1434 uint32_t li;
1435 memcpy(&li, sect + i, sizeof(uint32_t));
1436 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1437 sys::swapByteOrder(li);
1438 lp = li;
1439 }
1440
1441 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001442 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1443 return P.first == i;
1444 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001445 if (Reloc != Relocs.end()) {
1446 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001447 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001448 if (!SymName)
1449 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001450 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001451 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001452 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001453
1454 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001455 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1456 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1457 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001458 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001459 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001460 continue;
1461 }
1462
1463 uint64_t SectAddress = Sect->getAddress();
1464 uint64_t SectSize = Sect->getSize();
1465
1466 StringRef SectName;
1467 Sect->getName(SectName);
1468 DataRefImpl Ref = Sect->getRawDataRefImpl();
1469 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1470 outs() << SegmentName << ":" << SectName << ":";
1471
1472 uint32_t section_type;
1473 if (O->is64Bit()) {
1474 const MachO::section_64 Sec = O->getSection64(Ref);
1475 section_type = Sec.flags & MachO::SECTION_TYPE;
1476 } else {
1477 const MachO::section Sec = O->getSection(Ref);
1478 section_type = Sec.flags & MachO::SECTION_TYPE;
1479 }
1480
1481 StringRef BytesStr;
1482 Sect->getContents(BytesStr);
1483 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1484
1485 switch (section_type) {
1486 case MachO::S_CSTRING_LITERALS:
1487 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1488 i++) {
1489 DumpCstringChar(Contents[i]);
1490 }
1491 outs() << "\n";
1492 break;
1493 case MachO::S_4BYTE_LITERALS:
1494 float f;
1495 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1496 uint32_t l;
1497 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1498 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1499 sys::swapByteOrder(f);
1500 sys::swapByteOrder(l);
1501 }
1502 DumpLiteral4(l, f);
1503 break;
1504 case MachO::S_8BYTE_LITERALS: {
1505 double d;
1506 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1507 uint32_t l0, l1;
1508 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1509 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1510 sizeof(uint32_t));
1511 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1512 sys::swapByteOrder(f);
1513 sys::swapByteOrder(l0);
1514 sys::swapByteOrder(l1);
1515 }
1516 DumpLiteral8(O, l0, l1, d);
1517 break;
1518 }
1519 case MachO::S_16BYTE_LITERALS: {
1520 uint32_t l0, l1, l2, l3;
1521 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1522 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1523 sizeof(uint32_t));
1524 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1525 sizeof(uint32_t));
1526 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1527 sizeof(uint32_t));
1528 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1529 sys::swapByteOrder(l0);
1530 sys::swapByteOrder(l1);
1531 sys::swapByteOrder(l2);
1532 sys::swapByteOrder(l3);
1533 }
1534 DumpLiteral16(l0, l1, l2, l3);
1535 break;
1536 }
1537 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001538 }
1539}
1540
Kevin Enderby85b7a662018-03-20 20:29:52 +00001541static void DumpInitTermPointerSection(MachOObjectFile *O,
1542 const SectionRef &Section,
1543 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001544 uint32_t sect_size, uint64_t sect_addr,
1545 SymbolAddressMap *AddrMap,
1546 bool verbose) {
1547 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001548 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001549
1550 // Collect the external relocation symbols for the pointers.
1551 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1552 for (const RelocationRef &Reloc : Section.relocations()) {
1553 DataRefImpl Rel;
1554 MachO::any_relocation_info RE;
1555 bool isExtern = false;
1556 Rel = Reloc.getRawDataRefImpl();
1557 RE = O->getRelocation(Rel);
1558 isExtern = O->getPlainRelocationExternal(RE);
1559 if (isExtern) {
1560 uint64_t RelocOffset = Reloc.getOffset();
1561 symbol_iterator RelocSym = Reloc.getSymbol();
1562 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1563 }
1564 }
1565 array_pod_sort(Relocs.begin(), Relocs.end());
1566
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001567 for (uint32_t i = 0; i < sect_size; i += stride) {
1568 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001569 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001570 if (O->is64Bit()) {
1571 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1572 uint64_t pointer_value;
1573 memcpy(&pointer_value, sect + i, stride);
1574 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1575 sys::swapByteOrder(pointer_value);
1576 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001577 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001578 } else {
1579 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1580 uint32_t pointer_value;
1581 memcpy(&pointer_value, sect + i, stride);
1582 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1583 sys::swapByteOrder(pointer_value);
1584 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001585 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001586 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001587 if (verbose) {
1588 // First look for an external relocation entry for this pointer.
1589 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1590 return P.first == i;
1591 });
1592 if (Reloc != Relocs.end()) {
1593 symbol_iterator RelocSym = Reloc->second;
1594 Expected<StringRef> SymName = RelocSym->getName();
1595 if (!SymName)
1596 report_error(O->getFileName(), SymName.takeError());
1597 outs() << " " << *SymName;
1598 } else {
1599 SymbolName = GuessSymbolName(p, AddrMap);
1600 if (SymbolName)
1601 outs() << " " << SymbolName;
1602 }
1603 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001604 outs() << "\n";
1605 }
1606}
1607
1608static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1609 uint32_t size, uint64_t addr) {
1610 uint32_t cputype = O->getHeader().cputype;
1611 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1612 uint32_t j;
1613 for (uint32_t i = 0; i < size; i += j, addr += j) {
1614 if (O->is64Bit())
1615 outs() << format("%016" PRIx64, addr) << "\t";
1616 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001617 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001618 for (j = 0; j < 16 && i + j < size; j++) {
1619 uint8_t byte_word = *(sect + i + j);
1620 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1621 }
1622 outs() << "\n";
1623 }
1624 } else {
1625 uint32_t j;
1626 for (uint32_t i = 0; i < size; i += j, addr += j) {
1627 if (O->is64Bit())
1628 outs() << format("%016" PRIx64, addr) << "\t";
1629 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001630 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001631 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1632 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001633 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001634 uint32_t long_word;
1635 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1636 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1637 sys::swapByteOrder(long_word);
1638 outs() << format("%08" PRIx32, long_word) << " ";
1639 } else {
1640 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001641 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001642 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1643 }
1644 }
1645 }
1646 outs() << "\n";
1647 }
1648 }
1649}
1650
Kevin Enderby95df54c2015-02-04 01:01:38 +00001651static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1652 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001653static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1654 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001655#ifdef HAVE_LIBXAR
1656static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1657 uint32_t size, bool verbose,
1658 bool PrintXarHeader, bool PrintXarFileHeaders,
1659 std::string XarMemberName);
1660#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001661
1662static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1663 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001664 SymbolAddressMap AddrMap;
1665 if (verbose)
1666 CreateSymbolAddressMap(O, &AddrMap);
1667
Colin LeMahieufcc32762015-07-29 19:08:10 +00001668 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1669 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001670 std::pair<StringRef, StringRef> DumpSegSectName;
1671 DumpSegSectName = DumpSection.split(',');
1672 StringRef DumpSegName, DumpSectName;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001673 if (!DumpSegSectName.second.empty()) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001674 DumpSegName = DumpSegSectName.first;
1675 DumpSectName = DumpSegSectName.second;
1676 } else {
1677 DumpSegName = "";
1678 DumpSectName = DumpSegSectName.first;
1679 }
1680 for (const SectionRef &Section : O->sections()) {
1681 StringRef SectName;
1682 Section.getName(SectName);
1683 DataRefImpl Ref = Section.getRawDataRefImpl();
1684 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1685 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1686 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001687
Kevin Enderby95df54c2015-02-04 01:01:38 +00001688 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001689 if (O->is64Bit()) {
1690 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001691 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001692
1693 } else {
1694 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001695 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001696 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001697 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001698
1699 StringRef BytesStr;
1700 Section.getContents(BytesStr);
1701 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1702 uint32_t sect_size = BytesStr.size();
1703 uint64_t sect_addr = Section.getAddress();
1704
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001705 outs() << "Contents of (" << SegName << "," << SectName
1706 << ") section\n";
1707
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001708 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001709 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1710 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1711 DisassembleMachO(Filename, O, SegName, SectName);
1712 continue;
1713 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001714 if (SegName == "__TEXT" && SectName == "__info_plist") {
1715 outs() << sect;
1716 continue;
1717 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001718 if (SegName == "__OBJC" && SectName == "__protocol") {
1719 DumpProtocolSection(O, sect, sect_size, sect_addr);
1720 continue;
1721 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001722#ifdef HAVE_LIBXAR
1723 if (SegName == "__LLVM" && SectName == "__bundle") {
1724 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1725 ArchiveHeaders, "");
1726 continue;
1727 }
1728#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001729 switch (section_type) {
1730 case MachO::S_REGULAR:
1731 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1732 break;
1733 case MachO::S_ZEROFILL:
1734 outs() << "zerofill section and has no contents in the file\n";
1735 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001736 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001737 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001738 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001739 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001740 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001741 break;
1742 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001743 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001744 break;
1745 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001746 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1747 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001748 case MachO::S_LITERAL_POINTERS:
1749 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001750 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001751 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001752 case MachO::S_MOD_INIT_FUNC_POINTERS:
1753 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001754 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1755 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001756 break;
1757 default:
1758 outs() << "Unknown section type ("
1759 << format("0x%08" PRIx32, section_type) << ")\n";
1760 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1761 break;
1762 }
1763 } else {
1764 if (section_type == MachO::S_ZEROFILL)
1765 outs() << "zerofill section and has no contents in the file\n";
1766 else
1767 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1768 }
1769 }
1770 }
1771 }
1772}
1773
Kevin Enderbycd66be52015-03-11 22:06:32 +00001774static void DumpInfoPlistSectionContents(StringRef Filename,
1775 MachOObjectFile *O) {
1776 for (const SectionRef &Section : O->sections()) {
1777 StringRef SectName;
1778 Section.getName(SectName);
1779 DataRefImpl Ref = Section.getRawDataRefImpl();
1780 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1781 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001782 if (!NoLeadingHeaders)
1783 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001784 StringRef BytesStr;
1785 Section.getContents(BytesStr);
1786 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001787 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001788 return;
1789 }
1790 }
1791}
1792
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001793// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1794// and if it is and there is a list of architecture flags is specified then
1795// check to make sure this Mach-O file is one of those architectures or all
1796// architectures were specified. If not then an error is generated and this
1797// routine returns false. Else it returns true.
1798static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001799 auto *MachO = dyn_cast<MachOObjectFile>(O);
1800
1801 if (!MachO || ArchAll || ArchFlags.empty())
1802 return true;
1803
1804 MachO::mach_header H;
1805 MachO::mach_header_64 H_64;
1806 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001807 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001808 if (MachO->is64Bit()) {
1809 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001810 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1811 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001812 } else {
1813 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001814 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1815 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001816 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001817 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001818 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001819 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001820 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001821 WithColor::error(errs(), "llvm-objdump")
1822 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001823 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001824 }
1825 return true;
1826}
1827
Kevin Enderby0fc11822015-04-01 20:57:01 +00001828static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1829
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001830// ProcessMachO() is passed a single opened Mach-O file, which may be an
1831// archive member and or in a slice of a universal file. It prints the
1832// the file name and header info and then processes it according to the
1833// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001834static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001835 StringRef ArchiveMemberName = StringRef(),
1836 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001837 // If we are doing some processing here on the Mach-O file print the header
1838 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001839 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001840 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1841 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1842 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001843 (!FilterSections.empty())) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001844 if (!NoLeadingHeaders) {
1845 outs() << Name;
1846 if (!ArchiveMemberName.empty())
1847 outs() << '(' << ArchiveMemberName << ')';
1848 if (!ArchitectureName.empty())
1849 outs() << " (architecture " << ArchitectureName << ")";
1850 outs() << ":\n";
1851 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001852 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001853 // To use the report_error() form with an ArchiveName and FileName set
1854 // these up based on what is passed for Name and ArchiveMemberName.
1855 StringRef ArchiveName;
1856 StringRef FileName;
1857 if (!ArchiveMemberName.empty()) {
1858 ArchiveName = Name;
1859 FileName = ArchiveMemberName;
1860 } else {
1861 ArchiveName = StringRef();
1862 FileName = Name;
1863 }
1864
1865 // If we need the symbol table to do the operation then check it here to
1866 // produce a good error message as to where the Mach-O file comes from in
1867 // the error message.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001868 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001869 if (Error Err = MachOOF->checkSymbolTable())
1870 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Michael Trent7e660212019-01-15 20:41:30 +00001871
1872 if (DisassembleAll) {
1873 for (const SectionRef &Section : MachOOF->sections()) {
1874 StringRef SectName;
1875 Section.getName(SectName);
1876 if (SectName.equals("__text")) {
1877 DataRefImpl Ref = Section.getRawDataRefImpl();
1878 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1879 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1880 }
1881 }
1882 }
1883 else if (Disassemble) {
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001884 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001885 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001886 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1887 else
1888 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1889 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001890 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001891 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001892 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001893 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001894 if (LinkOptHints)
1895 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001896 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001897 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001898 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001899 printSectionHeaders(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001900 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001901 printSectionContents(MachOOF);
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001902 if (!FilterSections.empty())
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001903 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001904 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001905 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001906 if (DylibsUsed)
1907 PrintDylibs(MachOOF, false);
1908 if (DylibId)
1909 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001910 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001911 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001912 if (UnwindInfo)
1913 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001914 if (PrivateHeaders) {
1915 printMachOFileHeader(MachOOF);
1916 printMachOLoadCommands(MachOOF);
1917 }
1918 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001919 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001920 if (ObjcMetaData)
1921 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001922 if (ExportsTrie)
1923 printExportsTrie(MachOOF);
1924 if (Rebase)
1925 printRebaseTable(MachOOF);
1926 if (Bind)
1927 printBindTable(MachOOF);
1928 if (LazyBind)
1929 printLazyBindTable(MachOOF);
1930 if (WeakBind)
1931 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001932
1933 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001934 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001935 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001936 DIDumpOptions DumpOpts;
1937 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001938 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001939 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001940}
1941
Kevin Enderby131d1772015-01-09 19:22:37 +00001942// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1943static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1944 outs() << " cputype (" << cputype << ")\n";
1945 outs() << " cpusubtype (" << cpusubtype << ")\n";
1946}
1947
1948// printCPUType() helps print_fat_headers by printing the cputype and
1949// pusubtype (symbolically for the one's it knows about).
1950static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1951 switch (cputype) {
1952 case MachO::CPU_TYPE_I386:
1953 switch (cpusubtype) {
1954 case MachO::CPU_SUBTYPE_I386_ALL:
1955 outs() << " cputype CPU_TYPE_I386\n";
1956 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1957 break;
1958 default:
1959 printUnknownCPUType(cputype, cpusubtype);
1960 break;
1961 }
1962 break;
1963 case MachO::CPU_TYPE_X86_64:
1964 switch (cpusubtype) {
1965 case MachO::CPU_SUBTYPE_X86_64_ALL:
1966 outs() << " cputype CPU_TYPE_X86_64\n";
1967 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1968 break;
1969 case MachO::CPU_SUBTYPE_X86_64_H:
1970 outs() << " cputype CPU_TYPE_X86_64\n";
1971 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1972 break;
1973 default:
1974 printUnknownCPUType(cputype, cpusubtype);
1975 break;
1976 }
1977 break;
1978 case MachO::CPU_TYPE_ARM:
1979 switch (cpusubtype) {
1980 case MachO::CPU_SUBTYPE_ARM_ALL:
1981 outs() << " cputype CPU_TYPE_ARM\n";
1982 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1983 break;
1984 case MachO::CPU_SUBTYPE_ARM_V4T:
1985 outs() << " cputype CPU_TYPE_ARM\n";
1986 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1987 break;
1988 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1989 outs() << " cputype CPU_TYPE_ARM\n";
1990 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1991 break;
1992 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1993 outs() << " cputype CPU_TYPE_ARM\n";
1994 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1995 break;
1996 case MachO::CPU_SUBTYPE_ARM_V6:
1997 outs() << " cputype CPU_TYPE_ARM\n";
1998 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1999 break;
2000 case MachO::CPU_SUBTYPE_ARM_V6M:
2001 outs() << " cputype CPU_TYPE_ARM\n";
2002 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2003 break;
2004 case MachO::CPU_SUBTYPE_ARM_V7:
2005 outs() << " cputype CPU_TYPE_ARM\n";
2006 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2007 break;
2008 case MachO::CPU_SUBTYPE_ARM_V7EM:
2009 outs() << " cputype CPU_TYPE_ARM\n";
2010 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2011 break;
2012 case MachO::CPU_SUBTYPE_ARM_V7K:
2013 outs() << " cputype CPU_TYPE_ARM\n";
2014 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2015 break;
2016 case MachO::CPU_SUBTYPE_ARM_V7M:
2017 outs() << " cputype CPU_TYPE_ARM\n";
2018 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2019 break;
2020 case MachO::CPU_SUBTYPE_ARM_V7S:
2021 outs() << " cputype CPU_TYPE_ARM\n";
2022 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2023 break;
2024 default:
2025 printUnknownCPUType(cputype, cpusubtype);
2026 break;
2027 }
2028 break;
2029 case MachO::CPU_TYPE_ARM64:
2030 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2031 case MachO::CPU_SUBTYPE_ARM64_ALL:
2032 outs() << " cputype CPU_TYPE_ARM64\n";
2033 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2034 break;
2035 default:
2036 printUnknownCPUType(cputype, cpusubtype);
2037 break;
2038 }
2039 break;
2040 default:
2041 printUnknownCPUType(cputype, cpusubtype);
2042 break;
2043 }
2044}
2045
2046static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2047 bool verbose) {
2048 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00002049 if (verbose) {
2050 if (UB->getMagic() == MachO::FAT_MAGIC)
2051 outs() << "fat_magic FAT_MAGIC\n";
2052 else // UB->getMagic() == MachO::FAT_MAGIC_64
2053 outs() << "fat_magic FAT_MAGIC_64\n";
2054 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00002055 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2056
2057 uint32_t nfat_arch = UB->getNumberOfObjects();
2058 StringRef Buf = UB->getData();
2059 uint64_t size = Buf.size();
2060 uint64_t big_size = sizeof(struct MachO::fat_header) +
2061 nfat_arch * sizeof(struct MachO::fat_arch);
2062 outs() << "nfat_arch " << UB->getNumberOfObjects();
2063 if (nfat_arch == 0)
2064 outs() << " (malformed, contains zero architecture types)\n";
2065 else if (big_size > size)
2066 outs() << " (malformed, architectures past end of file)\n";
2067 else
2068 outs() << "\n";
2069
2070 for (uint32_t i = 0; i < nfat_arch; ++i) {
2071 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2072 uint32_t cputype = OFA.getCPUType();
2073 uint32_t cpusubtype = OFA.getCPUSubType();
2074 outs() << "architecture ";
2075 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2076 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2077 uint32_t other_cputype = other_OFA.getCPUType();
2078 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00002079 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00002080 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00002081 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00002082 outs() << "(illegal duplicate architecture) ";
2083 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00002084 }
Kevin Enderby131d1772015-01-09 19:22:37 +00002085 }
2086 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00002087 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00002088 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2089 } else {
2090 outs() << i << "\n";
2091 outs() << " cputype " << cputype << "\n";
2092 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2093 << "\n";
2094 }
2095 if (verbose &&
2096 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2097 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2098 else
2099 outs() << " capabilities "
2100 << format("0x%" PRIx32,
2101 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2102 outs() << " offset " << OFA.getOffset();
2103 if (OFA.getOffset() > size)
2104 outs() << " (past end of file)";
2105 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2106 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2107 outs() << "\n";
2108 outs() << " size " << OFA.getSize();
2109 big_size = OFA.getOffset() + OFA.getSize();
2110 if (big_size > size)
2111 outs() << " (past end of file)";
2112 outs() << "\n";
2113 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2114 << ")\n";
2115 }
2116}
2117
Kevin Enderby6524bd82016-07-19 20:47:07 +00002118static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2119 bool verbose, bool print_offset,
2120 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00002121 if (print_offset)
2122 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002123 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2124 if (!ModeOrErr)
2125 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
2126 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002127 if (verbose) {
2128 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2129 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2130 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00002131 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2132 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2133 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2134 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2135 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2136 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2137 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2138 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2139 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00002140 } else {
2141 outs() << format("0%o ", Mode);
2142 }
2143
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002144 Expected<unsigned> UIDOrErr = C.getUID();
2145 if (!UIDOrErr)
2146 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
2147 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002148 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002149 Expected<unsigned> GIDOrErr = C.getGID();
2150 if (!GIDOrErr)
2151 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
2152 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002153 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00002154 Expected<uint64_t> Size = C.getRawSize();
2155 if (!Size)
2156 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00002157 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002158
2159 StringRef RawLastModified = C.getRawLastModified();
2160 if (verbose) {
2161 unsigned Seconds;
2162 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002163 outs() << "(date: \"" << RawLastModified
2164 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002165 else {
2166 // Since cime(3) returns a 26 character string of the form:
2167 // "Sun Sep 16 01:03:52 1973\n\0"
2168 // just print 24 characters.
2169 time_t t = Seconds;
2170 outs() << format("%.24s ", ctime(&t));
2171 }
2172 } else {
2173 outs() << RawLastModified << " ";
2174 }
2175
2176 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002177 Expected<StringRef> NameOrErr = C.getName();
2178 if (!NameOrErr) {
2179 consumeError(NameOrErr.takeError());
2180 Expected<StringRef> NameOrErr = C.getRawName();
2181 if (!NameOrErr)
2182 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
2183 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002184 outs() << RawName << "\n";
2185 } else {
2186 StringRef Name = NameOrErr.get();
2187 outs() << Name << "\n";
2188 }
2189 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002190 Expected<StringRef> NameOrErr = C.getRawName();
2191 if (!NameOrErr)
2192 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
2193 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002194 outs() << RawName << "\n";
2195 }
2196}
2197
Kevin Enderby6524bd82016-07-19 20:47:07 +00002198static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2199 bool print_offset,
2200 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002201 Error Err = Error::success();
2202 ;
Lang Hamesfc209622016-07-14 02:24:01 +00002203 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00002204 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
2205
Lang Hamesfc209622016-07-14 02:24:01 +00002206 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002207 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002208}
2209
Dave Lee3fb120f2018-08-03 00:06:38 +00002210static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002211 // Check for -arch all and verifiy the -arch flags are valid.
2212 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2213 if (ArchFlags[i] == "all") {
2214 ArchAll = true;
2215 } else {
2216 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002217 WithColor::error(errs(), "llvm-objdump")
2218 << "unknown architecture named '" + ArchFlags[i] +
2219 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002220 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002221 }
2222 }
2223 }
Dave Lee3fb120f2018-08-03 00:06:38 +00002224 return true;
2225}
2226
2227// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2228// -arch flags selecting just those slices as specified by them and also parses
2229// archive files. Then for each individual Mach-O file ProcessMachO() is
2230// called to process the file based on the command line options.
George Rimar73a27232019-01-15 09:19:18 +00002231void llvm::parseInputMachO(StringRef Filename) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002232 if (!ValidateArchFlags())
2233 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002234
2235 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002236 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002237 if (!BinaryOrErr) {
2238 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2239 report_error(Filename, std::move(E));
2240 else
2241 outs() << Filename << ": is not an object file\n";
2242 return;
2243 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002244 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00002245
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002246 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2247 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002248 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002249 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2250
Mehdi Amini41af4302016-11-11 04:28:40 +00002251 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002252 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002253 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2254 if (!ChildOrErr) {
2255 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2256 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002257 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002258 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002259 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2260 if (!checkMachOAndArchFlags(O, Filename))
2261 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002262 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002263 }
2264 }
Lang Hamesfc209622016-07-14 02:24:01 +00002265 if (Err)
2266 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002267 return;
2268 }
2269 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
George Rimar73a27232019-01-15 09:19:18 +00002270 parseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002271 return;
2272 }
2273 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2274 if (!checkMachOAndArchFlags(O, Filename))
2275 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002276 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002277 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002278 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002279 WithColor::error(errs(), "llvm-objdump")
2280 << Filename << "': "
2281 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002282 return;
2283 }
2284 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002285}
2286
George Rimar73a27232019-01-15 09:19:18 +00002287void llvm::parseInputMachO(MachOUniversalBinary *UB) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002288 if (!ValidateArchFlags())
2289 return;
2290
2291 auto Filename = UB->getFileName();
2292
2293 if (UniversalHeaders)
2294 printMachOUniversalHeaders(UB, !NonVerbose);
2295
2296 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002297 if (!ArchAll && !ArchFlags.empty()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002298 // Look for a slice in the universal binary that matches each ArchFlag.
2299 bool ArchFound;
2300 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2301 ArchFound = false;
2302 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2303 E = UB->end_objects();
2304 I != E; ++I) {
2305 if (ArchFlags[i] == I->getArchFlagName()) {
2306 ArchFound = true;
2307 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2308 I->getAsObjectFile();
2309 std::string ArchitectureName = "";
2310 if (ArchFlags.size() > 1)
2311 ArchitectureName = I->getArchFlagName();
2312 if (ObjOrErr) {
2313 ObjectFile &O = *ObjOrErr.get();
2314 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2315 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2316 } else if (auto E = isNotObjectErrorInvalidFileType(
2317 ObjOrErr.takeError())) {
2318 report_error(Filename, StringRef(), std::move(E),
2319 ArchitectureName);
2320 continue;
2321 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2322 I->getAsArchive()) {
2323 std::unique_ptr<Archive> &A = *AOrErr;
2324 outs() << "Archive : " << Filename;
2325 if (!ArchitectureName.empty())
2326 outs() << " (architecture " << ArchitectureName << ")";
2327 outs() << "\n";
2328 if (ArchiveHeaders)
2329 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2330 ArchiveMemberOffsets, ArchitectureName);
2331 Error Err = Error::success();
2332 for (auto &C : A->children(Err)) {
2333 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2334 if (!ChildOrErr) {
2335 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2336 report_error(Filename, C, std::move(E), ArchitectureName);
2337 continue;
2338 }
2339 if (MachOObjectFile *O =
2340 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2341 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2342 }
2343 if (Err)
2344 report_error(Filename, std::move(Err));
2345 } else {
2346 consumeError(AOrErr.takeError());
2347 error("Mach-O universal file: " + Filename + " for " +
2348 "architecture " + StringRef(I->getArchFlagName()) +
2349 " is not a Mach-O file or an archive file");
2350 }
2351 }
2352 }
2353 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002354 WithColor::error(errs(), "llvm-objdump")
2355 << "file: " + Filename + " does not contain "
2356 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002357 return;
2358 }
2359 }
2360 return;
2361 }
2362 // No architecture flags were specified so if this contains a slice that
2363 // matches the host architecture dump only that.
2364 if (!ArchAll) {
2365 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2366 E = UB->end_objects();
2367 I != E; ++I) {
2368 if (MachOObjectFile::getHostArch().getArchName() ==
2369 I->getArchFlagName()) {
2370 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2371 std::string ArchiveName;
2372 ArchiveName.clear();
2373 if (ObjOrErr) {
2374 ObjectFile &O = *ObjOrErr.get();
2375 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2376 ProcessMachO(Filename, MachOOF);
2377 } else if (auto E = isNotObjectErrorInvalidFileType(
2378 ObjOrErr.takeError())) {
2379 report_error(Filename, std::move(E));
Dave Lee3fb120f2018-08-03 00:06:38 +00002380 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2381 I->getAsArchive()) {
2382 std::unique_ptr<Archive> &A = *AOrErr;
2383 outs() << "Archive : " << Filename << "\n";
2384 if (ArchiveHeaders)
2385 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2386 ArchiveMemberOffsets);
2387 Error Err = Error::success();
2388 for (auto &C : A->children(Err)) {
2389 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2390 if (!ChildOrErr) {
2391 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2392 report_error(Filename, C, std::move(E));
2393 continue;
2394 }
2395 if (MachOObjectFile *O =
2396 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2397 ProcessMachO(Filename, O, O->getFileName());
2398 }
2399 if (Err)
2400 report_error(Filename, std::move(Err));
2401 } else {
2402 consumeError(AOrErr.takeError());
2403 error("Mach-O universal file: " + Filename + " for architecture " +
2404 StringRef(I->getArchFlagName()) +
2405 " is not a Mach-O file or an archive file");
2406 }
2407 return;
2408 }
2409 }
2410 }
2411 // Either all architectures have been specified or none have been specified
2412 // and this does not contain the host architecture so dump all the slices.
2413 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2414 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2415 E = UB->end_objects();
2416 I != E; ++I) {
2417 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2418 std::string ArchitectureName = "";
2419 if (moreThanOneArch)
2420 ArchitectureName = I->getArchFlagName();
2421 if (ObjOrErr) {
2422 ObjectFile &Obj = *ObjOrErr.get();
2423 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2424 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2425 } else if (auto E = isNotObjectErrorInvalidFileType(
2426 ObjOrErr.takeError())) {
2427 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002428 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2429 I->getAsArchive()) {
2430 std::unique_ptr<Archive> &A = *AOrErr;
2431 outs() << "Archive : " << Filename;
2432 if (!ArchitectureName.empty())
2433 outs() << " (architecture " << ArchitectureName << ")";
2434 outs() << "\n";
2435 if (ArchiveHeaders)
2436 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2437 ArchiveMemberOffsets, ArchitectureName);
2438 Error Err = Error::success();
2439 for (auto &C : A->children(Err)) {
2440 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2441 if (!ChildOrErr) {
2442 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2443 report_error(Filename, C, std::move(E), ArchitectureName);
2444 continue;
2445 }
2446 if (MachOObjectFile *O =
2447 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2448 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2449 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2450 ArchitectureName);
2451 }
2452 }
2453 if (Err)
2454 report_error(Filename, std::move(Err));
2455 } else {
2456 consumeError(AOrErr.takeError());
2457 error("Mach-O universal file: " + Filename + " for architecture " +
2458 StringRef(I->getArchFlagName()) +
2459 " is not a Mach-O file or an archive file");
2460 }
2461 }
2462}
2463
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002464// The block of info used by the Symbolizer call backs.
2465struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002466 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2467 std::vector<SectionRef> *Sections, bool verbose)
2468 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002469 bool verbose;
2470 MachOObjectFile *O;
2471 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002472 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002473 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002474 const char *class_name = nullptr;
2475 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002476 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002477 char *demangled_name = nullptr;
2478 uint64_t adrp_addr = 0;
2479 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002480 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002481 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002482};
2483
2484// SymbolizerGetOpInfo() is the operand information call back function.
2485// This is called to get the symbolic information for operand(s) of an
2486// instruction when it is being done. This routine does this from
2487// the relocation information, symbol table, etc. That block of information
2488// is a pointer to the struct DisassembleInfo that was passed when the
2489// disassembler context was created and passed to back to here when
2490// called back by the disassembler for instruction operands that could have
2491// relocation information. The address of the instruction containing operand is
2492// at the Pc parameter. The immediate value the operand has is passed in
2493// op_info->Value and is at Offset past the start of the instruction and has a
2494// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2495// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2496// names and addends of the symbolic expression to add for the operand. The
2497// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2498// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002499static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2500 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002501 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2502 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002503 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002504
2505 // Make sure all fields returned are zero if we don't set them.
2506 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2507 op_info->Value = value;
2508
2509 // If the TagType is not the value 1 which it code knows about or if no
2510 // verbose symbolic information is wanted then just return 0, indicating no
2511 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002512 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002513 return 0;
2514
2515 unsigned int Arch = info->O->getArch();
2516 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002517 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2518 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002519 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2520 // TODO:
2521 // Search the external relocation entries of a fully linked image
2522 // (if any) for an entry that matches this segment offset.
2523 // uint32_t seg_offset = (Pc + Offset);
2524 return 0;
2525 }
2526 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2527 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002528 uint32_t sect_addr = info->S.getAddress();
2529 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2530 bool reloc_found = false;
2531 DataRefImpl Rel;
2532 MachO::any_relocation_info RE;
2533 bool isExtern = false;
2534 SymbolRef Symbol;
2535 bool r_scattered = false;
2536 uint32_t r_value, pair_r_value, r_type;
2537 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002538 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002539 if (RelocOffset == sect_offset) {
2540 Rel = Reloc.getRawDataRefImpl();
2541 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002542 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002543 r_scattered = info->O->isRelocationScattered(RE);
2544 if (r_scattered) {
2545 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002546 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2547 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2548 DataRefImpl RelNext = Rel;
2549 info->O->moveRelocationNext(RelNext);
2550 MachO::any_relocation_info RENext;
2551 RENext = info->O->getRelocation(RelNext);
2552 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002553 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002554 else
2555 return 0;
2556 }
2557 } else {
2558 isExtern = info->O->getPlainRelocationExternal(RE);
2559 if (isExtern) {
2560 symbol_iterator RelocSym = Reloc.getSymbol();
2561 Symbol = *RelocSym;
2562 }
2563 }
2564 reloc_found = true;
2565 break;
2566 }
2567 }
2568 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002569 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002570 if (!SymName)
2571 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002572 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002573 op_info->AddSymbol.Present = 1;
2574 op_info->AddSymbol.Name = name;
2575 // For i386 extern relocation entries the value in the instruction is
2576 // the offset from the symbol, and value is already set in op_info->Value.
2577 return 1;
2578 }
2579 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2580 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002581 const char *add = GuessSymbolName(r_value, info->AddrMap);
2582 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002583 uint32_t offset = value - (r_value - pair_r_value);
2584 op_info->AddSymbol.Present = 1;
2585 if (add != nullptr)
2586 op_info->AddSymbol.Name = add;
2587 else
2588 op_info->AddSymbol.Value = r_value;
2589 op_info->SubtractSymbol.Present = 1;
2590 if (sub != nullptr)
2591 op_info->SubtractSymbol.Name = sub;
2592 else
2593 op_info->SubtractSymbol.Value = pair_r_value;
2594 op_info->Value = offset;
2595 return 1;
2596 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002597 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002598 }
2599 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002600 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2601 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002602 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2603 // relocation entries of a linked image (if any) for an entry that matches
2604 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002605 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002606 uint64_t seg_offset = Pc + Offset;
2607 bool reloc_found = false;
2608 DataRefImpl Rel;
2609 MachO::any_relocation_info RE;
2610 bool isExtern = false;
2611 SymbolRef Symbol;
2612 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2613 uint64_t RelocOffset = Reloc.getOffset();
2614 if (RelocOffset == seg_offset) {
2615 Rel = Reloc.getRawDataRefImpl();
2616 RE = info->O->getRelocation(Rel);
2617 // external relocation entries should always be external.
2618 isExtern = info->O->getPlainRelocationExternal(RE);
2619 if (isExtern) {
2620 symbol_iterator RelocSym = Reloc.getSymbol();
2621 Symbol = *RelocSym;
2622 }
2623 reloc_found = true;
2624 break;
2625 }
2626 }
2627 if (reloc_found && isExtern) {
2628 // The Value passed in will be adjusted by the Pc if the instruction
2629 // adds the Pc. But for x86_64 external relocation entries the Value
2630 // is the offset from the external symbol.
2631 if (info->O->getAnyRelocationPCRel(RE))
2632 op_info->Value -= Pc + Offset + Size;
2633 Expected<StringRef> SymName = Symbol.getName();
2634 if (!SymName)
2635 report_error(info->O->getFileName(), SymName.takeError());
2636 const char *name = SymName->data();
2637 op_info->AddSymbol.Present = 1;
2638 op_info->AddSymbol.Name = name;
2639 return 1;
2640 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002641 return 0;
2642 }
2643 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2644 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002645 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002646 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2647 bool reloc_found = false;
2648 DataRefImpl Rel;
2649 MachO::any_relocation_info RE;
2650 bool isExtern = false;
2651 SymbolRef Symbol;
2652 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002653 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002654 if (RelocOffset == sect_offset) {
2655 Rel = Reloc.getRawDataRefImpl();
2656 RE = info->O->getRelocation(Rel);
2657 // NOTE: Scattered relocations don't exist on x86_64.
2658 isExtern = info->O->getPlainRelocationExternal(RE);
2659 if (isExtern) {
2660 symbol_iterator RelocSym = Reloc.getSymbol();
2661 Symbol = *RelocSym;
2662 }
2663 reloc_found = true;
2664 break;
2665 }
2666 }
2667 if (reloc_found && isExtern) {
2668 // The Value passed in will be adjusted by the Pc if the instruction
2669 // adds the Pc. But for x86_64 external relocation entries the Value
2670 // is the offset from the external symbol.
2671 if (info->O->getAnyRelocationPCRel(RE))
2672 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002673 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002674 if (!SymName)
2675 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002676 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002677 unsigned Type = info->O->getAnyRelocationType(RE);
2678 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2679 DataRefImpl RelNext = Rel;
2680 info->O->moveRelocationNext(RelNext);
2681 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2682 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2683 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2684 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2685 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2686 op_info->SubtractSymbol.Present = 1;
2687 op_info->SubtractSymbol.Name = name;
2688 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2689 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002690 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002691 if (!SymNameNext)
2692 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002693 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002694 }
2695 }
2696 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2697 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2698 op_info->AddSymbol.Present = 1;
2699 op_info->AddSymbol.Name = name;
2700 return 1;
2701 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002702 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002703 }
2704 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002705 if (Offset != 0 || (Size != 4 && Size != 2))
2706 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002707 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2708 // TODO:
2709 // Search the external relocation entries of a fully linked image
2710 // (if any) for an entry that matches this segment offset.
2711 // uint32_t seg_offset = (Pc + Offset);
2712 return 0;
2713 }
2714 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2715 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002716 uint32_t sect_addr = info->S.getAddress();
2717 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002718 DataRefImpl Rel;
2719 MachO::any_relocation_info RE;
2720 bool isExtern = false;
2721 SymbolRef Symbol;
2722 bool r_scattered = false;
2723 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002724 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002725 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2726 uint64_t RelocOffset = Reloc.getOffset();
2727 return RelocOffset == sect_offset;
2728 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002729
2730 if (Reloc == info->S.relocations().end())
2731 return 0;
2732
2733 Rel = Reloc->getRawDataRefImpl();
2734 RE = info->O->getRelocation(Rel);
2735 r_length = info->O->getAnyRelocationLength(RE);
2736 r_scattered = info->O->isRelocationScattered(RE);
2737 if (r_scattered) {
2738 r_value = info->O->getScatteredRelocationValue(RE);
2739 r_type = info->O->getScatteredRelocationType(RE);
2740 } else {
2741 r_type = info->O->getAnyRelocationType(RE);
2742 isExtern = info->O->getPlainRelocationExternal(RE);
2743 if (isExtern) {
2744 symbol_iterator RelocSym = Reloc->getSymbol();
2745 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002746 }
2747 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002748 if (r_type == MachO::ARM_RELOC_HALF ||
2749 r_type == MachO::ARM_RELOC_SECTDIFF ||
2750 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2751 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2752 DataRefImpl RelNext = Rel;
2753 info->O->moveRelocationNext(RelNext);
2754 MachO::any_relocation_info RENext;
2755 RENext = info->O->getRelocation(RelNext);
2756 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2757 if (info->O->isRelocationScattered(RENext))
2758 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2759 }
2760
2761 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002762 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002763 if (!SymName)
2764 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002765 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002766 op_info->AddSymbol.Present = 1;
2767 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002768 switch (r_type) {
2769 case MachO::ARM_RELOC_HALF:
2770 if ((r_length & 0x1) == 1) {
2771 op_info->Value = value << 16 | other_half;
2772 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2773 } else {
2774 op_info->Value = other_half << 16 | value;
2775 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002776 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002777 break;
2778 default:
2779 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002780 }
2781 return 1;
2782 }
2783 // If we have a branch that is not an external relocation entry then
2784 // return 0 so the code in tryAddingSymbolicOperand() can use the
2785 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002786 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002787 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2788 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002789 return 0;
2790
2791 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002792 if (r_type == MachO::ARM_RELOC_HALF ||
2793 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2794 if ((r_length & 0x1) == 1)
2795 value = value << 16 | other_half;
2796 else
2797 value = other_half << 16 | value;
2798 }
2799 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2800 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2801 offset = value - r_value;
2802 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002803 }
2804
David Blaikie33dd45d02015-03-23 18:39:02 +00002805 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002806 if ((r_length & 0x1) == 1)
2807 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2808 else
2809 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002810 const char *add = GuessSymbolName(r_value, info->AddrMap);
2811 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002812 int32_t offset = value - (r_value - pair_r_value);
2813 op_info->AddSymbol.Present = 1;
2814 if (add != nullptr)
2815 op_info->AddSymbol.Name = add;
2816 else
2817 op_info->AddSymbol.Value = r_value;
2818 op_info->SubtractSymbol.Present = 1;
2819 if (sub != nullptr)
2820 op_info->SubtractSymbol.Name = sub;
2821 else
2822 op_info->SubtractSymbol.Value = pair_r_value;
2823 op_info->Value = offset;
2824 return 1;
2825 }
2826
Kevin Enderby930fdc72014-11-06 19:00:13 +00002827 op_info->AddSymbol.Present = 1;
2828 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002829 if (r_type == MachO::ARM_RELOC_HALF) {
2830 if ((r_length & 0x1) == 1)
2831 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2832 else
2833 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002834 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002835 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002836 if (add != nullptr) {
2837 op_info->AddSymbol.Name = add;
2838 return 1;
2839 }
2840 op_info->AddSymbol.Value = value;
2841 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002842 }
2843 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002844 if (Offset != 0 || Size != 4)
2845 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002846 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2847 // TODO:
2848 // Search the external relocation entries of a fully linked image
2849 // (if any) for an entry that matches this segment offset.
2850 // uint64_t seg_offset = (Pc + Offset);
2851 return 0;
2852 }
2853 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2854 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002855 uint64_t sect_addr = info->S.getAddress();
2856 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002857 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002858 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2859 uint64_t RelocOffset = Reloc.getOffset();
2860 return RelocOffset == sect_offset;
2861 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002862
David Blaikie33dd45d02015-03-23 18:39:02 +00002863 if (Reloc == info->S.relocations().end())
2864 return 0;
2865
2866 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2867 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2868 uint32_t r_type = info->O->getAnyRelocationType(RE);
2869 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2870 DataRefImpl RelNext = Rel;
2871 info->O->moveRelocationNext(RelNext);
2872 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2873 if (value == 0) {
2874 value = info->O->getPlainRelocationSymbolNum(RENext);
2875 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002876 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002877 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002878 // NOTE: Scattered relocations don't exist on arm64.
2879 if (!info->O->getPlainRelocationExternal(RE))
2880 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002881 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002882 if (!SymName)
2883 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002884 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002885 op_info->AddSymbol.Present = 1;
2886 op_info->AddSymbol.Name = name;
2887
2888 switch (r_type) {
2889 case MachO::ARM64_RELOC_PAGE21:
2890 /* @page */
2891 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2892 break;
2893 case MachO::ARM64_RELOC_PAGEOFF12:
2894 /* @pageoff */
2895 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2896 break;
2897 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2898 /* @gotpage */
2899 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2900 break;
2901 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2902 /* @gotpageoff */
2903 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2904 break;
2905 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2906 /* @tvlppage is not implemented in llvm-mc */
2907 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2908 break;
2909 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2910 /* @tvlppageoff is not implemented in llvm-mc */
2911 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2912 break;
2913 default:
2914 case MachO::ARM64_RELOC_BRANCH26:
2915 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2916 break;
2917 }
2918 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002919 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002920 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002921}
2922
Kevin Enderbybf246f52014-09-24 23:08:22 +00002923// GuessCstringPointer is passed the address of what might be a pointer to a
2924// literal string in a cstring section. If that address is in a cstring section
2925// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002926static const char *GuessCstringPointer(uint64_t ReferenceValue,
2927 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002928 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002929 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2930 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2931 for (unsigned J = 0; J < Seg.nsects; ++J) {
2932 MachO::section_64 Sec = info->O->getSection64(Load, J);
2933 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2934 if (section_type == MachO::S_CSTRING_LITERALS &&
2935 ReferenceValue >= Sec.addr &&
2936 ReferenceValue < Sec.addr + Sec.size) {
2937 uint64_t sect_offset = ReferenceValue - Sec.addr;
2938 uint64_t object_offset = Sec.offset + sect_offset;
2939 StringRef MachOContents = info->O->getData();
2940 uint64_t object_size = MachOContents.size();
2941 const char *object_addr = (const char *)MachOContents.data();
2942 if (object_offset < object_size) {
2943 const char *name = object_addr + object_offset;
2944 return name;
2945 } else {
2946 return nullptr;
2947 }
2948 }
2949 }
2950 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2951 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2952 for (unsigned J = 0; J < Seg.nsects; ++J) {
2953 MachO::section Sec = info->O->getSection(Load, J);
2954 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2955 if (section_type == MachO::S_CSTRING_LITERALS &&
2956 ReferenceValue >= Sec.addr &&
2957 ReferenceValue < Sec.addr + Sec.size) {
2958 uint64_t sect_offset = ReferenceValue - Sec.addr;
2959 uint64_t object_offset = Sec.offset + sect_offset;
2960 StringRef MachOContents = info->O->getData();
2961 uint64_t object_size = MachOContents.size();
2962 const char *object_addr = (const char *)MachOContents.data();
2963 if (object_offset < object_size) {
2964 const char *name = object_addr + object_offset;
2965 return name;
2966 } else {
2967 return nullptr;
2968 }
2969 }
2970 }
2971 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002972 }
2973 return nullptr;
2974}
2975
Kevin Enderby85974882014-09-26 22:20:44 +00002976// GuessIndirectSymbol returns the name of the indirect symbol for the
2977// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2978// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2979// symbol name being referenced by the stub or pointer.
2980static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2981 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002982 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2983 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002984 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002985 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2986 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2987 for (unsigned J = 0; J < Seg.nsects; ++J) {
2988 MachO::section_64 Sec = info->O->getSection64(Load, J);
2989 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2990 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2991 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2992 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2993 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2994 section_type == MachO::S_SYMBOL_STUBS) &&
2995 ReferenceValue >= Sec.addr &&
2996 ReferenceValue < Sec.addr + Sec.size) {
2997 uint32_t stride;
2998 if (section_type == MachO::S_SYMBOL_STUBS)
2999 stride = Sec.reserved2;
3000 else
3001 stride = 8;
3002 if (stride == 0)
3003 return nullptr;
3004 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3005 if (index < Dysymtab.nindirectsyms) {
3006 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003007 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00003008 if (indirect_symbol < Symtab.nsyms) {
3009 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3010 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003011 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003012 if (!SymName)
3013 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003014 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00003015 return name;
3016 }
3017 }
3018 }
3019 }
3020 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3021 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3022 for (unsigned J = 0; J < Seg.nsects; ++J) {
3023 MachO::section Sec = info->O->getSection(Load, J);
3024 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3025 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3026 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3027 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3028 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3029 section_type == MachO::S_SYMBOL_STUBS) &&
3030 ReferenceValue >= Sec.addr &&
3031 ReferenceValue < Sec.addr + Sec.size) {
3032 uint32_t stride;
3033 if (section_type == MachO::S_SYMBOL_STUBS)
3034 stride = Sec.reserved2;
3035 else
3036 stride = 4;
3037 if (stride == 0)
3038 return nullptr;
3039 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3040 if (index < Dysymtab.nindirectsyms) {
3041 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003042 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00003043 if (indirect_symbol < Symtab.nsyms) {
3044 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3045 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003046 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003047 if (!SymName)
3048 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003049 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00003050 return name;
3051 }
3052 }
3053 }
3054 }
3055 }
Kevin Enderby85974882014-09-26 22:20:44 +00003056 }
3057 return nullptr;
3058}
3059
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003060// method_reference() is called passing it the ReferenceName that might be
3061// a reference it to an Objective-C method call. If so then it allocates and
3062// assembles a method call string with the values last seen and saved in
3063// the DisassembleInfo's class_name and selector_name fields. This is saved
3064// into the method field of the info and any previous string is free'ed.
3065// Then the class_name field in the info is set to nullptr. The method call
3066// string is set into ReferenceName and ReferenceType is set to
3067// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3068// then both ReferenceType and ReferenceName are left unchanged.
3069static void method_reference(struct DisassembleInfo *info,
3070 uint64_t *ReferenceType,
3071 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003072 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003073 if (*ReferenceName != nullptr) {
3074 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003075 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003076 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003077 info->method = llvm::make_unique<char[]>(
3078 5 + strlen(info->class_name) + strlen(info->selector_name));
3079 char *method = info->method.get();
3080 if (method != nullptr) {
3081 strcpy(method, "+[");
3082 strcat(method, info->class_name);
3083 strcat(method, " ");
3084 strcat(method, info->selector_name);
3085 strcat(method, "]");
3086 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003087 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3088 }
3089 } else {
David Blaikie0e550682018-02-20 18:48:51 +00003090 info->method =
3091 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
3092 char *method = info->method.get();
3093 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003094 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003095 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003096 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003097 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003098 else
David Blaikie0e550682018-02-20 18:48:51 +00003099 strcpy(method, "-[r? ");
3100 strcat(method, info->selector_name);
3101 strcat(method, "]");
3102 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003103 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3104 }
3105 }
3106 info->class_name = nullptr;
3107 }
3108 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003109 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003110 info->method =
3111 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
3112 char *method = info->method.get();
3113 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003114 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003115 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003116 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003117 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003118 else
David Blaikie0e550682018-02-20 18:48:51 +00003119 strcpy(method, "-[[r? super] ");
3120 strcat(method, info->selector_name);
3121 strcat(method, "]");
3122 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003123 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3124 }
3125 info->class_name = nullptr;
3126 }
3127 }
3128 }
3129}
3130
3131// GuessPointerPointer() is passed the address of what might be a pointer to
3132// a reference to an Objective-C class, selector, message ref or cfstring.
3133// If so the value of the pointer is returned and one of the booleans are set
3134// to true. If not zero is returned and all the booleans are set to false.
3135static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3136 struct DisassembleInfo *info,
3137 bool &classref, bool &selref, bool &msgref,
3138 bool &cfstring) {
3139 classref = false;
3140 selref = false;
3141 msgref = false;
3142 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003143 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003144 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3145 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3146 for (unsigned J = 0; J < Seg.nsects; ++J) {
3147 MachO::section_64 Sec = info->O->getSection64(Load, J);
3148 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3149 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3150 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3151 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3152 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3153 ReferenceValue >= Sec.addr &&
3154 ReferenceValue < Sec.addr + Sec.size) {
3155 uint64_t sect_offset = ReferenceValue - Sec.addr;
3156 uint64_t object_offset = Sec.offset + sect_offset;
3157 StringRef MachOContents = info->O->getData();
3158 uint64_t object_size = MachOContents.size();
3159 const char *object_addr = (const char *)MachOContents.data();
3160 if (object_offset < object_size) {
3161 uint64_t pointer_value;
3162 memcpy(&pointer_value, object_addr + object_offset,
3163 sizeof(uint64_t));
3164 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3165 sys::swapByteOrder(pointer_value);
3166 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3167 selref = true;
3168 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3169 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3170 classref = true;
3171 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3172 ReferenceValue + 8 < Sec.addr + Sec.size) {
3173 msgref = true;
3174 memcpy(&pointer_value, object_addr + object_offset + 8,
3175 sizeof(uint64_t));
3176 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3177 sys::swapByteOrder(pointer_value);
3178 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3179 cfstring = true;
3180 return pointer_value;
3181 } else {
3182 return 0;
3183 }
3184 }
3185 }
3186 }
3187 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003188 }
3189 return 0;
3190}
3191
3192// get_pointer_64 returns a pointer to the bytes in the object file at the
3193// Address from a section in the Mach-O file. And indirectly returns the
3194// offset into the section, number of bytes left in the section past the offset
3195// and which section is was being referenced. If the Address is not in a
3196// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003197static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3198 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003199 DisassembleInfo *info,
3200 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003201 offset = 0;
3202 left = 0;
3203 S = SectionRef();
3204 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3205 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3206 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00003207 if (SectSize == 0)
3208 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00003209 if (objc_only) {
3210 StringRef SectName;
3211 ((*(info->Sections))[SectIdx]).getName(SectName);
3212 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3213 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3214 if (SegName != "__OBJC" && SectName != "__cstring")
3215 continue;
3216 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003217 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3218 S = (*(info->Sections))[SectIdx];
3219 offset = Address - SectAddress;
3220 left = SectSize - offset;
3221 StringRef SectContents;
3222 ((*(info->Sections))[SectIdx]).getContents(SectContents);
3223 return SectContents.data() + offset;
3224 }
3225 }
3226 return nullptr;
3227}
3228
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003229static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3230 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003231 DisassembleInfo *info,
3232 bool objc_only = false) {
3233 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003234}
3235
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003236// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3237// the symbol indirectly through n_value. Based on the relocation information
3238// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00003239// If no relocation information is found and a non-zero ReferenceValue for the
3240// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00003241static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3242 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003243 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003244 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00003245 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003246 return nullptr;
3247
3248 // See if there is an external relocation entry at the sect_offset.
3249 bool reloc_found = false;
3250 DataRefImpl Rel;
3251 MachO::any_relocation_info RE;
3252 bool isExtern = false;
3253 SymbolRef Symbol;
3254 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00003255 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003256 if (RelocOffset == sect_offset) {
3257 Rel = Reloc.getRawDataRefImpl();
3258 RE = info->O->getRelocation(Rel);
3259 if (info->O->isRelocationScattered(RE))
3260 continue;
3261 isExtern = info->O->getPlainRelocationExternal(RE);
3262 if (isExtern) {
3263 symbol_iterator RelocSym = Reloc.getSymbol();
3264 Symbol = *RelocSym;
3265 }
3266 reloc_found = true;
3267 break;
3268 }
3269 }
3270 // If there is an external relocation entry for a symbol in this section
3271 // at this section_offset then use that symbol's value for the n_value
3272 // and return its name.
3273 const char *SymbolName = nullptr;
3274 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003275 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003276 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003277 if (!NameOrError)
3278 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003279 StringRef Name = *NameOrError;
3280 if (!Name.empty()) {
3281 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003282 return SymbolName;
3283 }
3284 }
3285
3286 // TODO: For fully linked images, look through the external relocation
3287 // entries off the dynamic symtab command. For these the r_offset is from the
3288 // start of the first writeable segment in the Mach-O file. So the offset
3289 // to this section from that segment is passed to this routine by the caller,
3290 // as the database_offset. Which is the difference of the section's starting
3291 // address and the first writable segment.
3292 //
3293 // NOTE: need add passing the database_offset to this routine.
3294
Kevin Enderby0fc11822015-04-01 20:57:01 +00003295 // We did not find an external relocation entry so look up the ReferenceValue
3296 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003297 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003298
3299 return SymbolName;
3300}
3301
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003302static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3303 DisassembleInfo *info,
3304 uint32_t ReferenceValue) {
3305 uint64_t n_value64;
3306 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3307}
3308
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003309// These are structs in the Objective-C meta data and read to produce the
3310// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003311// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3312// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003313
3314// The cfstring object in a 64-bit Mach-O file.
3315struct cfstring64_t {
3316 uint64_t isa; // class64_t * (64-bit pointer)
3317 uint64_t flags; // flag bits
3318 uint64_t characters; // char * (64-bit pointer)
3319 uint64_t length; // number of non-NULL characters in above
3320};
3321
3322// The class object in a 64-bit Mach-O file.
3323struct class64_t {
3324 uint64_t isa; // class64_t * (64-bit pointer)
3325 uint64_t superclass; // class64_t * (64-bit pointer)
3326 uint64_t cache; // Cache (64-bit pointer)
3327 uint64_t vtable; // IMP * (64-bit pointer)
3328 uint64_t data; // class_ro64_t * (64-bit pointer)
3329};
3330
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003331struct class32_t {
3332 uint32_t isa; /* class32_t * (32-bit pointer) */
3333 uint32_t superclass; /* class32_t * (32-bit pointer) */
3334 uint32_t cache; /* Cache (32-bit pointer) */
3335 uint32_t vtable; /* IMP * (32-bit pointer) */
3336 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3337};
3338
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003339struct class_ro64_t {
3340 uint32_t flags;
3341 uint32_t instanceStart;
3342 uint32_t instanceSize;
3343 uint32_t reserved;
3344 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3345 uint64_t name; // const char * (64-bit pointer)
3346 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3347 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3348 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3349 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3350 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3351};
3352
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003353struct class_ro32_t {
3354 uint32_t flags;
3355 uint32_t instanceStart;
3356 uint32_t instanceSize;
3357 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3358 uint32_t name; /* const char * (32-bit pointer) */
3359 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3360 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3361 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3362 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3363 uint32_t baseProperties; /* const struct objc_property_list *
3364 (32-bit pointer) */
3365};
3366
3367/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003368#define RO_META (1 << 0)
3369#define RO_ROOT (1 << 1)
3370#define RO_HAS_CXX_STRUCTORS (1 << 2)
3371
3372struct method_list64_t {
3373 uint32_t entsize;
3374 uint32_t count;
3375 /* struct method64_t first; These structures follow inline */
3376};
3377
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003378struct method_list32_t {
3379 uint32_t entsize;
3380 uint32_t count;
3381 /* struct method32_t first; These structures follow inline */
3382};
3383
Kevin Enderby0fc11822015-04-01 20:57:01 +00003384struct method64_t {
3385 uint64_t name; /* SEL (64-bit pointer) */
3386 uint64_t types; /* const char * (64-bit pointer) */
3387 uint64_t imp; /* IMP (64-bit pointer) */
3388};
3389
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003390struct method32_t {
3391 uint32_t name; /* SEL (32-bit pointer) */
3392 uint32_t types; /* const char * (32-bit pointer) */
3393 uint32_t imp; /* IMP (32-bit pointer) */
3394};
3395
Kevin Enderby0fc11822015-04-01 20:57:01 +00003396struct protocol_list64_t {
3397 uint64_t count; /* uintptr_t (a 64-bit value) */
3398 /* struct protocol64_t * list[0]; These pointers follow inline */
3399};
3400
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003401struct protocol_list32_t {
3402 uint32_t count; /* uintptr_t (a 32-bit value) */
3403 /* struct protocol32_t * list[0]; These pointers follow inline */
3404};
3405
Kevin Enderby0fc11822015-04-01 20:57:01 +00003406struct protocol64_t {
3407 uint64_t isa; /* id * (64-bit pointer) */
3408 uint64_t name; /* const char * (64-bit pointer) */
3409 uint64_t protocols; /* struct protocol_list64_t *
3410 (64-bit pointer) */
3411 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3412 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3413 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3414 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3415 uint64_t instanceProperties; /* struct objc_property_list *
3416 (64-bit pointer) */
3417};
3418
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003419struct protocol32_t {
3420 uint32_t isa; /* id * (32-bit pointer) */
3421 uint32_t name; /* const char * (32-bit pointer) */
3422 uint32_t protocols; /* struct protocol_list_t *
3423 (32-bit pointer) */
3424 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3425 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3426 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3427 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3428 uint32_t instanceProperties; /* struct objc_property_list *
3429 (32-bit pointer) */
3430};
3431
Kevin Enderby0fc11822015-04-01 20:57:01 +00003432struct ivar_list64_t {
3433 uint32_t entsize;
3434 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003435 /* struct ivar64_t first; These structures follow inline */
3436};
3437
3438struct ivar_list32_t {
3439 uint32_t entsize;
3440 uint32_t count;
3441 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003442};
3443
3444struct ivar64_t {
3445 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3446 uint64_t name; /* const char * (64-bit pointer) */
3447 uint64_t type; /* const char * (64-bit pointer) */
3448 uint32_t alignment;
3449 uint32_t size;
3450};
3451
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003452struct ivar32_t {
3453 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3454 uint32_t name; /* const char * (32-bit pointer) */
3455 uint32_t type; /* const char * (32-bit pointer) */
3456 uint32_t alignment;
3457 uint32_t size;
3458};
3459
Kevin Enderby0fc11822015-04-01 20:57:01 +00003460struct objc_property_list64 {
3461 uint32_t entsize;
3462 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003463 /* struct objc_property64 first; These structures follow inline */
3464};
3465
3466struct objc_property_list32 {
3467 uint32_t entsize;
3468 uint32_t count;
3469 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003470};
3471
3472struct objc_property64 {
3473 uint64_t name; /* const char * (64-bit pointer) */
3474 uint64_t attributes; /* const char * (64-bit pointer) */
3475};
3476
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003477struct objc_property32 {
3478 uint32_t name; /* const char * (32-bit pointer) */
3479 uint32_t attributes; /* const char * (32-bit pointer) */
3480};
3481
Kevin Enderby0fc11822015-04-01 20:57:01 +00003482struct category64_t {
3483 uint64_t name; /* const char * (64-bit pointer) */
3484 uint64_t cls; /* struct class_t * (64-bit pointer) */
3485 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3486 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3487 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3488 uint64_t instanceProperties; /* struct objc_property_list *
3489 (64-bit pointer) */
3490};
3491
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003492struct category32_t {
3493 uint32_t name; /* const char * (32-bit pointer) */
3494 uint32_t cls; /* struct class_t * (32-bit pointer) */
3495 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3496 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3497 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3498 uint32_t instanceProperties; /* struct objc_property_list *
3499 (32-bit pointer) */
3500};
3501
Kevin Enderby0fc11822015-04-01 20:57:01 +00003502struct objc_image_info64 {
3503 uint32_t version;
3504 uint32_t flags;
3505};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003506struct objc_image_info32 {
3507 uint32_t version;
3508 uint32_t flags;
3509};
Kevin Enderby846c0002015-04-16 17:19:59 +00003510struct imageInfo_t {
3511 uint32_t version;
3512 uint32_t flags;
3513};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003514/* masks for objc_image_info.flags */
3515#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3516#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003517#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3518#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003519
3520struct message_ref64 {
3521 uint64_t imp; /* IMP (64-bit pointer) */
3522 uint64_t sel; /* SEL (64-bit pointer) */
3523};
3524
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003525struct message_ref32 {
3526 uint32_t imp; /* IMP (32-bit pointer) */
3527 uint32_t sel; /* SEL (32-bit pointer) */
3528};
3529
Kevin Enderby846c0002015-04-16 17:19:59 +00003530// Objective-C 1 (32-bit only) meta data structs.
3531
3532struct objc_module_t {
3533 uint32_t version;
3534 uint32_t size;
3535 uint32_t name; /* char * (32-bit pointer) */
3536 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3537};
3538
3539struct objc_symtab_t {
3540 uint32_t sel_ref_cnt;
3541 uint32_t refs; /* SEL * (32-bit pointer) */
3542 uint16_t cls_def_cnt;
3543 uint16_t cat_def_cnt;
3544 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3545};
3546
3547struct objc_class_t {
3548 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3549 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3550 uint32_t name; /* const char * (32-bit pointer) */
3551 int32_t version;
3552 int32_t info;
3553 int32_t instance_size;
3554 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3555 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3556 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3557 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3558};
3559
3560#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3561// class is not a metaclass
3562#define CLS_CLASS 0x1
3563// class is a metaclass
3564#define CLS_META 0x2
3565
3566struct objc_category_t {
3567 uint32_t category_name; /* char * (32-bit pointer) */
3568 uint32_t class_name; /* char * (32-bit pointer) */
3569 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3570 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3571 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3572};
3573
3574struct objc_ivar_t {
3575 uint32_t ivar_name; /* char * (32-bit pointer) */
3576 uint32_t ivar_type; /* char * (32-bit pointer) */
3577 int32_t ivar_offset;
3578};
3579
3580struct objc_ivar_list_t {
3581 int32_t ivar_count;
3582 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3583};
3584
3585struct objc_method_list_t {
3586 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3587 int32_t method_count;
3588 // struct objc_method_t method_list[1]; /* variable length structure */
3589};
3590
3591struct objc_method_t {
3592 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3593 uint32_t method_types; /* char * (32-bit pointer) */
3594 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3595 (32-bit pointer) */
3596};
3597
3598struct objc_protocol_list_t {
3599 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3600 int32_t count;
3601 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3602 // (32-bit pointer) */
3603};
3604
3605struct objc_protocol_t {
3606 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3607 uint32_t protocol_name; /* char * (32-bit pointer) */
3608 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3609 uint32_t instance_methods; /* struct objc_method_description_list *
3610 (32-bit pointer) */
3611 uint32_t class_methods; /* struct objc_method_description_list *
3612 (32-bit pointer) */
3613};
3614
3615struct objc_method_description_list_t {
3616 int32_t count;
3617 // struct objc_method_description_t list[1];
3618};
3619
3620struct objc_method_description_t {
3621 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3622 uint32_t types; /* char * (32-bit pointer) */
3623};
3624
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003625inline void swapStruct(struct cfstring64_t &cfs) {
3626 sys::swapByteOrder(cfs.isa);
3627 sys::swapByteOrder(cfs.flags);
3628 sys::swapByteOrder(cfs.characters);
3629 sys::swapByteOrder(cfs.length);
3630}
3631
3632inline void swapStruct(struct class64_t &c) {
3633 sys::swapByteOrder(c.isa);
3634 sys::swapByteOrder(c.superclass);
3635 sys::swapByteOrder(c.cache);
3636 sys::swapByteOrder(c.vtable);
3637 sys::swapByteOrder(c.data);
3638}
3639
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003640inline void swapStruct(struct class32_t &c) {
3641 sys::swapByteOrder(c.isa);
3642 sys::swapByteOrder(c.superclass);
3643 sys::swapByteOrder(c.cache);
3644 sys::swapByteOrder(c.vtable);
3645 sys::swapByteOrder(c.data);
3646}
3647
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003648inline void swapStruct(struct class_ro64_t &cro) {
3649 sys::swapByteOrder(cro.flags);
3650 sys::swapByteOrder(cro.instanceStart);
3651 sys::swapByteOrder(cro.instanceSize);
3652 sys::swapByteOrder(cro.reserved);
3653 sys::swapByteOrder(cro.ivarLayout);
3654 sys::swapByteOrder(cro.name);
3655 sys::swapByteOrder(cro.baseMethods);
3656 sys::swapByteOrder(cro.baseProtocols);
3657 sys::swapByteOrder(cro.ivars);
3658 sys::swapByteOrder(cro.weakIvarLayout);
3659 sys::swapByteOrder(cro.baseProperties);
3660}
3661
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003662inline void swapStruct(struct class_ro32_t &cro) {
3663 sys::swapByteOrder(cro.flags);
3664 sys::swapByteOrder(cro.instanceStart);
3665 sys::swapByteOrder(cro.instanceSize);
3666 sys::swapByteOrder(cro.ivarLayout);
3667 sys::swapByteOrder(cro.name);
3668 sys::swapByteOrder(cro.baseMethods);
3669 sys::swapByteOrder(cro.baseProtocols);
3670 sys::swapByteOrder(cro.ivars);
3671 sys::swapByteOrder(cro.weakIvarLayout);
3672 sys::swapByteOrder(cro.baseProperties);
3673}
3674
Kevin Enderby0fc11822015-04-01 20:57:01 +00003675inline void swapStruct(struct method_list64_t &ml) {
3676 sys::swapByteOrder(ml.entsize);
3677 sys::swapByteOrder(ml.count);
3678}
3679
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003680inline void swapStruct(struct method_list32_t &ml) {
3681 sys::swapByteOrder(ml.entsize);
3682 sys::swapByteOrder(ml.count);
3683}
3684
Kevin Enderby0fc11822015-04-01 20:57:01 +00003685inline void swapStruct(struct method64_t &m) {
3686 sys::swapByteOrder(m.name);
3687 sys::swapByteOrder(m.types);
3688 sys::swapByteOrder(m.imp);
3689}
3690
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003691inline void swapStruct(struct method32_t &m) {
3692 sys::swapByteOrder(m.name);
3693 sys::swapByteOrder(m.types);
3694 sys::swapByteOrder(m.imp);
3695}
3696
Kevin Enderby0fc11822015-04-01 20:57:01 +00003697inline void swapStruct(struct protocol_list64_t &pl) {
3698 sys::swapByteOrder(pl.count);
3699}
3700
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003701inline void swapStruct(struct protocol_list32_t &pl) {
3702 sys::swapByteOrder(pl.count);
3703}
3704
Kevin Enderby0fc11822015-04-01 20:57:01 +00003705inline void swapStruct(struct protocol64_t &p) {
3706 sys::swapByteOrder(p.isa);
3707 sys::swapByteOrder(p.name);
3708 sys::swapByteOrder(p.protocols);
3709 sys::swapByteOrder(p.instanceMethods);
3710 sys::swapByteOrder(p.classMethods);
3711 sys::swapByteOrder(p.optionalInstanceMethods);
3712 sys::swapByteOrder(p.optionalClassMethods);
3713 sys::swapByteOrder(p.instanceProperties);
3714}
3715
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003716inline void swapStruct(struct protocol32_t &p) {
3717 sys::swapByteOrder(p.isa);
3718 sys::swapByteOrder(p.name);
3719 sys::swapByteOrder(p.protocols);
3720 sys::swapByteOrder(p.instanceMethods);
3721 sys::swapByteOrder(p.classMethods);
3722 sys::swapByteOrder(p.optionalInstanceMethods);
3723 sys::swapByteOrder(p.optionalClassMethods);
3724 sys::swapByteOrder(p.instanceProperties);
3725}
3726
Kevin Enderby0fc11822015-04-01 20:57:01 +00003727inline void swapStruct(struct ivar_list64_t &il) {
3728 sys::swapByteOrder(il.entsize);
3729 sys::swapByteOrder(il.count);
3730}
3731
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003732inline void swapStruct(struct ivar_list32_t &il) {
3733 sys::swapByteOrder(il.entsize);
3734 sys::swapByteOrder(il.count);
3735}
3736
Kevin Enderby0fc11822015-04-01 20:57:01 +00003737inline void swapStruct(struct ivar64_t &i) {
3738 sys::swapByteOrder(i.offset);
3739 sys::swapByteOrder(i.name);
3740 sys::swapByteOrder(i.type);
3741 sys::swapByteOrder(i.alignment);
3742 sys::swapByteOrder(i.size);
3743}
3744
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003745inline void swapStruct(struct ivar32_t &i) {
3746 sys::swapByteOrder(i.offset);
3747 sys::swapByteOrder(i.name);
3748 sys::swapByteOrder(i.type);
3749 sys::swapByteOrder(i.alignment);
3750 sys::swapByteOrder(i.size);
3751}
3752
Kevin Enderby0fc11822015-04-01 20:57:01 +00003753inline void swapStruct(struct objc_property_list64 &pl) {
3754 sys::swapByteOrder(pl.entsize);
3755 sys::swapByteOrder(pl.count);
3756}
3757
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003758inline void swapStruct(struct objc_property_list32 &pl) {
3759 sys::swapByteOrder(pl.entsize);
3760 sys::swapByteOrder(pl.count);
3761}
3762
Kevin Enderby0fc11822015-04-01 20:57:01 +00003763inline void swapStruct(struct objc_property64 &op) {
3764 sys::swapByteOrder(op.name);
3765 sys::swapByteOrder(op.attributes);
3766}
3767
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003768inline void swapStruct(struct objc_property32 &op) {
3769 sys::swapByteOrder(op.name);
3770 sys::swapByteOrder(op.attributes);
3771}
3772
Kevin Enderby0fc11822015-04-01 20:57:01 +00003773inline void swapStruct(struct category64_t &c) {
3774 sys::swapByteOrder(c.name);
3775 sys::swapByteOrder(c.cls);
3776 sys::swapByteOrder(c.instanceMethods);
3777 sys::swapByteOrder(c.classMethods);
3778 sys::swapByteOrder(c.protocols);
3779 sys::swapByteOrder(c.instanceProperties);
3780}
3781
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003782inline void swapStruct(struct category32_t &c) {
3783 sys::swapByteOrder(c.name);
3784 sys::swapByteOrder(c.cls);
3785 sys::swapByteOrder(c.instanceMethods);
3786 sys::swapByteOrder(c.classMethods);
3787 sys::swapByteOrder(c.protocols);
3788 sys::swapByteOrder(c.instanceProperties);
3789}
3790
Kevin Enderby0fc11822015-04-01 20:57:01 +00003791inline void swapStruct(struct objc_image_info64 &o) {
3792 sys::swapByteOrder(o.version);
3793 sys::swapByteOrder(o.flags);
3794}
3795
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003796inline void swapStruct(struct objc_image_info32 &o) {
3797 sys::swapByteOrder(o.version);
3798 sys::swapByteOrder(o.flags);
3799}
3800
Kevin Enderby846c0002015-04-16 17:19:59 +00003801inline void swapStruct(struct imageInfo_t &o) {
3802 sys::swapByteOrder(o.version);
3803 sys::swapByteOrder(o.flags);
3804}
3805
Kevin Enderby0fc11822015-04-01 20:57:01 +00003806inline void swapStruct(struct message_ref64 &mr) {
3807 sys::swapByteOrder(mr.imp);
3808 sys::swapByteOrder(mr.sel);
3809}
3810
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003811inline void swapStruct(struct message_ref32 &mr) {
3812 sys::swapByteOrder(mr.imp);
3813 sys::swapByteOrder(mr.sel);
3814}
3815
Kevin Enderby846c0002015-04-16 17:19:59 +00003816inline void swapStruct(struct objc_module_t &module) {
3817 sys::swapByteOrder(module.version);
3818 sys::swapByteOrder(module.size);
3819 sys::swapByteOrder(module.name);
3820 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003821}
Kevin Enderby846c0002015-04-16 17:19:59 +00003822
3823inline void swapStruct(struct objc_symtab_t &symtab) {
3824 sys::swapByteOrder(symtab.sel_ref_cnt);
3825 sys::swapByteOrder(symtab.refs);
3826 sys::swapByteOrder(symtab.cls_def_cnt);
3827 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003828}
Kevin Enderby846c0002015-04-16 17:19:59 +00003829
3830inline void swapStruct(struct objc_class_t &objc_class) {
3831 sys::swapByteOrder(objc_class.isa);
3832 sys::swapByteOrder(objc_class.super_class);
3833 sys::swapByteOrder(objc_class.name);
3834 sys::swapByteOrder(objc_class.version);
3835 sys::swapByteOrder(objc_class.info);
3836 sys::swapByteOrder(objc_class.instance_size);
3837 sys::swapByteOrder(objc_class.ivars);
3838 sys::swapByteOrder(objc_class.methodLists);
3839 sys::swapByteOrder(objc_class.cache);
3840 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003841}
Kevin Enderby846c0002015-04-16 17:19:59 +00003842
3843inline void swapStruct(struct objc_category_t &objc_category) {
3844 sys::swapByteOrder(objc_category.category_name);
3845 sys::swapByteOrder(objc_category.class_name);
3846 sys::swapByteOrder(objc_category.instance_methods);
3847 sys::swapByteOrder(objc_category.class_methods);
3848 sys::swapByteOrder(objc_category.protocols);
3849}
3850
3851inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3852 sys::swapByteOrder(objc_ivar_list.ivar_count);
3853}
3854
3855inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3856 sys::swapByteOrder(objc_ivar.ivar_name);
3857 sys::swapByteOrder(objc_ivar.ivar_type);
3858 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003859}
Kevin Enderby846c0002015-04-16 17:19:59 +00003860
3861inline void swapStruct(struct objc_method_list_t &method_list) {
3862 sys::swapByteOrder(method_list.obsolete);
3863 sys::swapByteOrder(method_list.method_count);
3864}
3865
3866inline void swapStruct(struct objc_method_t &method) {
3867 sys::swapByteOrder(method.method_name);
3868 sys::swapByteOrder(method.method_types);
3869 sys::swapByteOrder(method.method_imp);
3870}
3871
3872inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3873 sys::swapByteOrder(protocol_list.next);
3874 sys::swapByteOrder(protocol_list.count);
3875}
3876
3877inline void swapStruct(struct objc_protocol_t &protocol) {
3878 sys::swapByteOrder(protocol.isa);
3879 sys::swapByteOrder(protocol.protocol_name);
3880 sys::swapByteOrder(protocol.protocol_list);
3881 sys::swapByteOrder(protocol.instance_methods);
3882 sys::swapByteOrder(protocol.class_methods);
3883}
3884
3885inline void swapStruct(struct objc_method_description_list_t &mdl) {
3886 sys::swapByteOrder(mdl.count);
3887}
3888
3889inline void swapStruct(struct objc_method_description_t &md) {
3890 sys::swapByteOrder(md.name);
3891 sys::swapByteOrder(md.types);
3892}
3893
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003894static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3895 struct DisassembleInfo *info);
3896
3897// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3898// to an Objective-C class and returns the class name. It is also passed the
3899// address of the pointer, so when the pointer is zero as it can be in an .o
3900// file, that is used to look for an external relocation entry with a symbol
3901// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003902static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3903 uint64_t ReferenceValue,
3904 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003905 const char *r;
3906 uint32_t offset, left;
3907 SectionRef S;
3908
3909 // The pointer_value can be 0 in an object file and have a relocation
3910 // entry for the class symbol at the ReferenceValue (the address of the
3911 // pointer).
3912 if (pointer_value == 0) {
3913 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3914 if (r == nullptr || left < sizeof(uint64_t))
3915 return nullptr;
3916 uint64_t n_value;
3917 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3918 if (symbol_name == nullptr)
3919 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003920 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003921 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3922 return class_name + 2;
3923 else
3924 return nullptr;
3925 }
3926
3927 // The case were the pointer_value is non-zero and points to a class defined
3928 // in this Mach-O file.
3929 r = get_pointer_64(pointer_value, offset, left, S, info);
3930 if (r == nullptr || left < sizeof(struct class64_t))
3931 return nullptr;
3932 struct class64_t c;
3933 memcpy(&c, r, sizeof(struct class64_t));
3934 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3935 swapStruct(c);
3936 if (c.data == 0)
3937 return nullptr;
3938 r = get_pointer_64(c.data, offset, left, S, info);
3939 if (r == nullptr || left < sizeof(struct class_ro64_t))
3940 return nullptr;
3941 struct class_ro64_t cro;
3942 memcpy(&cro, r, sizeof(struct class_ro64_t));
3943 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3944 swapStruct(cro);
3945 if (cro.name == 0)
3946 return nullptr;
3947 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3948 return name;
3949}
3950
3951// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3952// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003953static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3954 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003955 const char *r, *name;
3956 uint32_t offset, left;
3957 SectionRef S;
3958 struct cfstring64_t cfs;
3959 uint64_t cfs_characters;
3960
3961 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3962 if (r == nullptr || left < sizeof(struct cfstring64_t))
3963 return nullptr;
3964 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3965 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3966 swapStruct(cfs);
3967 if (cfs.characters == 0) {
3968 uint64_t n_value;
3969 const char *symbol_name = get_symbol_64(
3970 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3971 if (symbol_name == nullptr)
3972 return nullptr;
3973 cfs_characters = n_value;
3974 } else
3975 cfs_characters = cfs.characters;
3976 name = get_pointer_64(cfs_characters, offset, left, S, info);
3977
3978 return name;
3979}
3980
3981// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3982// of a pointer to an Objective-C selector reference when the pointer value is
3983// zero as in a .o file and is likely to have a external relocation entry with
3984// who's symbol's n_value is the real pointer to the selector name. If that is
3985// the case the real pointer to the selector name is returned else 0 is
3986// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003987static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3988 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003989 uint32_t offset, left;
3990 SectionRef S;
3991
3992 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3993 if (r == nullptr || left < sizeof(uint64_t))
3994 return 0;
3995 uint64_t n_value;
3996 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3997 if (symbol_name == nullptr)
3998 return 0;
3999 return n_value;
4000}
4001
Kevin Enderby0fc11822015-04-01 20:57:01 +00004002static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4003 const char *sectname) {
4004 for (const SectionRef &Section : O->sections()) {
4005 StringRef SectName;
4006 Section.getName(SectName);
4007 DataRefImpl Ref = Section.getRawDataRefImpl();
4008 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4009 if (SegName == segname && SectName == sectname)
4010 return Section;
4011 }
4012 return SectionRef();
4013}
4014
4015static void
4016walk_pointer_list_64(const char *listname, const SectionRef S,
4017 MachOObjectFile *O, struct DisassembleInfo *info,
4018 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4019 if (S == SectionRef())
4020 return;
4021
4022 StringRef SectName;
4023 S.getName(SectName);
4024 DataRefImpl Ref = S.getRawDataRefImpl();
4025 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4026 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4027
4028 StringRef BytesStr;
4029 S.getContents(BytesStr);
4030 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4031
4032 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4033 uint32_t left = S.getSize() - i;
4034 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4035 uint64_t p = 0;
4036 memcpy(&p, Contents + i, size);
4037 if (i + sizeof(uint64_t) > S.getSize())
4038 outs() << listname << " list pointer extends past end of (" << SegName
4039 << "," << SectName << ") section\n";
4040 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4041
4042 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4043 sys::swapByteOrder(p);
4044
4045 uint64_t n_value = 0;
4046 const char *name = get_symbol_64(i, S, info, n_value, p);
4047 if (name == nullptr)
4048 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4049
4050 if (n_value != 0) {
4051 outs() << format("0x%" PRIx64, n_value);
4052 if (p != 0)
4053 outs() << " + " << format("0x%" PRIx64, p);
4054 } else
4055 outs() << format("0x%" PRIx64, p);
4056 if (name != nullptr)
4057 outs() << " " << name;
4058 outs() << "\n";
4059
4060 p += n_value;
4061 if (func)
4062 func(p, info);
4063 }
4064}
4065
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004066static void
4067walk_pointer_list_32(const char *listname, const SectionRef S,
4068 MachOObjectFile *O, struct DisassembleInfo *info,
4069 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4070 if (S == SectionRef())
4071 return;
4072
4073 StringRef SectName;
4074 S.getName(SectName);
4075 DataRefImpl Ref = S.getRawDataRefImpl();
4076 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4077 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4078
4079 StringRef BytesStr;
4080 S.getContents(BytesStr);
4081 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4082
4083 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4084 uint32_t left = S.getSize() - i;
4085 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4086 uint32_t p = 0;
4087 memcpy(&p, Contents + i, size);
4088 if (i + sizeof(uint32_t) > S.getSize())
4089 outs() << listname << " list pointer extends past end of (" << SegName
4090 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00004091 uint32_t Address = S.getAddress() + i;
4092 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004093
4094 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4095 sys::swapByteOrder(p);
4096 outs() << format("0x%" PRIx32, p);
4097
4098 const char *name = get_symbol_32(i, S, info, p);
4099 if (name != nullptr)
4100 outs() << " " << name;
4101 outs() << "\n";
4102
4103 if (func)
4104 func(p, info);
4105 }
4106}
4107
4108static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004109 if (layout_map == nullptr)
4110 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004111 outs() << " layout map: ";
4112 do {
4113 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4114 left--;
4115 layout_map++;
4116 } while (*layout_map != '\0' && left != 0);
4117 outs() << "\n";
4118}
4119
Kevin Enderby0fc11822015-04-01 20:57:01 +00004120static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4121 uint32_t offset, left;
4122 SectionRef S;
4123 const char *layout_map;
4124
4125 if (p == 0)
4126 return;
4127 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004128 print_layout_map(layout_map, left);
4129}
4130
4131static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4132 uint32_t offset, left;
4133 SectionRef S;
4134 const char *layout_map;
4135
4136 if (p == 0)
4137 return;
4138 layout_map = get_pointer_32(p, offset, left, S, info);
4139 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004140}
4141
4142static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4143 const char *indent) {
4144 struct method_list64_t ml;
4145 struct method64_t m;
4146 const char *r;
4147 uint32_t offset, xoffset, left, i;
4148 SectionRef S, xS;
4149 const char *name, *sym_name;
4150 uint64_t n_value;
4151
4152 r = get_pointer_64(p, offset, left, S, info);
4153 if (r == nullptr)
4154 return;
4155 memset(&ml, '\0', sizeof(struct method_list64_t));
4156 if (left < sizeof(struct method_list64_t)) {
4157 memcpy(&ml, r, left);
4158 outs() << " (method_list_t entends past the end of the section)\n";
4159 } else
4160 memcpy(&ml, r, sizeof(struct method_list64_t));
4161 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4162 swapStruct(ml);
4163 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4164 outs() << indent << "\t\t count " << ml.count << "\n";
4165
4166 p += sizeof(struct method_list64_t);
4167 offset += sizeof(struct method_list64_t);
4168 for (i = 0; i < ml.count; i++) {
4169 r = get_pointer_64(p, offset, left, S, info);
4170 if (r == nullptr)
4171 return;
4172 memset(&m, '\0', sizeof(struct method64_t));
4173 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004174 memcpy(&m, r, left);
4175 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00004176 } else
4177 memcpy(&m, r, sizeof(struct method64_t));
4178 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4179 swapStruct(m);
4180
4181 outs() << indent << "\t\t name ";
4182 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4183 info, n_value, m.name);
4184 if (n_value != 0) {
4185 if (info->verbose && sym_name != nullptr)
4186 outs() << sym_name;
4187 else
4188 outs() << format("0x%" PRIx64, n_value);
4189 if (m.name != 0)
4190 outs() << " + " << format("0x%" PRIx64, m.name);
4191 } else
4192 outs() << format("0x%" PRIx64, m.name);
4193 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4194 if (name != nullptr)
4195 outs() << format(" %.*s", left, name);
4196 outs() << "\n";
4197
4198 outs() << indent << "\t\t types ";
4199 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4200 info, n_value, m.types);
4201 if (n_value != 0) {
4202 if (info->verbose && sym_name != nullptr)
4203 outs() << sym_name;
4204 else
4205 outs() << format("0x%" PRIx64, n_value);
4206 if (m.types != 0)
4207 outs() << " + " << format("0x%" PRIx64, m.types);
4208 } else
4209 outs() << format("0x%" PRIx64, m.types);
4210 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4211 if (name != nullptr)
4212 outs() << format(" %.*s", left, name);
4213 outs() << "\n";
4214
4215 outs() << indent << "\t\t imp ";
4216 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4217 n_value, m.imp);
4218 if (info->verbose && name == nullptr) {
4219 if (n_value != 0) {
4220 outs() << format("0x%" PRIx64, n_value) << " ";
4221 if (m.imp != 0)
4222 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4223 } else
4224 outs() << format("0x%" PRIx64, m.imp) << " ";
4225 }
4226 if (name != nullptr)
4227 outs() << name;
4228 outs() << "\n";
4229
4230 p += sizeof(struct method64_t);
4231 offset += sizeof(struct method64_t);
4232 }
4233}
4234
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004235static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4236 const char *indent) {
4237 struct method_list32_t ml;
4238 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00004239 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004240 uint32_t offset, xoffset, left, i;
4241 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004242
4243 r = get_pointer_32(p, offset, left, S, info);
4244 if (r == nullptr)
4245 return;
4246 memset(&ml, '\0', sizeof(struct method_list32_t));
4247 if (left < sizeof(struct method_list32_t)) {
4248 memcpy(&ml, r, left);
4249 outs() << " (method_list_t entends past the end of the section)\n";
4250 } else
4251 memcpy(&ml, r, sizeof(struct method_list32_t));
4252 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4253 swapStruct(ml);
4254 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4255 outs() << indent << "\t\t count " << ml.count << "\n";
4256
4257 p += sizeof(struct method_list32_t);
4258 offset += sizeof(struct method_list32_t);
4259 for (i = 0; i < ml.count; i++) {
4260 r = get_pointer_32(p, offset, left, S, info);
4261 if (r == nullptr)
4262 return;
4263 memset(&m, '\0', sizeof(struct method32_t));
4264 if (left < sizeof(struct method32_t)) {
4265 memcpy(&ml, r, left);
4266 outs() << indent << " (method_t entends past the end of the section)\n";
4267 } else
4268 memcpy(&m, r, sizeof(struct method32_t));
4269 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4270 swapStruct(m);
4271
4272 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4273 name = get_pointer_32(m.name, xoffset, left, xS, info);
4274 if (name != nullptr)
4275 outs() << format(" %.*s", left, name);
4276 outs() << "\n";
4277
4278 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4279 name = get_pointer_32(m.types, xoffset, left, xS, info);
4280 if (name != nullptr)
4281 outs() << format(" %.*s", left, name);
4282 outs() << "\n";
4283
4284 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4285 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4286 m.imp);
4287 if (name != nullptr)
4288 outs() << " " << name;
4289 outs() << "\n";
4290
4291 p += sizeof(struct method32_t);
4292 offset += sizeof(struct method32_t);
4293 }
4294}
4295
Kevin Enderby846c0002015-04-16 17:19:59 +00004296static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4297 uint32_t offset, left, xleft;
4298 SectionRef S;
4299 struct objc_method_list_t method_list;
4300 struct objc_method_t method;
4301 const char *r, *methods, *name, *SymbolName;
4302 int32_t i;
4303
4304 r = get_pointer_32(p, offset, left, S, info, true);
4305 if (r == nullptr)
4306 return true;
4307
4308 outs() << "\n";
4309 if (left > sizeof(struct objc_method_list_t)) {
4310 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4311 } else {
4312 outs() << "\t\t objc_method_list extends past end of the section\n";
4313 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4314 memcpy(&method_list, r, left);
4315 }
4316 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4317 swapStruct(method_list);
4318
4319 outs() << "\t\t obsolete "
4320 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4321 outs() << "\t\t method_count " << method_list.method_count << "\n";
4322
4323 methods = r + sizeof(struct objc_method_list_t);
4324 for (i = 0; i < method_list.method_count; i++) {
4325 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4326 outs() << "\t\t remaining method's extend past the of the section\n";
4327 break;
4328 }
4329 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4330 sizeof(struct objc_method_t));
4331 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4332 swapStruct(method);
4333
4334 outs() << "\t\t method_name "
4335 << format("0x%08" PRIx32, method.method_name);
4336 if (info->verbose) {
4337 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4338 if (name != nullptr)
4339 outs() << format(" %.*s", xleft, name);
4340 else
4341 outs() << " (not in an __OBJC section)";
4342 }
4343 outs() << "\n";
4344
4345 outs() << "\t\t method_types "
4346 << format("0x%08" PRIx32, method.method_types);
4347 if (info->verbose) {
4348 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4349 if (name != nullptr)
4350 outs() << format(" %.*s", xleft, name);
4351 else
4352 outs() << " (not in an __OBJC section)";
4353 }
4354 outs() << "\n";
4355
4356 outs() << "\t\t method_imp "
4357 << format("0x%08" PRIx32, method.method_imp) << " ";
4358 if (info->verbose) {
4359 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4360 if (SymbolName != nullptr)
4361 outs() << SymbolName;
4362 }
4363 outs() << "\n";
4364 }
4365 return false;
4366}
4367
Kevin Enderby0fc11822015-04-01 20:57:01 +00004368static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4369 struct protocol_list64_t pl;
4370 uint64_t q, n_value;
4371 struct protocol64_t pc;
4372 const char *r;
4373 uint32_t offset, xoffset, left, i;
4374 SectionRef S, xS;
4375 const char *name, *sym_name;
4376
4377 r = get_pointer_64(p, offset, left, S, info);
4378 if (r == nullptr)
4379 return;
4380 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4381 if (left < sizeof(struct protocol_list64_t)) {
4382 memcpy(&pl, r, left);
4383 outs() << " (protocol_list_t entends past the end of the section)\n";
4384 } else
4385 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4386 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4387 swapStruct(pl);
4388 outs() << " count " << pl.count << "\n";
4389
4390 p += sizeof(struct protocol_list64_t);
4391 offset += sizeof(struct protocol_list64_t);
4392 for (i = 0; i < pl.count; i++) {
4393 r = get_pointer_64(p, offset, left, S, info);
4394 if (r == nullptr)
4395 return;
4396 q = 0;
4397 if (left < sizeof(uint64_t)) {
4398 memcpy(&q, r, left);
4399 outs() << " (protocol_t * entends past the end of the section)\n";
4400 } else
4401 memcpy(&q, r, sizeof(uint64_t));
4402 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4403 sys::swapByteOrder(q);
4404
4405 outs() << "\t\t list[" << i << "] ";
4406 sym_name = get_symbol_64(offset, S, info, n_value, q);
4407 if (n_value != 0) {
4408 if (info->verbose && sym_name != nullptr)
4409 outs() << sym_name;
4410 else
4411 outs() << format("0x%" PRIx64, n_value);
4412 if (q != 0)
4413 outs() << " + " << format("0x%" PRIx64, q);
4414 } else
4415 outs() << format("0x%" PRIx64, q);
4416 outs() << " (struct protocol_t *)\n";
4417
4418 r = get_pointer_64(q + n_value, offset, left, S, info);
4419 if (r == nullptr)
4420 return;
4421 memset(&pc, '\0', sizeof(struct protocol64_t));
4422 if (left < sizeof(struct protocol64_t)) {
4423 memcpy(&pc, r, left);
4424 outs() << " (protocol_t entends past the end of the section)\n";
4425 } else
4426 memcpy(&pc, r, sizeof(struct protocol64_t));
4427 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4428 swapStruct(pc);
4429
4430 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4431
4432 outs() << "\t\t\t name ";
4433 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4434 info, n_value, pc.name);
4435 if (n_value != 0) {
4436 if (info->verbose && sym_name != nullptr)
4437 outs() << sym_name;
4438 else
4439 outs() << format("0x%" PRIx64, n_value);
4440 if (pc.name != 0)
4441 outs() << " + " << format("0x%" PRIx64, pc.name);
4442 } else
4443 outs() << format("0x%" PRIx64, pc.name);
4444 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4445 if (name != nullptr)
4446 outs() << format(" %.*s", left, name);
4447 outs() << "\n";
4448
4449 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4450
4451 outs() << "\t\t instanceMethods ";
4452 sym_name =
4453 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4454 S, info, n_value, pc.instanceMethods);
4455 if (n_value != 0) {
4456 if (info->verbose && sym_name != nullptr)
4457 outs() << sym_name;
4458 else
4459 outs() << format("0x%" PRIx64, n_value);
4460 if (pc.instanceMethods != 0)
4461 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4462 } else
4463 outs() << format("0x%" PRIx64, pc.instanceMethods);
4464 outs() << " (struct method_list_t *)\n";
4465 if (pc.instanceMethods + n_value != 0)
4466 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4467
4468 outs() << "\t\t classMethods ";
4469 sym_name =
4470 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4471 info, n_value, pc.classMethods);
4472 if (n_value != 0) {
4473 if (info->verbose && sym_name != nullptr)
4474 outs() << sym_name;
4475 else
4476 outs() << format("0x%" PRIx64, n_value);
4477 if (pc.classMethods != 0)
4478 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4479 } else
4480 outs() << format("0x%" PRIx64, pc.classMethods);
4481 outs() << " (struct method_list_t *)\n";
4482 if (pc.classMethods + n_value != 0)
4483 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4484
4485 outs() << "\t optionalInstanceMethods "
4486 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4487 outs() << "\t optionalClassMethods "
4488 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4489 outs() << "\t instanceProperties "
4490 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4491
4492 p += sizeof(uint64_t);
4493 offset += sizeof(uint64_t);
4494 }
4495}
4496
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004497static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4498 struct protocol_list32_t pl;
4499 uint32_t q;
4500 struct protocol32_t pc;
4501 const char *r;
4502 uint32_t offset, xoffset, left, i;
4503 SectionRef S, xS;
4504 const char *name;
4505
4506 r = get_pointer_32(p, offset, left, S, info);
4507 if (r == nullptr)
4508 return;
4509 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4510 if (left < sizeof(struct protocol_list32_t)) {
4511 memcpy(&pl, r, left);
4512 outs() << " (protocol_list_t entends past the end of the section)\n";
4513 } else
4514 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4515 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4516 swapStruct(pl);
4517 outs() << " count " << pl.count << "\n";
4518
4519 p += sizeof(struct protocol_list32_t);
4520 offset += sizeof(struct protocol_list32_t);
4521 for (i = 0; i < pl.count; i++) {
4522 r = get_pointer_32(p, offset, left, S, info);
4523 if (r == nullptr)
4524 return;
4525 q = 0;
4526 if (left < sizeof(uint32_t)) {
4527 memcpy(&q, r, left);
4528 outs() << " (protocol_t * entends past the end of the section)\n";
4529 } else
4530 memcpy(&q, r, sizeof(uint32_t));
4531 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4532 sys::swapByteOrder(q);
4533 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4534 << " (struct protocol_t *)\n";
4535 r = get_pointer_32(q, offset, left, S, info);
4536 if (r == nullptr)
4537 return;
4538 memset(&pc, '\0', sizeof(struct protocol32_t));
4539 if (left < sizeof(struct protocol32_t)) {
4540 memcpy(&pc, r, left);
4541 outs() << " (protocol_t entends past the end of the section)\n";
4542 } else
4543 memcpy(&pc, r, sizeof(struct protocol32_t));
4544 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4545 swapStruct(pc);
4546 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4547 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4548 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4549 if (name != nullptr)
4550 outs() << format(" %.*s", left, name);
4551 outs() << "\n";
4552 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4553 outs() << "\t\t instanceMethods "
4554 << format("0x%" PRIx32, pc.instanceMethods)
4555 << " (struct method_list_t *)\n";
4556 if (pc.instanceMethods != 0)
4557 print_method_list32_t(pc.instanceMethods, info, "\t");
4558 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4559 << " (struct method_list_t *)\n";
4560 if (pc.classMethods != 0)
4561 print_method_list32_t(pc.classMethods, info, "\t");
4562 outs() << "\t optionalInstanceMethods "
4563 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4564 outs() << "\t optionalClassMethods "
4565 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4566 outs() << "\t instanceProperties "
4567 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4568 p += sizeof(uint32_t);
4569 offset += sizeof(uint32_t);
4570 }
4571}
4572
Kevin Enderby846c0002015-04-16 17:19:59 +00004573static void print_indent(uint32_t indent) {
4574 for (uint32_t i = 0; i < indent;) {
4575 if (indent - i >= 8) {
4576 outs() << "\t";
4577 i += 8;
4578 } else {
4579 for (uint32_t j = i; j < indent; j++)
4580 outs() << " ";
4581 return;
4582 }
4583 }
4584}
4585
4586static bool print_method_description_list(uint32_t p, uint32_t indent,
4587 struct DisassembleInfo *info) {
4588 uint32_t offset, left, xleft;
4589 SectionRef S;
4590 struct objc_method_description_list_t mdl;
4591 struct objc_method_description_t md;
4592 const char *r, *list, *name;
4593 int32_t i;
4594
4595 r = get_pointer_32(p, offset, left, S, info, true);
4596 if (r == nullptr)
4597 return true;
4598
4599 outs() << "\n";
4600 if (left > sizeof(struct objc_method_description_list_t)) {
4601 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4602 } else {
4603 print_indent(indent);
4604 outs() << " objc_method_description_list extends past end of the section\n";
4605 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4606 memcpy(&mdl, r, left);
4607 }
4608 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4609 swapStruct(mdl);
4610
4611 print_indent(indent);
4612 outs() << " count " << mdl.count << "\n";
4613
4614 list = r + sizeof(struct objc_method_description_list_t);
4615 for (i = 0; i < mdl.count; i++) {
4616 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4617 print_indent(indent);
4618 outs() << " remaining list entries extend past the of the section\n";
4619 break;
4620 }
4621 print_indent(indent);
4622 outs() << " list[" << i << "]\n";
4623 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4624 sizeof(struct objc_method_description_t));
4625 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4626 swapStruct(md);
4627
4628 print_indent(indent);
4629 outs() << " name " << format("0x%08" PRIx32, md.name);
4630 if (info->verbose) {
4631 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4632 if (name != nullptr)
4633 outs() << format(" %.*s", xleft, name);
4634 else
4635 outs() << " (not in an __OBJC section)";
4636 }
4637 outs() << "\n";
4638
4639 print_indent(indent);
4640 outs() << " types " << format("0x%08" PRIx32, md.types);
4641 if (info->verbose) {
4642 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4643 if (name != nullptr)
4644 outs() << format(" %.*s", xleft, name);
4645 else
4646 outs() << " (not in an __OBJC section)";
4647 }
4648 outs() << "\n";
4649 }
4650 return false;
4651}
4652
4653static bool print_protocol_list(uint32_t p, uint32_t indent,
4654 struct DisassembleInfo *info);
4655
4656static bool print_protocol(uint32_t p, uint32_t indent,
4657 struct DisassembleInfo *info) {
4658 uint32_t offset, left;
4659 SectionRef S;
4660 struct objc_protocol_t protocol;
4661 const char *r, *name;
4662
4663 r = get_pointer_32(p, offset, left, S, info, true);
4664 if (r == nullptr)
4665 return true;
4666
4667 outs() << "\n";
4668 if (left >= sizeof(struct objc_protocol_t)) {
4669 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4670 } else {
4671 print_indent(indent);
4672 outs() << " Protocol extends past end of the section\n";
4673 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4674 memcpy(&protocol, r, left);
4675 }
4676 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4677 swapStruct(protocol);
4678
4679 print_indent(indent);
4680 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4681 << "\n";
4682
4683 print_indent(indent);
4684 outs() << " protocol_name "
4685 << format("0x%08" PRIx32, protocol.protocol_name);
4686 if (info->verbose) {
4687 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4688 if (name != nullptr)
4689 outs() << format(" %.*s", left, name);
4690 else
4691 outs() << " (not in an __OBJC section)";
4692 }
4693 outs() << "\n";
4694
4695 print_indent(indent);
4696 outs() << " protocol_list "
4697 << format("0x%08" PRIx32, protocol.protocol_list);
4698 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4699 outs() << " (not in an __OBJC section)\n";
4700
4701 print_indent(indent);
4702 outs() << " instance_methods "
4703 << format("0x%08" PRIx32, protocol.instance_methods);
4704 if (print_method_description_list(protocol.instance_methods, indent, info))
4705 outs() << " (not in an __OBJC section)\n";
4706
4707 print_indent(indent);
4708 outs() << " class_methods "
4709 << format("0x%08" PRIx32, protocol.class_methods);
4710 if (print_method_description_list(protocol.class_methods, indent, info))
4711 outs() << " (not in an __OBJC section)\n";
4712
4713 return false;
4714}
4715
4716static bool print_protocol_list(uint32_t p, uint32_t indent,
4717 struct DisassembleInfo *info) {
4718 uint32_t offset, left, l;
4719 SectionRef S;
4720 struct objc_protocol_list_t protocol_list;
4721 const char *r, *list;
4722 int32_t i;
4723
4724 r = get_pointer_32(p, offset, left, S, info, true);
4725 if (r == nullptr)
4726 return true;
4727
4728 outs() << "\n";
4729 if (left > sizeof(struct objc_protocol_list_t)) {
4730 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4731 } else {
4732 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4733 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4734 memcpy(&protocol_list, r, left);
4735 }
4736 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4737 swapStruct(protocol_list);
4738
4739 print_indent(indent);
4740 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4741 << "\n";
4742 print_indent(indent);
4743 outs() << " count " << protocol_list.count << "\n";
4744
4745 list = r + sizeof(struct objc_protocol_list_t);
4746 for (i = 0; i < protocol_list.count; i++) {
4747 if ((i + 1) * sizeof(uint32_t) > left) {
4748 outs() << "\t\t remaining list entries extend past the of the section\n";
4749 break;
4750 }
4751 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4752 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4753 sys::swapByteOrder(l);
4754
4755 print_indent(indent);
4756 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4757 if (print_protocol(l, indent, info))
4758 outs() << "(not in an __OBJC section)\n";
4759 }
4760 return false;
4761}
4762
Kevin Enderby0fc11822015-04-01 20:57:01 +00004763static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4764 struct ivar_list64_t il;
4765 struct ivar64_t i;
4766 const char *r;
4767 uint32_t offset, xoffset, left, j;
4768 SectionRef S, xS;
4769 const char *name, *sym_name, *ivar_offset_p;
4770 uint64_t ivar_offset, n_value;
4771
4772 r = get_pointer_64(p, offset, left, S, info);
4773 if (r == nullptr)
4774 return;
4775 memset(&il, '\0', sizeof(struct ivar_list64_t));
4776 if (left < sizeof(struct ivar_list64_t)) {
4777 memcpy(&il, r, left);
4778 outs() << " (ivar_list_t entends past the end of the section)\n";
4779 } else
4780 memcpy(&il, r, sizeof(struct ivar_list64_t));
4781 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4782 swapStruct(il);
4783 outs() << " entsize " << il.entsize << "\n";
4784 outs() << " count " << il.count << "\n";
4785
4786 p += sizeof(struct ivar_list64_t);
4787 offset += sizeof(struct ivar_list64_t);
4788 for (j = 0; j < il.count; j++) {
4789 r = get_pointer_64(p, offset, left, S, info);
4790 if (r == nullptr)
4791 return;
4792 memset(&i, '\0', sizeof(struct ivar64_t));
4793 if (left < sizeof(struct ivar64_t)) {
4794 memcpy(&i, r, left);
4795 outs() << " (ivar_t entends past the end of the section)\n";
4796 } else
4797 memcpy(&i, r, sizeof(struct ivar64_t));
4798 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4799 swapStruct(i);
4800
4801 outs() << "\t\t\t offset ";
4802 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4803 info, n_value, i.offset);
4804 if (n_value != 0) {
4805 if (info->verbose && sym_name != nullptr)
4806 outs() << sym_name;
4807 else
4808 outs() << format("0x%" PRIx64, n_value);
4809 if (i.offset != 0)
4810 outs() << " + " << format("0x%" PRIx64, i.offset);
4811 } else
4812 outs() << format("0x%" PRIx64, i.offset);
4813 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4814 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4815 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4816 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4817 sys::swapByteOrder(ivar_offset);
4818 outs() << " " << ivar_offset << "\n";
4819 } else
4820 outs() << "\n";
4821
4822 outs() << "\t\t\t name ";
4823 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4824 n_value, i.name);
4825 if (n_value != 0) {
4826 if (info->verbose && sym_name != nullptr)
4827 outs() << sym_name;
4828 else
4829 outs() << format("0x%" PRIx64, n_value);
4830 if (i.name != 0)
4831 outs() << " + " << format("0x%" PRIx64, i.name);
4832 } else
4833 outs() << format("0x%" PRIx64, i.name);
4834 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4835 if (name != nullptr)
4836 outs() << format(" %.*s", left, name);
4837 outs() << "\n";
4838
4839 outs() << "\t\t\t type ";
4840 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4841 n_value, i.name);
4842 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4843 if (n_value != 0) {
4844 if (info->verbose && sym_name != nullptr)
4845 outs() << sym_name;
4846 else
4847 outs() << format("0x%" PRIx64, n_value);
4848 if (i.type != 0)
4849 outs() << " + " << format("0x%" PRIx64, i.type);
4850 } else
4851 outs() << format("0x%" PRIx64, i.type);
4852 if (name != nullptr)
4853 outs() << format(" %.*s", left, name);
4854 outs() << "\n";
4855
4856 outs() << "\t\t\talignment " << i.alignment << "\n";
4857 outs() << "\t\t\t size " << i.size << "\n";
4858
4859 p += sizeof(struct ivar64_t);
4860 offset += sizeof(struct ivar64_t);
4861 }
4862}
4863
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004864static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4865 struct ivar_list32_t il;
4866 struct ivar32_t i;
4867 const char *r;
4868 uint32_t offset, xoffset, left, j;
4869 SectionRef S, xS;
4870 const char *name, *ivar_offset_p;
4871 uint32_t ivar_offset;
4872
4873 r = get_pointer_32(p, offset, left, S, info);
4874 if (r == nullptr)
4875 return;
4876 memset(&il, '\0', sizeof(struct ivar_list32_t));
4877 if (left < sizeof(struct ivar_list32_t)) {
4878 memcpy(&il, r, left);
4879 outs() << " (ivar_list_t entends past the end of the section)\n";
4880 } else
4881 memcpy(&il, r, sizeof(struct ivar_list32_t));
4882 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4883 swapStruct(il);
4884 outs() << " entsize " << il.entsize << "\n";
4885 outs() << " count " << il.count << "\n";
4886
4887 p += sizeof(struct ivar_list32_t);
4888 offset += sizeof(struct ivar_list32_t);
4889 for (j = 0; j < il.count; j++) {
4890 r = get_pointer_32(p, offset, left, S, info);
4891 if (r == nullptr)
4892 return;
4893 memset(&i, '\0', sizeof(struct ivar32_t));
4894 if (left < sizeof(struct ivar32_t)) {
4895 memcpy(&i, r, left);
4896 outs() << " (ivar_t entends past the end of the section)\n";
4897 } else
4898 memcpy(&i, r, sizeof(struct ivar32_t));
4899 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4900 swapStruct(i);
4901
4902 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4903 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4904 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4905 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4906 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4907 sys::swapByteOrder(ivar_offset);
4908 outs() << " " << ivar_offset << "\n";
4909 } else
4910 outs() << "\n";
4911
4912 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4913 name = get_pointer_32(i.name, xoffset, left, xS, info);
4914 if (name != nullptr)
4915 outs() << format(" %.*s", left, name);
4916 outs() << "\n";
4917
4918 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4919 name = get_pointer_32(i.type, xoffset, left, xS, info);
4920 if (name != nullptr)
4921 outs() << format(" %.*s", left, name);
4922 outs() << "\n";
4923
4924 outs() << "\t\t\talignment " << i.alignment << "\n";
4925 outs() << "\t\t\t size " << i.size << "\n";
4926
4927 p += sizeof(struct ivar32_t);
4928 offset += sizeof(struct ivar32_t);
4929 }
4930}
4931
Kevin Enderby0fc11822015-04-01 20:57:01 +00004932static void print_objc_property_list64(uint64_t p,
4933 struct DisassembleInfo *info) {
4934 struct objc_property_list64 opl;
4935 struct objc_property64 op;
4936 const char *r;
4937 uint32_t offset, xoffset, left, j;
4938 SectionRef S, xS;
4939 const char *name, *sym_name;
4940 uint64_t n_value;
4941
4942 r = get_pointer_64(p, offset, left, S, info);
4943 if (r == nullptr)
4944 return;
4945 memset(&opl, '\0', sizeof(struct objc_property_list64));
4946 if (left < sizeof(struct objc_property_list64)) {
4947 memcpy(&opl, r, left);
4948 outs() << " (objc_property_list entends past the end of the section)\n";
4949 } else
4950 memcpy(&opl, r, sizeof(struct objc_property_list64));
4951 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4952 swapStruct(opl);
4953 outs() << " entsize " << opl.entsize << "\n";
4954 outs() << " count " << opl.count << "\n";
4955
4956 p += sizeof(struct objc_property_list64);
4957 offset += sizeof(struct objc_property_list64);
4958 for (j = 0; j < opl.count; j++) {
4959 r = get_pointer_64(p, offset, left, S, info);
4960 if (r == nullptr)
4961 return;
4962 memset(&op, '\0', sizeof(struct objc_property64));
4963 if (left < sizeof(struct objc_property64)) {
4964 memcpy(&op, r, left);
4965 outs() << " (objc_property entends past the end of the section)\n";
4966 } else
4967 memcpy(&op, r, sizeof(struct objc_property64));
4968 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4969 swapStruct(op);
4970
4971 outs() << "\t\t\t name ";
4972 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4973 info, n_value, op.name);
4974 if (n_value != 0) {
4975 if (info->verbose && sym_name != nullptr)
4976 outs() << sym_name;
4977 else
4978 outs() << format("0x%" PRIx64, n_value);
4979 if (op.name != 0)
4980 outs() << " + " << format("0x%" PRIx64, op.name);
4981 } else
4982 outs() << format("0x%" PRIx64, op.name);
4983 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4984 if (name != nullptr)
4985 outs() << format(" %.*s", left, name);
4986 outs() << "\n";
4987
4988 outs() << "\t\t\tattributes ";
4989 sym_name =
4990 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4991 info, n_value, op.attributes);
4992 if (n_value != 0) {
4993 if (info->verbose && sym_name != nullptr)
4994 outs() << sym_name;
4995 else
4996 outs() << format("0x%" PRIx64, n_value);
4997 if (op.attributes != 0)
4998 outs() << " + " << format("0x%" PRIx64, op.attributes);
4999 } else
5000 outs() << format("0x%" PRIx64, op.attributes);
5001 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5002 if (name != nullptr)
5003 outs() << format(" %.*s", left, name);
5004 outs() << "\n";
5005
5006 p += sizeof(struct objc_property64);
5007 offset += sizeof(struct objc_property64);
5008 }
5009}
5010
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005011static void print_objc_property_list32(uint32_t p,
5012 struct DisassembleInfo *info) {
5013 struct objc_property_list32 opl;
5014 struct objc_property32 op;
5015 const char *r;
5016 uint32_t offset, xoffset, left, j;
5017 SectionRef S, xS;
5018 const char *name;
5019
5020 r = get_pointer_32(p, offset, left, S, info);
5021 if (r == nullptr)
5022 return;
5023 memset(&opl, '\0', sizeof(struct objc_property_list32));
5024 if (left < sizeof(struct objc_property_list32)) {
5025 memcpy(&opl, r, left);
5026 outs() << " (objc_property_list entends past the end of the section)\n";
5027 } else
5028 memcpy(&opl, r, sizeof(struct objc_property_list32));
5029 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5030 swapStruct(opl);
5031 outs() << " entsize " << opl.entsize << "\n";
5032 outs() << " count " << opl.count << "\n";
5033
5034 p += sizeof(struct objc_property_list32);
5035 offset += sizeof(struct objc_property_list32);
5036 for (j = 0; j < opl.count; j++) {
5037 r = get_pointer_32(p, offset, left, S, info);
5038 if (r == nullptr)
5039 return;
5040 memset(&op, '\0', sizeof(struct objc_property32));
5041 if (left < sizeof(struct objc_property32)) {
5042 memcpy(&op, r, left);
5043 outs() << " (objc_property entends past the end of the section)\n";
5044 } else
5045 memcpy(&op, r, sizeof(struct objc_property32));
5046 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5047 swapStruct(op);
5048
5049 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
5050 name = get_pointer_32(op.name, xoffset, left, xS, info);
5051 if (name != nullptr)
5052 outs() << format(" %.*s", left, name);
5053 outs() << "\n";
5054
5055 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5056 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5057 if (name != nullptr)
5058 outs() << format(" %.*s", left, name);
5059 outs() << "\n";
5060
5061 p += sizeof(struct objc_property32);
5062 offset += sizeof(struct objc_property32);
5063 }
5064}
5065
Richard Smith81ff44d2015-10-09 22:09:56 +00005066static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00005067 bool &is_meta_class) {
5068 struct class_ro64_t cro;
5069 const char *r;
5070 uint32_t offset, xoffset, left;
5071 SectionRef S, xS;
5072 const char *name, *sym_name;
5073 uint64_t n_value;
5074
5075 r = get_pointer_64(p, offset, left, S, info);
5076 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00005077 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00005078 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005079 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5080 swapStruct(cro);
5081 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5082 if (cro.flags & RO_META)
5083 outs() << " RO_META";
5084 if (cro.flags & RO_ROOT)
5085 outs() << " RO_ROOT";
5086 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5087 outs() << " RO_HAS_CXX_STRUCTORS";
5088 outs() << "\n";
5089 outs() << " instanceStart " << cro.instanceStart << "\n";
5090 outs() << " instanceSize " << cro.instanceSize << "\n";
5091 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5092 << "\n";
5093 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5094 << "\n";
5095 print_layout_map64(cro.ivarLayout, info);
5096
5097 outs() << " name ";
5098 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5099 info, n_value, cro.name);
5100 if (n_value != 0) {
5101 if (info->verbose && sym_name != nullptr)
5102 outs() << sym_name;
5103 else
5104 outs() << format("0x%" PRIx64, n_value);
5105 if (cro.name != 0)
5106 outs() << " + " << format("0x%" PRIx64, cro.name);
5107 } else
5108 outs() << format("0x%" PRIx64, cro.name);
5109 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5110 if (name != nullptr)
5111 outs() << format(" %.*s", left, name);
5112 outs() << "\n";
5113
5114 outs() << " baseMethods ";
5115 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5116 S, info, n_value, cro.baseMethods);
5117 if (n_value != 0) {
5118 if (info->verbose && sym_name != nullptr)
5119 outs() << sym_name;
5120 else
5121 outs() << format("0x%" PRIx64, n_value);
5122 if (cro.baseMethods != 0)
5123 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5124 } else
5125 outs() << format("0x%" PRIx64, cro.baseMethods);
5126 outs() << " (struct method_list_t *)\n";
5127 if (cro.baseMethods + n_value != 0)
5128 print_method_list64_t(cro.baseMethods + n_value, info, "");
5129
5130 outs() << " baseProtocols ";
5131 sym_name =
5132 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5133 info, n_value, cro.baseProtocols);
5134 if (n_value != 0) {
5135 if (info->verbose && sym_name != nullptr)
5136 outs() << sym_name;
5137 else
5138 outs() << format("0x%" PRIx64, n_value);
5139 if (cro.baseProtocols != 0)
5140 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5141 } else
5142 outs() << format("0x%" PRIx64, cro.baseProtocols);
5143 outs() << "\n";
5144 if (cro.baseProtocols + n_value != 0)
5145 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5146
5147 outs() << " ivars ";
5148 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005149 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005150 if (n_value != 0) {
5151 if (info->verbose && sym_name != nullptr)
5152 outs() << sym_name;
5153 else
5154 outs() << format("0x%" PRIx64, n_value);
5155 if (cro.ivars != 0)
5156 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5157 } else
5158 outs() << format("0x%" PRIx64, cro.ivars);
5159 outs() << "\n";
5160 if (cro.ivars + n_value != 0)
5161 print_ivar_list64_t(cro.ivars + n_value, info);
5162
5163 outs() << " weakIvarLayout ";
5164 sym_name =
5165 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5166 info, n_value, cro.weakIvarLayout);
5167 if (n_value != 0) {
5168 if (info->verbose && sym_name != nullptr)
5169 outs() << sym_name;
5170 else
5171 outs() << format("0x%" PRIx64, n_value);
5172 if (cro.weakIvarLayout != 0)
5173 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5174 } else
5175 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5176 outs() << "\n";
5177 print_layout_map64(cro.weakIvarLayout + n_value, info);
5178
5179 outs() << " baseProperties ";
5180 sym_name =
5181 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5182 info, n_value, cro.baseProperties);
5183 if (n_value != 0) {
5184 if (info->verbose && sym_name != nullptr)
5185 outs() << sym_name;
5186 else
5187 outs() << format("0x%" PRIx64, n_value);
5188 if (cro.baseProperties != 0)
5189 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5190 } else
5191 outs() << format("0x%" PRIx64, cro.baseProperties);
5192 outs() << "\n";
5193 if (cro.baseProperties + n_value != 0)
5194 print_objc_property_list64(cro.baseProperties + n_value, info);
5195
Rafael Espindolab9091322015-10-24 23:19:10 +00005196 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005197 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005198}
5199
Richard Smith81ff44d2015-10-09 22:09:56 +00005200static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005201 bool &is_meta_class) {
5202 struct class_ro32_t cro;
5203 const char *r;
5204 uint32_t offset, xoffset, left;
5205 SectionRef S, xS;
5206 const char *name;
5207
5208 r = get_pointer_32(p, offset, left, S, info);
5209 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00005210 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005211 memset(&cro, '\0', sizeof(struct class_ro32_t));
5212 if (left < sizeof(struct class_ro32_t)) {
5213 memcpy(&cro, r, left);
5214 outs() << " (class_ro_t entends past the end of the section)\n";
5215 } else
5216 memcpy(&cro, r, sizeof(struct class_ro32_t));
5217 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5218 swapStruct(cro);
5219 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5220 if (cro.flags & RO_META)
5221 outs() << " RO_META";
5222 if (cro.flags & RO_ROOT)
5223 outs() << " RO_ROOT";
5224 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5225 outs() << " RO_HAS_CXX_STRUCTORS";
5226 outs() << "\n";
5227 outs() << " instanceStart " << cro.instanceStart << "\n";
5228 outs() << " instanceSize " << cro.instanceSize << "\n";
5229 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5230 << "\n";
5231 print_layout_map32(cro.ivarLayout, info);
5232
5233 outs() << " name " << format("0x%" PRIx32, cro.name);
5234 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5235 if (name != nullptr)
5236 outs() << format(" %.*s", left, name);
5237 outs() << "\n";
5238
5239 outs() << " baseMethods "
5240 << format("0x%" PRIx32, cro.baseMethods)
5241 << " (struct method_list_t *)\n";
5242 if (cro.baseMethods != 0)
5243 print_method_list32_t(cro.baseMethods, info, "");
5244
5245 outs() << " baseProtocols "
5246 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5247 if (cro.baseProtocols != 0)
5248 print_protocol_list32_t(cro.baseProtocols, info);
5249 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5250 << "\n";
5251 if (cro.ivars != 0)
5252 print_ivar_list32_t(cro.ivars, info);
5253 outs() << " weakIvarLayout "
5254 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5255 print_layout_map32(cro.weakIvarLayout, info);
5256 outs() << " baseProperties "
5257 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5258 if (cro.baseProperties != 0)
5259 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00005260 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005261 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005262}
5263
Kevin Enderby0fc11822015-04-01 20:57:01 +00005264static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5265 struct class64_t c;
5266 const char *r;
5267 uint32_t offset, left;
5268 SectionRef S;
5269 const char *name;
5270 uint64_t isa_n_value, n_value;
5271
5272 r = get_pointer_64(p, offset, left, S, info);
5273 if (r == nullptr || left < sizeof(struct class64_t))
5274 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005275 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005276 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5277 swapStruct(c);
5278
5279 outs() << " isa " << format("0x%" PRIx64, c.isa);
5280 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5281 isa_n_value, c.isa);
5282 if (name != nullptr)
5283 outs() << " " << name;
5284 outs() << "\n";
5285
5286 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5287 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5288 n_value, c.superclass);
5289 if (name != nullptr)
5290 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005291 else {
5292 name = get_dyld_bind_info_symbolname(S.getAddress() +
5293 offset + offsetof(struct class64_t, superclass), info);
5294 if (name != nullptr)
5295 outs() << " " << name;
5296 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005297 outs() << "\n";
5298
5299 outs() << " cache " << format("0x%" PRIx64, c.cache);
5300 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5301 n_value, c.cache);
5302 if (name != nullptr)
5303 outs() << " " << name;
5304 outs() << "\n";
5305
5306 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5307 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5308 n_value, c.vtable);
5309 if (name != nullptr)
5310 outs() << " " << name;
5311 outs() << "\n";
5312
5313 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5314 n_value, c.data);
5315 outs() << " data ";
5316 if (n_value != 0) {
5317 if (info->verbose && name != nullptr)
5318 outs() << name;
5319 else
5320 outs() << format("0x%" PRIx64, n_value);
5321 if (c.data != 0)
5322 outs() << " + " << format("0x%" PRIx64, c.data);
5323 } else
5324 outs() << format("0x%" PRIx64, c.data);
5325 outs() << " (struct class_ro_t *)";
5326
5327 // This is a Swift class if some of the low bits of the pointer are set.
5328 if ((c.data + n_value) & 0x7)
5329 outs() << " Swift class";
5330 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005331 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005332 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5333 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005334
Kevin Enderbyaac75382015-10-08 16:56:35 +00005335 if (!is_meta_class &&
5336 c.isa + isa_n_value != p &&
5337 c.isa + isa_n_value != 0 &&
5338 info->depth < 100) {
5339 info->depth++;
5340 outs() << "Meta Class\n";
5341 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005342 }
5343}
5344
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005345static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5346 struct class32_t c;
5347 const char *r;
5348 uint32_t offset, left;
5349 SectionRef S;
5350 const char *name;
5351
5352 r = get_pointer_32(p, offset, left, S, info);
5353 if (r == nullptr)
5354 return;
5355 memset(&c, '\0', sizeof(struct class32_t));
5356 if (left < sizeof(struct class32_t)) {
5357 memcpy(&c, r, left);
5358 outs() << " (class_t entends past the end of the section)\n";
5359 } else
5360 memcpy(&c, r, sizeof(struct class32_t));
5361 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5362 swapStruct(c);
5363
5364 outs() << " isa " << format("0x%" PRIx32, c.isa);
5365 name =
5366 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5367 if (name != nullptr)
5368 outs() << " " << name;
5369 outs() << "\n";
5370
5371 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5372 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5373 c.superclass);
5374 if (name != nullptr)
5375 outs() << " " << name;
5376 outs() << "\n";
5377
5378 outs() << " cache " << format("0x%" PRIx32, c.cache);
5379 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5380 c.cache);
5381 if (name != nullptr)
5382 outs() << " " << name;
5383 outs() << "\n";
5384
5385 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5386 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5387 c.vtable);
5388 if (name != nullptr)
5389 outs() << " " << name;
5390 outs() << "\n";
5391
5392 name =
5393 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5394 outs() << " data " << format("0x%" PRIx32, c.data)
5395 << " (struct class_ro_t *)";
5396
5397 // This is a Swift class if some of the low bits of the pointer are set.
5398 if (c.data & 0x3)
5399 outs() << " Swift class";
5400 outs() << "\n";
5401 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005402 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5403 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005404
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005405 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005406 outs() << "Meta Class\n";
5407 print_class32_t(c.isa, info);
5408 }
5409}
5410
Kevin Enderby846c0002015-04-16 17:19:59 +00005411static void print_objc_class_t(struct objc_class_t *objc_class,
5412 struct DisassembleInfo *info) {
5413 uint32_t offset, left, xleft;
5414 const char *name, *p, *ivar_list;
5415 SectionRef S;
5416 int32_t i;
5417 struct objc_ivar_list_t objc_ivar_list;
5418 struct objc_ivar_t ivar;
5419
5420 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5421 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5422 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5423 if (name != nullptr)
5424 outs() << format(" %.*s", left, name);
5425 else
5426 outs() << " (not in an __OBJC section)";
5427 }
5428 outs() << "\n";
5429
5430 outs() << "\t super_class "
5431 << format("0x%08" PRIx32, objc_class->super_class);
5432 if (info->verbose) {
5433 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5434 if (name != nullptr)
5435 outs() << format(" %.*s", left, name);
5436 else
5437 outs() << " (not in an __OBJC section)";
5438 }
5439 outs() << "\n";
5440
5441 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5442 if (info->verbose) {
5443 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5444 if (name != nullptr)
5445 outs() << format(" %.*s", left, name);
5446 else
5447 outs() << " (not in an __OBJC section)";
5448 }
5449 outs() << "\n";
5450
5451 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5452 << "\n";
5453
5454 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5455 if (info->verbose) {
5456 if (CLS_GETINFO(objc_class, CLS_CLASS))
5457 outs() << " CLS_CLASS";
5458 else if (CLS_GETINFO(objc_class, CLS_META))
5459 outs() << " CLS_META";
5460 }
5461 outs() << "\n";
5462
5463 outs() << "\t instance_size "
5464 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5465
5466 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5467 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5468 if (p != nullptr) {
5469 if (left > sizeof(struct objc_ivar_list_t)) {
5470 outs() << "\n";
5471 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5472 } else {
5473 outs() << " (entends past the end of the section)\n";
5474 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5475 memcpy(&objc_ivar_list, p, left);
5476 }
5477 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5478 swapStruct(objc_ivar_list);
5479 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5480 ivar_list = p + sizeof(struct objc_ivar_list_t);
5481 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5482 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5483 outs() << "\t\t remaining ivar's extend past the of the section\n";
5484 break;
5485 }
5486 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5487 sizeof(struct objc_ivar_t));
5488 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5489 swapStruct(ivar);
5490
5491 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5492 if (info->verbose) {
5493 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5494 if (name != nullptr)
5495 outs() << format(" %.*s", xleft, name);
5496 else
5497 outs() << " (not in an __OBJC section)";
5498 }
5499 outs() << "\n";
5500
5501 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5502 if (info->verbose) {
5503 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5504 if (name != nullptr)
5505 outs() << format(" %.*s", xleft, name);
5506 else
5507 outs() << " (not in an __OBJC section)";
5508 }
5509 outs() << "\n";
5510
5511 outs() << "\t\t ivar_offset "
5512 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5513 }
5514 } else {
5515 outs() << " (not in an __OBJC section)\n";
5516 }
5517
5518 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5519 if (print_method_list(objc_class->methodLists, info))
5520 outs() << " (not in an __OBJC section)\n";
5521
5522 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5523 << "\n";
5524
5525 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5526 if (print_protocol_list(objc_class->protocols, 16, info))
5527 outs() << " (not in an __OBJC section)\n";
5528}
5529
5530static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5531 struct DisassembleInfo *info) {
5532 uint32_t offset, left;
5533 const char *name;
5534 SectionRef S;
5535
5536 outs() << "\t category name "
5537 << format("0x%08" PRIx32, objc_category->category_name);
5538 if (info->verbose) {
5539 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5540 true);
5541 if (name != nullptr)
5542 outs() << format(" %.*s", left, name);
5543 else
5544 outs() << " (not in an __OBJC section)";
5545 }
5546 outs() << "\n";
5547
5548 outs() << "\t\t class name "
5549 << format("0x%08" PRIx32, objc_category->class_name);
5550 if (info->verbose) {
5551 name =
5552 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5553 if (name != nullptr)
5554 outs() << format(" %.*s", left, name);
5555 else
5556 outs() << " (not in an __OBJC section)";
5557 }
5558 outs() << "\n";
5559
5560 outs() << "\t instance methods "
5561 << format("0x%08" PRIx32, objc_category->instance_methods);
5562 if (print_method_list(objc_category->instance_methods, info))
5563 outs() << " (not in an __OBJC section)\n";
5564
5565 outs() << "\t class methods "
5566 << format("0x%08" PRIx32, objc_category->class_methods);
5567 if (print_method_list(objc_category->class_methods, info))
5568 outs() << " (not in an __OBJC section)\n";
5569}
5570
Kevin Enderby0fc11822015-04-01 20:57:01 +00005571static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5572 struct category64_t c;
5573 const char *r;
5574 uint32_t offset, xoffset, left;
5575 SectionRef S, xS;
5576 const char *name, *sym_name;
5577 uint64_t n_value;
5578
5579 r = get_pointer_64(p, offset, left, S, info);
5580 if (r == nullptr)
5581 return;
5582 memset(&c, '\0', sizeof(struct category64_t));
5583 if (left < sizeof(struct category64_t)) {
5584 memcpy(&c, r, left);
5585 outs() << " (category_t entends past the end of the section)\n";
5586 } else
5587 memcpy(&c, r, sizeof(struct category64_t));
5588 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5589 swapStruct(c);
5590
5591 outs() << " name ";
5592 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5593 info, n_value, c.name);
5594 if (n_value != 0) {
5595 if (info->verbose && sym_name != nullptr)
5596 outs() << sym_name;
5597 else
5598 outs() << format("0x%" PRIx64, n_value);
5599 if (c.name != 0)
5600 outs() << " + " << format("0x%" PRIx64, c.name);
5601 } else
5602 outs() << format("0x%" PRIx64, c.name);
5603 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5604 if (name != nullptr)
5605 outs() << format(" %.*s", left, name);
5606 outs() << "\n";
5607
5608 outs() << " cls ";
5609 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5610 n_value, c.cls);
5611 if (n_value != 0) {
5612 if (info->verbose && sym_name != nullptr)
5613 outs() << sym_name;
5614 else
5615 outs() << format("0x%" PRIx64, n_value);
5616 if (c.cls != 0)
5617 outs() << " + " << format("0x%" PRIx64, c.cls);
5618 } else
5619 outs() << format("0x%" PRIx64, c.cls);
5620 outs() << "\n";
5621 if (c.cls + n_value != 0)
5622 print_class64_t(c.cls + n_value, info);
5623
5624 outs() << " instanceMethods ";
5625 sym_name =
5626 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5627 info, n_value, c.instanceMethods);
5628 if (n_value != 0) {
5629 if (info->verbose && sym_name != nullptr)
5630 outs() << sym_name;
5631 else
5632 outs() << format("0x%" PRIx64, n_value);
5633 if (c.instanceMethods != 0)
5634 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5635 } else
5636 outs() << format("0x%" PRIx64, c.instanceMethods);
5637 outs() << "\n";
5638 if (c.instanceMethods + n_value != 0)
5639 print_method_list64_t(c.instanceMethods + n_value, info, "");
5640
5641 outs() << " classMethods ";
5642 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5643 S, info, n_value, c.classMethods);
5644 if (n_value != 0) {
5645 if (info->verbose && sym_name != nullptr)
5646 outs() << sym_name;
5647 else
5648 outs() << format("0x%" PRIx64, n_value);
5649 if (c.classMethods != 0)
5650 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5651 } else
5652 outs() << format("0x%" PRIx64, c.classMethods);
5653 outs() << "\n";
5654 if (c.classMethods + n_value != 0)
5655 print_method_list64_t(c.classMethods + n_value, info, "");
5656
5657 outs() << " protocols ";
5658 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5659 info, n_value, c.protocols);
5660 if (n_value != 0) {
5661 if (info->verbose && sym_name != nullptr)
5662 outs() << sym_name;
5663 else
5664 outs() << format("0x%" PRIx64, n_value);
5665 if (c.protocols != 0)
5666 outs() << " + " << format("0x%" PRIx64, c.protocols);
5667 } else
5668 outs() << format("0x%" PRIx64, c.protocols);
5669 outs() << "\n";
5670 if (c.protocols + n_value != 0)
5671 print_protocol_list64_t(c.protocols + n_value, info);
5672
5673 outs() << "instanceProperties ";
5674 sym_name =
5675 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5676 S, info, n_value, c.instanceProperties);
5677 if (n_value != 0) {
5678 if (info->verbose && sym_name != nullptr)
5679 outs() << sym_name;
5680 else
5681 outs() << format("0x%" PRIx64, n_value);
5682 if (c.instanceProperties != 0)
5683 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5684 } else
5685 outs() << format("0x%" PRIx64, c.instanceProperties);
5686 outs() << "\n";
5687 if (c.instanceProperties + n_value != 0)
5688 print_objc_property_list64(c.instanceProperties + n_value, info);
5689}
5690
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005691static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5692 struct category32_t c;
5693 const char *r;
5694 uint32_t offset, left;
5695 SectionRef S, xS;
5696 const char *name;
5697
5698 r = get_pointer_32(p, offset, left, S, info);
5699 if (r == nullptr)
5700 return;
5701 memset(&c, '\0', sizeof(struct category32_t));
5702 if (left < sizeof(struct category32_t)) {
5703 memcpy(&c, r, left);
5704 outs() << " (category_t entends past the end of the section)\n";
5705 } else
5706 memcpy(&c, r, sizeof(struct category32_t));
5707 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5708 swapStruct(c);
5709
5710 outs() << " name " << format("0x%" PRIx32, c.name);
5711 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5712 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005713 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005714 outs() << " " << name;
5715 outs() << "\n";
5716
5717 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5718 if (c.cls != 0)
5719 print_class32_t(c.cls, info);
5720 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5721 << "\n";
5722 if (c.instanceMethods != 0)
5723 print_method_list32_t(c.instanceMethods, info, "");
5724 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5725 << "\n";
5726 if (c.classMethods != 0)
5727 print_method_list32_t(c.classMethods, info, "");
5728 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5729 if (c.protocols != 0)
5730 print_protocol_list32_t(c.protocols, info);
5731 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5732 << "\n";
5733 if (c.instanceProperties != 0)
5734 print_objc_property_list32(c.instanceProperties, info);
5735}
5736
Kevin Enderby0fc11822015-04-01 20:57:01 +00005737static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5738 uint32_t i, left, offset, xoffset;
5739 uint64_t p, n_value;
5740 struct message_ref64 mr;
5741 const char *name, *sym_name;
5742 const char *r;
5743 SectionRef xS;
5744
5745 if (S == SectionRef())
5746 return;
5747
5748 StringRef SectName;
5749 S.getName(SectName);
5750 DataRefImpl Ref = S.getRawDataRefImpl();
5751 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5752 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5753 offset = 0;
5754 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5755 p = S.getAddress() + i;
5756 r = get_pointer_64(p, offset, left, S, info);
5757 if (r == nullptr)
5758 return;
5759 memset(&mr, '\0', sizeof(struct message_ref64));
5760 if (left < sizeof(struct message_ref64)) {
5761 memcpy(&mr, r, left);
5762 outs() << " (message_ref entends past the end of the section)\n";
5763 } else
5764 memcpy(&mr, r, sizeof(struct message_ref64));
5765 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5766 swapStruct(mr);
5767
5768 outs() << " imp ";
5769 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5770 n_value, mr.imp);
5771 if (n_value != 0) {
5772 outs() << format("0x%" PRIx64, n_value) << " ";
5773 if (mr.imp != 0)
5774 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5775 } else
5776 outs() << format("0x%" PRIx64, mr.imp) << " ";
5777 if (name != nullptr)
5778 outs() << " " << name;
5779 outs() << "\n";
5780
5781 outs() << " sel ";
5782 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5783 info, n_value, mr.sel);
5784 if (n_value != 0) {
5785 if (info->verbose && sym_name != nullptr)
5786 outs() << sym_name;
5787 else
5788 outs() << format("0x%" PRIx64, n_value);
5789 if (mr.sel != 0)
5790 outs() << " + " << format("0x%" PRIx64, mr.sel);
5791 } else
5792 outs() << format("0x%" PRIx64, mr.sel);
5793 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5794 if (name != nullptr)
5795 outs() << format(" %.*s", left, name);
5796 outs() << "\n";
5797
5798 offset += sizeof(struct message_ref64);
5799 }
5800}
5801
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005802static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5803 uint32_t i, left, offset, xoffset, p;
5804 struct message_ref32 mr;
5805 const char *name, *r;
5806 SectionRef xS;
5807
5808 if (S == SectionRef())
5809 return;
5810
5811 StringRef SectName;
5812 S.getName(SectName);
5813 DataRefImpl Ref = S.getRawDataRefImpl();
5814 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5815 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5816 offset = 0;
5817 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5818 p = S.getAddress() + i;
5819 r = get_pointer_32(p, offset, left, S, info);
5820 if (r == nullptr)
5821 return;
5822 memset(&mr, '\0', sizeof(struct message_ref32));
5823 if (left < sizeof(struct message_ref32)) {
5824 memcpy(&mr, r, left);
5825 outs() << " (message_ref entends past the end of the section)\n";
5826 } else
5827 memcpy(&mr, r, sizeof(struct message_ref32));
5828 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5829 swapStruct(mr);
5830
5831 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5832 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5833 mr.imp);
5834 if (name != nullptr)
5835 outs() << " " << name;
5836 outs() << "\n";
5837
5838 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5839 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5840 if (name != nullptr)
5841 outs() << " " << name;
5842 outs() << "\n";
5843
5844 offset += sizeof(struct message_ref32);
5845 }
5846}
5847
Kevin Enderby0fc11822015-04-01 20:57:01 +00005848static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5849 uint32_t left, offset, swift_version;
5850 uint64_t p;
5851 struct objc_image_info64 o;
5852 const char *r;
5853
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005854 if (S == SectionRef())
5855 return;
5856
Kevin Enderby0fc11822015-04-01 20:57:01 +00005857 StringRef SectName;
5858 S.getName(SectName);
5859 DataRefImpl Ref = S.getRawDataRefImpl();
5860 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5861 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5862 p = S.getAddress();
5863 r = get_pointer_64(p, offset, left, S, info);
5864 if (r == nullptr)
5865 return;
5866 memset(&o, '\0', sizeof(struct objc_image_info64));
5867 if (left < sizeof(struct objc_image_info64)) {
5868 memcpy(&o, r, left);
5869 outs() << " (objc_image_info entends past the end of the section)\n";
5870 } else
5871 memcpy(&o, r, sizeof(struct objc_image_info64));
5872 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5873 swapStruct(o);
5874 outs() << " version " << o.version << "\n";
5875 outs() << " flags " << format("0x%" PRIx32, o.flags);
5876 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5877 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5878 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5879 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005880 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5881 outs() << " OBJC_IMAGE_IS_SIMULATED";
5882 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5883 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005884 swift_version = (o.flags >> 8) & 0xff;
5885 if (swift_version != 0) {
5886 if (swift_version == 1)
5887 outs() << " Swift 1.0";
5888 else if (swift_version == 2)
5889 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005890 else if(swift_version == 3)
5891 outs() << " Swift 2.0";
5892 else if(swift_version == 4)
5893 outs() << " Swift 3.0";
5894 else if(swift_version == 5)
5895 outs() << " Swift 4.0";
5896 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005897 outs() << " Swift 4.1/Swift 4.2";
5898 else if(swift_version == 7)
5899 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005900 else
5901 outs() << " unknown future Swift version (" << swift_version << ")";
5902 }
5903 outs() << "\n";
5904}
5905
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005906static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5907 uint32_t left, offset, swift_version, p;
5908 struct objc_image_info32 o;
5909 const char *r;
5910
Kevin Enderby19be2512016-04-21 19:49:29 +00005911 if (S == SectionRef())
5912 return;
5913
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005914 StringRef SectName;
5915 S.getName(SectName);
5916 DataRefImpl Ref = S.getRawDataRefImpl();
5917 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5918 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5919 p = S.getAddress();
5920 r = get_pointer_32(p, offset, left, S, info);
5921 if (r == nullptr)
5922 return;
5923 memset(&o, '\0', sizeof(struct objc_image_info32));
5924 if (left < sizeof(struct objc_image_info32)) {
5925 memcpy(&o, r, left);
5926 outs() << " (objc_image_info entends past the end of the section)\n";
5927 } else
5928 memcpy(&o, r, sizeof(struct objc_image_info32));
5929 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5930 swapStruct(o);
5931 outs() << " version " << o.version << "\n";
5932 outs() << " flags " << format("0x%" PRIx32, o.flags);
5933 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5934 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5935 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5936 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5937 swift_version = (o.flags >> 8) & 0xff;
5938 if (swift_version != 0) {
5939 if (swift_version == 1)
5940 outs() << " Swift 1.0";
5941 else if (swift_version == 2)
5942 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005943 else if(swift_version == 3)
5944 outs() << " Swift 2.0";
5945 else if(swift_version == 4)
5946 outs() << " Swift 3.0";
5947 else if(swift_version == 5)
5948 outs() << " Swift 4.0";
5949 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005950 outs() << " Swift 4.1/Swift 4.2";
5951 else if(swift_version == 7)
5952 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005953 else
5954 outs() << " unknown future Swift version (" << swift_version << ")";
5955 }
5956 outs() << "\n";
5957}
5958
Kevin Enderby846c0002015-04-16 17:19:59 +00005959static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5960 uint32_t left, offset, p;
5961 struct imageInfo_t o;
5962 const char *r;
5963
5964 StringRef SectName;
5965 S.getName(SectName);
5966 DataRefImpl Ref = S.getRawDataRefImpl();
5967 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5968 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5969 p = S.getAddress();
5970 r = get_pointer_32(p, offset, left, S, info);
5971 if (r == nullptr)
5972 return;
5973 memset(&o, '\0', sizeof(struct imageInfo_t));
5974 if (left < sizeof(struct imageInfo_t)) {
5975 memcpy(&o, r, left);
5976 outs() << " (imageInfo entends past the end of the section)\n";
5977 } else
5978 memcpy(&o, r, sizeof(struct imageInfo_t));
5979 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5980 swapStruct(o);
5981 outs() << " version " << o.version << "\n";
5982 outs() << " flags " << format("0x%" PRIx32, o.flags);
5983 if (o.flags & 0x1)
5984 outs() << " F&C";
5985 if (o.flags & 0x2)
5986 outs() << " GC";
5987 if (o.flags & 0x4)
5988 outs() << " GC-only";
5989 else
5990 outs() << " RR";
5991 outs() << "\n";
5992}
5993
Kevin Enderby0fc11822015-04-01 20:57:01 +00005994static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5995 SymbolAddressMap AddrMap;
5996 if (verbose)
5997 CreateSymbolAddressMap(O, &AddrMap);
5998
5999 std::vector<SectionRef> Sections;
6000 for (const SectionRef &Section : O->sections()) {
6001 StringRef SectName;
6002 Section.getName(SectName);
6003 Sections.push_back(Section);
6004 }
6005
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006006 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006007
Davide Italiano62507042015-12-11 22:27:59 +00006008 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6009 if (CL == SectionRef())
6010 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006011 if (CL == SectionRef())
6012 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6013 if (CL == SectionRef())
6014 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00006015 info.S = CL;
6016 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006017
Davide Italiano62507042015-12-11 22:27:59 +00006018 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6019 if (CR == SectionRef())
6020 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006021 if (CR == SectionRef())
6022 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6023 if (CR == SectionRef())
6024 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006025 info.S = CR;
6026 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006027
Davide Italiano62507042015-12-11 22:27:59 +00006028 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6029 if (SR == SectionRef())
6030 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006031 if (SR == SectionRef())
6032 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6033 if (SR == SectionRef())
6034 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006035 info.S = SR;
6036 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006037
Davide Italiano62507042015-12-11 22:27:59 +00006038 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6039 if (CA == SectionRef())
6040 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006041 if (CA == SectionRef())
6042 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6043 if (CA == SectionRef())
6044 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00006045 info.S = CA;
6046 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006047
Davide Italiano62507042015-12-11 22:27:59 +00006048 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6049 if (PL == SectionRef())
6050 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006051 if (PL == SectionRef())
6052 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6053 if (PL == SectionRef())
6054 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00006055 info.S = PL;
6056 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006057
Davide Italiano62507042015-12-11 22:27:59 +00006058 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6059 if (MR == SectionRef())
6060 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006061 if (MR == SectionRef())
6062 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6063 if (MR == SectionRef())
6064 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006065 info.S = MR;
6066 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006067
Davide Italiano62507042015-12-11 22:27:59 +00006068 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6069 if (II == SectionRef())
6070 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00006071 if (II == SectionRef())
6072 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6073 if (II == SectionRef())
6074 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00006075 info.S = II;
6076 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006077}
6078
6079static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006080 SymbolAddressMap AddrMap;
6081 if (verbose)
6082 CreateSymbolAddressMap(O, &AddrMap);
6083
6084 std::vector<SectionRef> Sections;
6085 for (const SectionRef &Section : O->sections()) {
6086 StringRef SectName;
6087 Section.getName(SectName);
6088 Sections.push_back(Section);
6089 }
6090
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006091 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006092
Kevin Enderby5879a482017-02-09 17:56:26 +00006093 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6094 if (CL == SectionRef())
6095 CL = get_section(O, "__DATA", "__objc_classlist");
6096 if (CL == SectionRef())
6097 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6098 if (CL == SectionRef())
6099 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6100 info.S = CL;
6101 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006102
Kevin Enderby5879a482017-02-09 17:56:26 +00006103 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6104 if (CR == SectionRef())
6105 CR = get_section(O, "__DATA", "__objc_classrefs");
6106 if (CR == SectionRef())
6107 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6108 if (CR == SectionRef())
6109 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6110 info.S = CR;
6111 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006112
Kevin Enderby5879a482017-02-09 17:56:26 +00006113 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6114 if (SR == SectionRef())
6115 SR = get_section(O, "__DATA", "__objc_superrefs");
6116 if (SR == SectionRef())
6117 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6118 if (SR == SectionRef())
6119 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6120 info.S = SR;
6121 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006122
Kevin Enderby5879a482017-02-09 17:56:26 +00006123 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6124 if (CA == SectionRef())
6125 CA = get_section(O, "__DATA", "__objc_catlist");
6126 if (CA == SectionRef())
6127 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6128 if (CA == SectionRef())
6129 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6130 info.S = CA;
6131 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006132
Kevin Enderby5879a482017-02-09 17:56:26 +00006133 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6134 if (PL == SectionRef())
6135 PL = get_section(O, "__DATA", "__objc_protolist");
6136 if (PL == SectionRef())
6137 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6138 if (PL == SectionRef())
6139 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6140 info.S = PL;
6141 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006142
Kevin Enderby5879a482017-02-09 17:56:26 +00006143 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6144 if (MR == SectionRef())
6145 MR = get_section(O, "__DATA", "__objc_msgrefs");
6146 if (MR == SectionRef())
6147 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6148 if (MR == SectionRef())
6149 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6150 info.S = MR;
6151 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006152
Kevin Enderby5879a482017-02-09 17:56:26 +00006153 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6154 if (II == SectionRef())
6155 II = get_section(O, "__DATA", "__objc_imageinfo");
6156 if (II == SectionRef())
6157 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6158 if (II == SectionRef())
6159 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6160 info.S = II;
6161 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006162}
6163
6164static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00006165 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6166 const char *r, *name, *defs;
6167 struct objc_module_t module;
6168 SectionRef S, xS;
6169 struct objc_symtab_t symtab;
6170 struct objc_class_t objc_class;
6171 struct objc_category_t objc_category;
6172
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006173 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00006174 S = get_section(O, "__OBJC", "__module_info");
6175 if (S == SectionRef())
6176 return false;
6177
6178 SymbolAddressMap AddrMap;
6179 if (verbose)
6180 CreateSymbolAddressMap(O, &AddrMap);
6181
6182 std::vector<SectionRef> Sections;
6183 for (const SectionRef &Section : O->sections()) {
6184 StringRef SectName;
6185 Section.getName(SectName);
6186 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006187 }
Kevin Enderby846c0002015-04-16 17:19:59 +00006188
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006189 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00006190
6191 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6192 p = S.getAddress() + i;
6193 r = get_pointer_32(p, offset, left, S, &info, true);
6194 if (r == nullptr)
6195 return true;
6196 memset(&module, '\0', sizeof(struct objc_module_t));
6197 if (left < sizeof(struct objc_module_t)) {
6198 memcpy(&module, r, left);
6199 outs() << " (module extends past end of __module_info section)\n";
6200 } else
6201 memcpy(&module, r, sizeof(struct objc_module_t));
6202 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6203 swapStruct(module);
6204
6205 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6206 outs() << " version " << module.version << "\n";
6207 outs() << " size " << module.size << "\n";
6208 outs() << " name ";
6209 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6210 if (name != nullptr)
6211 outs() << format("%.*s", left, name);
6212 else
6213 outs() << format("0x%08" PRIx32, module.name)
6214 << "(not in an __OBJC section)";
6215 outs() << "\n";
6216
6217 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6218 if (module.symtab == 0 || r == nullptr) {
6219 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6220 << " (not in an __OBJC section)\n";
6221 continue;
6222 }
6223 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6224 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6225 defs_left = 0;
6226 defs = nullptr;
6227 if (left < sizeof(struct objc_symtab_t)) {
6228 memcpy(&symtab, r, left);
6229 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6230 } else {
6231 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6232 if (left > sizeof(struct objc_symtab_t)) {
6233 defs_left = left - sizeof(struct objc_symtab_t);
6234 defs = r + sizeof(struct objc_symtab_t);
6235 }
6236 }
6237 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6238 swapStruct(symtab);
6239
6240 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6241 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6242 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6243 if (r == nullptr)
6244 outs() << " (not in an __OBJC section)";
6245 outs() << "\n";
6246 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6247 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6248 if (symtab.cls_def_cnt > 0)
6249 outs() << "\tClass Definitions\n";
6250 for (j = 0; j < symtab.cls_def_cnt; j++) {
6251 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6252 outs() << "\t(remaining class defs entries entends past the end of the "
6253 << "section)\n";
6254 break;
6255 }
6256 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6257 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6258 sys::swapByteOrder(def);
6259
6260 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6261 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6262 if (r != nullptr) {
6263 if (left > sizeof(struct objc_class_t)) {
6264 outs() << "\n";
6265 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6266 } else {
6267 outs() << " (entends past the end of the section)\n";
6268 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6269 memcpy(&objc_class, r, left);
6270 }
6271 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6272 swapStruct(objc_class);
6273 print_objc_class_t(&objc_class, &info);
6274 } else {
6275 outs() << "(not in an __OBJC section)\n";
6276 }
6277
6278 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6279 outs() << "\tMeta Class";
6280 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6281 if (r != nullptr) {
6282 if (left > sizeof(struct objc_class_t)) {
6283 outs() << "\n";
6284 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6285 } else {
6286 outs() << " (entends past the end of the section)\n";
6287 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6288 memcpy(&objc_class, r, left);
6289 }
6290 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6291 swapStruct(objc_class);
6292 print_objc_class_t(&objc_class, &info);
6293 } else {
6294 outs() << "(not in an __OBJC section)\n";
6295 }
6296 }
6297 }
6298 if (symtab.cat_def_cnt > 0)
6299 outs() << "\tCategory Definitions\n";
6300 for (j = 0; j < symtab.cat_def_cnt; j++) {
6301 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6302 outs() << "\t(remaining category defs entries entends past the end of "
6303 << "the section)\n";
6304 break;
6305 }
6306 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6307 sizeof(uint32_t));
6308 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6309 sys::swapByteOrder(def);
6310
6311 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6312 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6313 << format("0x%08" PRIx32, def);
6314 if (r != nullptr) {
6315 if (left > sizeof(struct objc_category_t)) {
6316 outs() << "\n";
6317 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6318 } else {
6319 outs() << " (entends past the end of the section)\n";
6320 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6321 memcpy(&objc_category, r, left);
6322 }
6323 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6324 swapStruct(objc_category);
6325 print_objc_objc_category_t(&objc_category, &info);
6326 } else {
6327 outs() << "(not in an __OBJC section)\n";
6328 }
6329 }
6330 }
6331 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6332 if (II != SectionRef())
6333 print_image_info(II, &info);
6334
6335 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006336}
6337
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006338static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6339 uint32_t size, uint32_t addr) {
6340 SymbolAddressMap AddrMap;
6341 CreateSymbolAddressMap(O, &AddrMap);
6342
6343 std::vector<SectionRef> Sections;
6344 for (const SectionRef &Section : O->sections()) {
6345 StringRef SectName;
6346 Section.getName(SectName);
6347 Sections.push_back(Section);
6348 }
6349
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006350 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006351
6352 const char *p;
6353 struct objc_protocol_t protocol;
6354 uint32_t left, paddr;
6355 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6356 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6357 left = size - (p - sect);
6358 if (left < sizeof(struct objc_protocol_t)) {
6359 outs() << "Protocol extends past end of __protocol section\n";
6360 memcpy(&protocol, p, left);
6361 } else
6362 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6363 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6364 swapStruct(protocol);
6365 paddr = addr + (p - sect);
6366 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6367 if (print_protocol(paddr, 0, &info))
6368 outs() << "(not in an __OBJC section)\n";
6369 }
6370}
6371
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006372#ifdef HAVE_LIBXAR
6373inline void swapStruct(struct xar_header &xar) {
6374 sys::swapByteOrder(xar.magic);
6375 sys::swapByteOrder(xar.size);
6376 sys::swapByteOrder(xar.version);
6377 sys::swapByteOrder(xar.toc_length_compressed);
6378 sys::swapByteOrder(xar.toc_length_uncompressed);
6379 sys::swapByteOrder(xar.cksum_alg);
6380}
6381
6382static void PrintModeVerbose(uint32_t mode) {
6383 switch(mode & S_IFMT){
6384 case S_IFDIR:
6385 outs() << "d";
6386 break;
6387 case S_IFCHR:
6388 outs() << "c";
6389 break;
6390 case S_IFBLK:
6391 outs() << "b";
6392 break;
6393 case S_IFREG:
6394 outs() << "-";
6395 break;
6396 case S_IFLNK:
6397 outs() << "l";
6398 break;
6399 case S_IFSOCK:
6400 outs() << "s";
6401 break;
6402 default:
6403 outs() << "?";
6404 break;
6405 }
6406
6407 /* owner permissions */
6408 if(mode & S_IREAD)
6409 outs() << "r";
6410 else
6411 outs() << "-";
6412 if(mode & S_IWRITE)
6413 outs() << "w";
6414 else
6415 outs() << "-";
6416 if(mode & S_ISUID)
6417 outs() << "s";
6418 else if(mode & S_IEXEC)
6419 outs() << "x";
6420 else
6421 outs() << "-";
6422
6423 /* group permissions */
6424 if(mode & (S_IREAD >> 3))
6425 outs() << "r";
6426 else
6427 outs() << "-";
6428 if(mode & (S_IWRITE >> 3))
6429 outs() << "w";
6430 else
6431 outs() << "-";
6432 if(mode & S_ISGID)
6433 outs() << "s";
6434 else if(mode & (S_IEXEC >> 3))
6435 outs() << "x";
6436 else
6437 outs() << "-";
6438
6439 /* other permissions */
6440 if(mode & (S_IREAD >> 6))
6441 outs() << "r";
6442 else
6443 outs() << "-";
6444 if(mode & (S_IWRITE >> 6))
6445 outs() << "w";
6446 else
6447 outs() << "-";
6448 if(mode & S_ISVTX)
6449 outs() << "t";
6450 else if(mode & (S_IEXEC >> 6))
6451 outs() << "x";
6452 else
6453 outs() << "-";
6454}
6455
6456static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006457 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006458 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6459 char *endp;
6460 uint32_t mode_value;
6461
Francis Ricci6f942972017-10-06 15:33:28 +00006462 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006463 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006464 WithColor::error(errs(), "llvm-objdump")
6465 << "can't obtain an xar iterator for xar archive " << XarFilename
6466 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006467 return;
6468 }
6469
6470 // Go through the xar's files.
6471 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006472 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006473 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006474 WithColor::error(errs(), "llvm-objdump")
6475 << "can't obtain an xar iterator for xar archive " << XarFilename
6476 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006477 return;
6478 }
6479 type = nullptr;
6480 mode = nullptr;
6481 user = nullptr;
6482 group = nullptr;
6483 size = nullptr;
6484 mtime = nullptr;
6485 name = nullptr;
6486 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006487 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006488 xar_prop_get(xf, key, &val);
6489#if 0 // Useful for debugging.
6490 outs() << "key: " << key << " value: " << val << "\n";
6491#endif
6492 if(strcmp(key, "type") == 0)
6493 type = val;
6494 if(strcmp(key, "mode") == 0)
6495 mode = val;
6496 if(strcmp(key, "user") == 0)
6497 user = val;
6498 if(strcmp(key, "group") == 0)
6499 group = val;
6500 if(strcmp(key, "data/size") == 0)
6501 size = val;
6502 if(strcmp(key, "mtime") == 0)
6503 mtime = val;
6504 if(strcmp(key, "name") == 0)
6505 name = val;
6506 }
6507 if(mode != nullptr){
6508 mode_value = strtoul(mode, &endp, 8);
6509 if(*endp != '\0')
6510 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6511 if(strcmp(type, "file") == 0)
6512 mode_value |= S_IFREG;
6513 PrintModeVerbose(mode_value);
6514 outs() << " ";
6515 }
6516 if(user != nullptr)
6517 outs() << format("%10s/", user);
6518 if(group != nullptr)
6519 outs() << format("%-10s ", group);
6520 if(size != nullptr)
6521 outs() << format("%7s ", size);
6522 if(mtime != nullptr){
6523 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6524 outs() << *m;
6525 if(*m == 'T')
6526 m++;
6527 outs() << " ";
6528 for( ; *m != 'Z' && *m != '\0'; m++)
6529 outs() << *m;
6530 outs() << " ";
6531 }
6532 if(name != nullptr)
6533 outs() << name;
6534 outs() << "\n";
6535 }
6536}
6537
6538static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6539 uint32_t size, bool verbose,
6540 bool PrintXarHeader, bool PrintXarFileHeaders,
6541 std::string XarMemberName) {
6542 if(size < sizeof(struct xar_header)) {
6543 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6544 "of struct xar_header)\n";
6545 return;
6546 }
6547 struct xar_header XarHeader;
6548 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6549 if (sys::IsLittleEndianHost)
6550 swapStruct(XarHeader);
6551 if (PrintXarHeader) {
6552 if (!XarMemberName.empty())
6553 outs() << "In xar member " << XarMemberName << ": ";
6554 else
6555 outs() << "For (__LLVM,__bundle) section: ";
6556 outs() << "xar header\n";
6557 if (XarHeader.magic == XAR_HEADER_MAGIC)
6558 outs() << " magic XAR_HEADER_MAGIC\n";
6559 else
6560 outs() << " magic "
6561 << format_hex(XarHeader.magic, 10, true)
6562 << " (not XAR_HEADER_MAGIC)\n";
6563 outs() << " size " << XarHeader.size << "\n";
6564 outs() << " version " << XarHeader.version << "\n";
6565 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6566 << "\n";
6567 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6568 << "\n";
6569 outs() << " cksum_alg ";
6570 switch (XarHeader.cksum_alg) {
6571 case XAR_CKSUM_NONE:
6572 outs() << "XAR_CKSUM_NONE\n";
6573 break;
6574 case XAR_CKSUM_SHA1:
6575 outs() << "XAR_CKSUM_SHA1\n";
6576 break;
6577 case XAR_CKSUM_MD5:
6578 outs() << "XAR_CKSUM_MD5\n";
6579 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006580#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006581 case XAR_CKSUM_SHA256:
6582 outs() << "XAR_CKSUM_SHA256\n";
6583 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006584#endif
6585#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006586 case XAR_CKSUM_SHA512:
6587 outs() << "XAR_CKSUM_SHA512\n";
6588 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006589#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006590 default:
6591 outs() << XarHeader.cksum_alg << "\n";
6592 }
6593 }
6594
6595 SmallString<128> XarFilename;
6596 int FD;
6597 std::error_code XarEC =
6598 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6599 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006600 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006601 return;
6602 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006603 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006604 raw_fd_ostream &XarOut = XarFile.os();
6605 StringRef XarContents(sect, size);
6606 XarOut << XarContents;
6607 XarOut.close();
6608 if (XarOut.has_error())
6609 return;
6610
Francis Ricci6f942972017-10-06 15:33:28 +00006611 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006612 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006613 WithColor::error(errs(), "llvm-objdump")
6614 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006615 return;
6616 }
6617
6618 SmallString<128> TocFilename;
6619 std::error_code TocEC =
6620 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6621 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006622 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006623 return;
6624 }
6625 xar_serialize(xar, TocFilename.c_str());
6626
6627 if (PrintXarFileHeaders) {
6628 if (!XarMemberName.empty())
6629 outs() << "In xar member " << XarMemberName << ": ";
6630 else
6631 outs() << "For (__LLVM,__bundle) section: ";
6632 outs() << "xar archive files:\n";
6633 PrintXarFilesSummary(XarFilename.c_str(), xar);
6634 }
6635
6636 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6637 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6638 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006639 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006640 return;
6641 }
6642 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6643
6644 if (!XarMemberName.empty())
6645 outs() << "In xar member " << XarMemberName << ": ";
6646 else
6647 outs() << "For (__LLVM,__bundle) section: ";
6648 outs() << "xar table of contents:\n";
6649 outs() << Buffer->getBuffer() << "\n";
6650
6651 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006652 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006653 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006654 WithColor::error(errs(), "llvm-objdump")
6655 << "can't obtain an xar iterator for xar archive "
6656 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006657 return;
6658 }
6659 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6660 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006661 const char *member_name, *member_type, *member_size_string;
6662 size_t member_size;
6663
Francis Ricci6f942972017-10-06 15:33:28 +00006664 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006665 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006666 WithColor::error(errs(), "llvm-objdump")
6667 << "can't obtain an xar iterator for xar archive "
6668 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006669 return;
6670 }
6671 member_name = NULL;
6672 member_type = NULL;
6673 member_size_string = NULL;
6674 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006675 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006676 xar_prop_get(xf, key, &val);
6677#if 0 // Useful for debugging.
6678 outs() << "key: " << key << " value: " << val << "\n";
6679#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006680 if (strcmp(key, "name") == 0)
6681 member_name = val;
6682 if (strcmp(key, "type") == 0)
6683 member_type = val;
6684 if (strcmp(key, "data/size") == 0)
6685 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006686 }
6687 /*
6688 * If we find a file with a name, date/size and type properties
6689 * and with the type being "file" see if that is a xar file.
6690 */
6691 if (member_name != NULL && member_type != NULL &&
6692 strcmp(member_type, "file") == 0 &&
6693 member_size_string != NULL){
6694 // Extract the file into a buffer.
6695 char *endptr;
6696 member_size = strtoul(member_size_string, &endptr, 10);
6697 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006698 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006699 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006700#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006701 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006702#endif
6703 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006704 std::string OldXarMemberName;
6705 // If XarMemberName is already set this is nested. So
6706 // save the old name and create the nested name.
6707 if (!XarMemberName.empty()) {
6708 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006709 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006710 (Twine("[") + XarMemberName + "]" + member_name).str();
6711 } else {
6712 OldXarMemberName = "";
6713 XarMemberName = member_name;
6714 }
6715 // See if this is could be a xar file (nested).
6716 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006717#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006718 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006719#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006720 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006721 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006722 swapStruct(XarHeader);
6723 if (XarHeader.magic == XAR_HEADER_MAGIC)
6724 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006725 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006726 XarMemberName);
6727 }
6728 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006729 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006730 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006731 }
6732 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006733 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006734}
6735#endif // defined(HAVE_LIBXAR)
6736
Kevin Enderby0fc11822015-04-01 20:57:01 +00006737static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6738 if (O->is64Bit())
6739 printObjc2_64bit_MetaData(O, verbose);
6740 else {
6741 MachO::mach_header H;
6742 H = O->getHeader();
6743 if (H.cputype == MachO::CPU_TYPE_ARM)
6744 printObjc2_32bit_MetaData(O, verbose);
6745 else {
6746 // This is the 32-bit non-arm cputype case. Which is normally
6747 // the first Objective-C ABI. But it may be the case of a
6748 // binary for the iOS simulator which is the second Objective-C
6749 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6750 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006751 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006752 printObjc2_32bit_MetaData(O, verbose);
6753 }
6754 }
6755}
6756
Kevin Enderbybf246f52014-09-24 23:08:22 +00006757// GuessLiteralPointer returns a string which for the item in the Mach-O file
6758// for the address passed in as ReferenceValue for printing as a comment with
6759// the instruction and also returns the corresponding type of that item
6760// indirectly through ReferenceType.
6761//
6762// If ReferenceValue is an address of literal cstring then a pointer to the
6763// cstring is returned and ReferenceType is set to
6764// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6765//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006766// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6767// Class ref that name is returned and the ReferenceType is set accordingly.
6768//
6769// Lastly, literals which are Symbol address in a literal pool are looked for
6770// and if found the symbol name is returned and ReferenceType is set to
6771// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6772//
6773// If there is no item in the Mach-O file for the address passed in as
6774// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006775static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6776 uint64_t ReferencePC,
6777 uint64_t *ReferenceType,
6778 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006779 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006780 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6781 uint64_t sect_addr = info->S.getAddress();
6782 uint64_t sect_offset = ReferencePC - sect_addr;
6783 bool reloc_found = false;
6784 DataRefImpl Rel;
6785 MachO::any_relocation_info RE;
6786 bool isExtern = false;
6787 SymbolRef Symbol;
6788 for (const RelocationRef &Reloc : info->S.relocations()) {
6789 uint64_t RelocOffset = Reloc.getOffset();
6790 if (RelocOffset == sect_offset) {
6791 Rel = Reloc.getRawDataRefImpl();
6792 RE = info->O->getRelocation(Rel);
6793 if (info->O->isRelocationScattered(RE))
6794 continue;
6795 isExtern = info->O->getPlainRelocationExternal(RE);
6796 if (isExtern) {
6797 symbol_iterator RelocSym = Reloc.getSymbol();
6798 Symbol = *RelocSym;
6799 }
6800 reloc_found = true;
6801 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006802 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006803 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006804 // If there is an external relocation entry for a symbol in a section
6805 // then used that symbol's value for the value of the reference.
6806 if (reloc_found && isExtern) {
6807 if (info->O->getAnyRelocationPCRel(RE)) {
6808 unsigned Type = info->O->getAnyRelocationType(RE);
6809 if (Type == MachO::X86_64_RELOC_SIGNED) {
6810 ReferenceValue = Symbol.getValue();
6811 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006812 }
6813 }
6814 }
6815
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006816 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6817 // Message refs and Class refs.
6818 bool classref, selref, msgref, cfstring;
6819 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6820 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006821 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006822 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6823 // And the pointer_value in that section is typically zero as it will be
6824 // set by dyld as part of the "bind information".
6825 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6826 if (name != nullptr) {
6827 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006828 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006829 if (class_name != nullptr && class_name[1] == '_' &&
6830 class_name[2] != '\0') {
6831 info->class_name = class_name + 2;
6832 return name;
6833 }
6834 }
6835 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006836
David Blaikie33dd45d02015-03-23 18:39:02 +00006837 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006838 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6839 const char *name =
6840 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6841 if (name != nullptr)
6842 info->class_name = name;
6843 else
6844 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006845 return name;
6846 }
6847
David Blaikie33dd45d02015-03-23 18:39:02 +00006848 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006849 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6850 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6851 return name;
6852 }
6853
David Blaikie33dd45d02015-03-23 18:39:02 +00006854 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006855 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6856
6857 if (pointer_value != 0)
6858 ReferenceValue = pointer_value;
6859
6860 const char *name = GuessCstringPointer(ReferenceValue, info);
6861 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006862 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006863 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6864 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006865 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006866 info->class_name = nullptr;
6867 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6868 info->selector_name = name;
6869 } else
6870 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6871 return name;
6872 }
6873
6874 // Lastly look for an indirect symbol with this ReferenceValue which is in
6875 // a literal pool. If found return that symbol name.
6876 name = GuessIndirectSymbol(ReferenceValue, info);
6877 if (name) {
6878 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6879 return name;
6880 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006881
6882 return nullptr;
6883}
6884
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006885// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006886// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006887// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6888// is created and returns the symbol name that matches the ReferenceValue or
6889// nullptr if none. The ReferenceType is passed in for the IN type of
6890// reference the instruction is making from the values in defined in the header
6891// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6892// Out type and the ReferenceName will also be set which is added as a comment
6893// to the disassembled instruction.
6894//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006895// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006896// returned through ReferenceName and ReferenceType is set to
6897// LLVMDisassembler_ReferenceType_DeMangled_Name .
6898//
6899// When this is called to get a symbol name for a branch target then the
6900// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6901// SymbolValue will be looked for in the indirect symbol table to determine if
6902// it is an address for a symbol stub. If so then the symbol name for that
6903// stub is returned indirectly through ReferenceName and then ReferenceType is
6904// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6905//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006906// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006907// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6908// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6909// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006910// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006911static const char *SymbolizerSymbolLookUp(void *DisInfo,
6912 uint64_t ReferenceValue,
6913 uint64_t *ReferenceType,
6914 uint64_t ReferencePC,
6915 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006916 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006917 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006918 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006919 *ReferenceName = nullptr;
6920 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006921 return nullptr;
6922 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006923
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006924 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006925
Kevin Enderby85974882014-09-26 22:20:44 +00006926 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6927 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006928 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006929 method_reference(info, ReferenceType, ReferenceName);
6930 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6931 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006932 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006933 if (info->demangled_name != nullptr)
6934 free(info->demangled_name);
6935 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006936 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006937 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006938 if (info->demangled_name != nullptr) {
6939 *ReferenceName = info->demangled_name;
6940 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6941 } else
6942 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6943 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006944 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6945 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6946 *ReferenceName =
6947 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006948 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006949 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006950 else
6951 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006952 // If this is arm64 and the reference is an adrp instruction save the
6953 // instruction, passed in ReferenceValue and the address of the instruction
6954 // for use later if we see and add immediate instruction.
6955 } else if (info->O->getArch() == Triple::aarch64 &&
6956 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6957 info->adrp_inst = ReferenceValue;
6958 info->adrp_addr = ReferencePC;
6959 SymbolName = nullptr;
6960 *ReferenceName = nullptr;
6961 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6962 // If this is arm64 and reference is an add immediate instruction and we
6963 // have
6964 // seen an adrp instruction just before it and the adrp's Xd register
6965 // matches
6966 // this add's Xn register reconstruct the value being referenced and look to
6967 // see if it is a literal pointer. Note the add immediate instruction is
6968 // passed in ReferenceValue.
6969 } else if (info->O->getArch() == Triple::aarch64 &&
6970 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6971 ReferencePC - 4 == info->adrp_addr &&
6972 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6973 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6974 uint32_t addxri_inst;
6975 uint64_t adrp_imm, addxri_imm;
6976
6977 adrp_imm =
6978 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6979 if (info->adrp_inst & 0x0200000)
6980 adrp_imm |= 0xfffffffffc000000LL;
6981
6982 addxri_inst = ReferenceValue;
6983 addxri_imm = (addxri_inst >> 10) & 0xfff;
6984 if (((addxri_inst >> 22) & 0x3) == 1)
6985 addxri_imm <<= 12;
6986
6987 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6988 (adrp_imm << 12) + addxri_imm;
6989
6990 *ReferenceName =
6991 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6992 if (*ReferenceName == nullptr)
6993 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6994 // If this is arm64 and the reference is a load register instruction and we
6995 // have seen an adrp instruction just before it and the adrp's Xd register
6996 // matches this add's Xn register reconstruct the value being referenced and
6997 // look to see if it is a literal pointer. Note the load register
6998 // instruction is passed in ReferenceValue.
6999 } else if (info->O->getArch() == Triple::aarch64 &&
7000 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7001 ReferencePC - 4 == info->adrp_addr &&
7002 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7003 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7004 uint32_t ldrxui_inst;
7005 uint64_t adrp_imm, ldrxui_imm;
7006
7007 adrp_imm =
7008 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7009 if (info->adrp_inst & 0x0200000)
7010 adrp_imm |= 0xfffffffffc000000LL;
7011
7012 ldrxui_inst = ReferenceValue;
7013 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7014
7015 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7016 (adrp_imm << 12) + (ldrxui_imm << 3);
7017
7018 *ReferenceName =
7019 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7020 if (*ReferenceName == nullptr)
7021 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7022 }
7023 // If this arm64 and is an load register (PC-relative) instruction the
7024 // ReferenceValue is the PC plus the immediate value.
7025 else if (info->O->getArch() == Triple::aarch64 &&
7026 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7027 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7028 *ReferenceName =
7029 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7030 if (*ReferenceName == nullptr)
7031 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00007032 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00007033 if (info->demangled_name != nullptr)
7034 free(info->demangled_name);
7035 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007036 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00007037 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007038 if (info->demangled_name != nullptr) {
7039 *ReferenceName = info->demangled_name;
7040 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7041 }
7042 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007043 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007044 *ReferenceName = nullptr;
7045 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7046 }
7047
7048 return SymbolName;
7049}
7050
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007051/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007052/// Each comment in the CommentStream must end with a newline.
7053static void emitComments(raw_svector_ostream &CommentStream,
7054 SmallString<128> &CommentsToEmit,
7055 formatted_raw_ostream &FormattedOS,
7056 const MCAsmInfo &MAI) {
7057 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007058 StringRef Comments = CommentsToEmit.str();
7059 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00007060 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00007061 unsigned CommentColumn = MAI.getCommentColumn();
7062 bool IsFirst = true;
7063 while (!Comments.empty()) {
7064 if (!IsFirst)
7065 FormattedOS << '\n';
7066 // Emit a line of comments.
7067 FormattedOS.PadToColumn(CommentColumn);
7068 size_t Position = Comments.find('\n');
7069 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7070 // Move after the newline character.
7071 Comments = Comments.substr(Position + 1);
7072 IsFirst = false;
7073 }
7074 FormattedOS.flush();
7075
7076 // Tell the comment stream that the vector changed underneath it.
7077 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007078}
7079
Kevin Enderby95df54c2015-02-04 01:01:38 +00007080static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7081 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007082 const char *McpuDefault = nullptr;
7083 const Target *ThumbTarget = nullptr;
7084 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007085 if (!TheTarget) {
7086 // GetTarget prints out stuff.
7087 return;
7088 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00007089 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007090 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00007091 MachOMCPU = McpuDefault;
7092 else
7093 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007094
Ahmed Charles56440fd2014-03-06 05:51:42 +00007095 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007096 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007097 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007098 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007099
Kevin Enderbyc9595622014-08-06 23:24:41 +00007100 // Package up features to be passed to target/subtarget
7101 std::string FeaturesStr;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007102 if (!MAttrs.empty()) {
Kevin Enderbyc9595622014-08-06 23:24:41 +00007103 SubtargetFeatures Features;
7104 for (unsigned i = 0; i != MAttrs.size(); ++i)
7105 Features.AddFeature(MAttrs[i]);
7106 FeaturesStr = Features.getString();
7107 }
7108
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007109 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00007110 std::unique_ptr<const MCRegisterInfo> MRI(
7111 TheTarget->createMCRegInfo(TripleName));
7112 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00007113 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00007114 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007115 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00007116 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007117 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007118 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007119 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007120 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007121 std::unique_ptr<MCRelocationInfo> RelInfo(
7122 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7123 if (RelInfo) {
7124 Symbolizer.reset(TheTarget->createMCSymbolizer(
7125 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007126 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007127 DisAsm->setSymbolizer(std::move(Symbolizer));
7128 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007129 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00007130 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007131 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007132 // Set the display preference for hex vs. decimal immediates.
7133 IP->setPrintImmHex(PrintImmHex);
7134 // Comment stream and backing vector.
7135 SmallString<128> CommentsToEmit;
7136 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007137 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7138 // if it is done then arm64 comments for string literals don't get printed
7139 // and some constant get printed instead and not setting it causes intel
7140 // (32-bit and 64-bit) comments printed with different spacing before the
7141 // comment causing different diffs with the 'C' disassembler library API.
7142 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007143
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007144 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007145 WithColor::error(errs(), "llvm-objdump")
7146 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007147 return;
7148 }
7149
Tim Northover09ca33e2016-04-22 23:23:31 +00007150 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007151 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7152 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7153 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007154 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007155 std::unique_ptr<MCInstPrinter> ThumbIP;
7156 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007157 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007158 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007159 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007160 if (ThumbTarget) {
7161 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7162 ThumbAsmInfo.reset(
7163 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7164 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007165 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7166 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007167 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7168 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007169 MCContext *PtrThumbCtx = ThumbCtx.get();
7170 ThumbRelInfo.reset(
7171 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7172 if (ThumbRelInfo) {
7173 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7174 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007175 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007176 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7177 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007178 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7179 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007180 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7181 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007182 // Set the display preference for hex vs. decimal immediates.
7183 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007184 }
7185
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007186 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007187 WithColor::error(errs(), "llvm-objdump")
7188 << "couldn't initialize disassembler for target " << ThumbTripleName
7189 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007190 return;
7191 }
7192
Charles Davis8bdfafd2013-09-01 04:28:48 +00007193 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007194
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007195 // FIXME: Using the -cfg command line option, this code used to be able to
7196 // annotate relocations with the referenced symbol's name, and if this was
7197 // inside a __[cf]string section, the data it points to. This is now replaced
7198 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00007199 std::vector<SectionRef> Sections;
7200 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007201 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00007202 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007203
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00007204 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00007205 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007206
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007207 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00007208 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007209
Kevin Enderby273ae012013-06-06 17:20:50 +00007210 // Build a data in code table that is sorted on by the address of each entry.
7211 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00007212 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00007213 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00007214 else
7215 BaseAddress = BaseSegmentAddress;
7216 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00007217 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00007218 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007219 uint32_t Offset;
7220 DI->getOffset(Offset);
7221 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7222 }
7223 array_pod_sort(Dices.begin(), Dices.end());
7224
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007225#ifndef NDEBUG
7226 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7227#else
7228 raw_ostream &DebugOut = nulls();
7229#endif
7230
Ahmed Charles56440fd2014-03-06 05:51:42 +00007231 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00007232 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007233 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00007234 // Try to find debug info and set up the DIContext for it.
7235 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00007236 // A separate DSym file path was specified, parse it as a macho file,
7237 // get the sections and supply it to the section name parsing machinery.
7238 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00007239 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00007240 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00007241 if (std::error_code EC = BufOrErr.getError()) {
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007242 report_error(DSYMFile, errorCodeToError(EC));
Benjamin Kramer699128e2011-09-21 01:13:19 +00007243 return;
7244 }
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007245
Gerolf Hoflehnerbf26d542018-04-19 20:48:35 +00007246 Expected<std::unique_ptr<MachOObjectFile>> DbgObjCheck =
7247 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef());
7248
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007249 if (Error E = DbgObjCheck.takeError()) {
Francis Visoiu Mistrih1b427d42019-01-10 17:16:42 +00007250 report_error(DSYMFile, std::move(E));
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007251 return;
7252 }
Francis Visoiu Mistrih9f4f0112019-01-10 17:16:37 +00007253
Gerolf Hoflehnerbf26d542018-04-19 20:48:35 +00007254 DbgObj = DbgObjCheck.get().release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007255 // We need to keep the file alive, because we're replacing DbgObj with it.
7256 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00007257 }
7258
Eric Christopher7370b552012-11-12 21:40:38 +00007259 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00007260 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007261 }
7262
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007263 if (FilterSections.empty())
Kevin Enderby95df54c2015-02-04 01:01:38 +00007264 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007265
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007266 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00007267 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00007268 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7269 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007270
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007271 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007272
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007273 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007274 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007275 continue;
7276
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007277 StringRef BytesStr;
7278 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00007279 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
7280 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00007281 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007282
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007283 bool symbolTableWorked = false;
7284
Kevin Enderbybf246f52014-09-24 23:08:22 +00007285 // Create a map of symbol addresses to symbol names for use by
7286 // the SymbolizerSymbolLookUp() routine.
7287 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007288 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007289 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007290 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007291 if (!STOrErr)
7292 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007293 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007294 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7295 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007296 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007297 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007298 if (!SymNameOrErr)
7299 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007300 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007301 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007302 if (!DisSymName.empty() && DisSymName == SymName)
7303 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007304 }
7305 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007306 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007307 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7308 return;
7309 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007310 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007311 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007312 SymbolizerInfo.O = MachOOF;
7313 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007314 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007315 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007316 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007317 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007318 ThumbSymbolizerInfo.O = MachOOF;
7319 ThumbSymbolizerInfo.S = Sections[SectIdx];
7320 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7321 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007322
Kevin Enderby4b627be2016-04-28 20:14:13 +00007323 unsigned int Arch = MachOOF->getArch();
7324
Tim Northoverf203ab52016-07-14 22:13:32 +00007325 // Skip all symbols if this is a stubs file.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007326 if (Bytes.empty())
Tim Northoverf203ab52016-07-14 22:13:32 +00007327 return;
7328
Kevin Enderbyc138da32017-02-06 18:43:18 +00007329 // If the section has symbols but no symbol at the start of the section
7330 // these are used to make sure the bytes before the first symbol are
7331 // disassembled.
7332 bool FirstSymbol = true;
7333 bool FirstSymbolAtSectionStart = true;
7334
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007335 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007336 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007337 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007338 if (!SymNameOrErr)
7339 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007340 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007341
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007342 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007343 if (!STOrErr)
7344 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007345 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007346 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007347 continue;
7348
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007349 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007350 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007351 if (!containsSym) {
7352 if (!DisSymName.empty() && DisSymName == SymName) {
7353 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7354 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007355 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007356 continue;
7357 }
7358 // The __mh_execute_header is special and we need to deal with that fact
7359 // this symbol is before the start of the (__TEXT,__text) section and at the
7360 // address of the start of the __TEXT segment. This is because this symbol
7361 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7362 // start of the section in a standard MH_EXECUTE filetype.
7363 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7364 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7365 return;
7366 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007367 // When this code is trying to disassemble a symbol at a time and in the
7368 // case there is only the __mh_execute_header symbol left as in a stripped
7369 // executable, we need to deal with this by ignoring this symbol so the
7370 // whole section is disassembled and this symbol is then not displayed.
7371 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7372 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7373 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007374 continue;
7375
Kevin Enderby6a221752015-03-17 17:10:57 +00007376 // If we are only disassembling one symbol see if this is that symbol.
7377 if (!DisSymName.empty() && DisSymName != SymName)
7378 continue;
7379
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007380 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007381 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007382 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007383 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007384 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007385
Tim Northoverf203ab52016-07-14 22:13:32 +00007386 if (Start > SectSize) {
7387 outs() << "section data ends, " << SymName
7388 << " lies outside valid range\n";
7389 return;
7390 }
7391
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007392 // Stop disassembling either at the beginning of the next symbol or at
7393 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007394 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007395 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007396 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007397 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007398 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007399 if (!STOrErr)
7400 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007401 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007402 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007403 containsNextSym =
7404 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007405 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007406 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007407 break;
7408 }
7409 ++NextSymIdx;
7410 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007411
Tim Northoverf203ab52016-07-14 22:13:32 +00007412 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007413 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007414
7415 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007416
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007417 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007418 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7419
7420 // We only need the dedicated Thumb target if there's a real choice
7421 // (i.e. we're not targeting M-class) and the function is Thumb.
7422 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007423
Kevin Enderbyc138da32017-02-06 18:43:18 +00007424 // If we are not specifying a symbol to start disassembly with and this
7425 // is the first symbol in the section but not at the start of the section
7426 // then move the disassembly index to the start of the section and
7427 // don't print the symbol name just yet. This is so the bytes before the
7428 // first symbol are disassembled.
7429 uint64_t SymbolStart = Start;
7430 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7431 FirstSymbolAtSectionStart = false;
7432 Start = 0;
7433 }
7434 else
7435 outs() << SymName << ":\n";
7436
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007437 DILineInfo lastLine;
7438 for (uint64_t Index = Start; Index < End; Index += Size) {
7439 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007440
Kevin Enderbyc138da32017-02-06 18:43:18 +00007441 // If this is the first symbol in the section and it was not at the
7442 // start of the section, see if we are at its Index now and if so print
7443 // the symbol name.
7444 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7445 outs() << SymName << ":\n";
7446
Kevin Enderbybf246f52014-09-24 23:08:22 +00007447 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007448 if (!NoLeadingAddr) {
7449 if (FullLeadingAddr) {
7450 if (MachOOF->is64Bit())
7451 outs() << format("%016" PRIx64, PC);
7452 else
7453 outs() << format("%08" PRIx64, PC);
7454 } else {
7455 outs() << format("%8" PRIx64 ":", PC);
7456 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007457 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007458 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007459 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007460
7461 // Check the data in code table here to see if this is data not an
7462 // instruction to be disassembled.
7463 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007464 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007465 dice_table_iterator DTI =
7466 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7467 compareDiceTableEntries);
7468 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007469 uint16_t Length;
7470 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007471 uint16_t Kind;
7472 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007473 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007474 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7475 (PC == (DTI->first + Length - 1)) && (Length & 1))
7476 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007477 continue;
7478 }
7479
Kevin Enderbybf246f52014-09-24 23:08:22 +00007480 SmallVector<char, 64> AnnotationsBytes;
7481 raw_svector_ostream Annotations(AnnotationsBytes);
7482
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007483 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007484 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007485 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007486 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007487 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007488 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007489 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007490 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007491 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007492 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007493 }
7494 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007495 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007496 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007497 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007498 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007499 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007500 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007501
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007502 // Print debug info.
7503 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007504 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007505 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007506 if (dli != lastLine && dli.Line != 0)
7507 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7508 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007509 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007510 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007511 outs() << "\n";
7512 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007513 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007514 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007515 outs() << format("\t.byte 0x%02x #bad opcode\n",
7516 *(Bytes.data() + Index) & 0xff);
7517 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007518 } else if (Arch == Triple::aarch64 ||
7519 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007520 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7521 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7522 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7523 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7524 outs() << format("\t.long\t0x%08x\n", opcode);
7525 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007526 } else if (Arch == Triple::arm) {
7527 assert(IsThumb && "ARM mode should have been dealt with above");
7528 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7529 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7530 outs() << format("\t.short\t0x%04x\n", opcode);
7531 Size = 2;
7532 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007533 WithColor::warning(errs(), "llvm-objdump")
7534 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007535 if (Size == 0)
7536 Size = 1; // skip illegible bytes
7537 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007538 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007539 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007540 // Now that we are done disassembled the first symbol set the bool that
7541 // were doing this to false.
7542 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007543 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007544 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007545 // Reading the symbol table didn't work, disassemble the whole section.
7546 uint64_t SectAddress = Sections[SectIdx].getAddress();
7547 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007548 uint64_t InstSize;
7549 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007550 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007551
Kevin Enderbybf246f52014-09-24 23:08:22 +00007552 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007553 SmallVector<char, 64> AnnotationsBytes;
7554 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007555 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007556 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007557 if (!NoLeadingAddr) {
7558 if (FullLeadingAddr) {
7559 if (MachOOF->is64Bit())
7560 outs() << format("%016" PRIx64, PC);
7561 else
7562 outs() << format("%08" PRIx64, PC);
7563 } else {
7564 outs() << format("%8" PRIx64 ":", PC);
7565 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007566 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007567 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007568 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007569 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007570 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007571 StringRef AnnotationsStr = Annotations.str();
7572 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007573 outs() << "\n";
7574 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007575 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007576 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007577 outs() << format("\t.byte 0x%02x #bad opcode\n",
7578 *(Bytes.data() + Index) & 0xff);
7579 InstSize = 1; // skip exactly one illegible byte and move on.
7580 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007581 WithColor::warning(errs(), "llvm-objdump")
7582 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007583 if (InstSize == 0)
7584 InstSize = 1; // skip illegible bytes
7585 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007586 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007587 }
7588 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007589 // The TripleName's need to be reset if we are called again for a different
7590 // archtecture.
7591 TripleName = "";
7592 ThumbTripleName = "";
7593
Kevin Enderby04bf6932014-10-28 23:39:46 +00007594 if (SymbolizerInfo.demangled_name != nullptr)
7595 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007596 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7597 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007598 }
7599}
Tim Northover4bd286a2014-08-01 13:07:19 +00007600
Tim Northover39c70bb2014-08-12 11:52:59 +00007601//===----------------------------------------------------------------------===//
7602// __compact_unwind section dumping
7603//===----------------------------------------------------------------------===//
7604
Tim Northover4bd286a2014-08-01 13:07:19 +00007605namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007606
Tim Northover3a4e1c72018-01-23 13:51:57 +00007607template <typename T>
7608static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007609 using llvm::support::little;
7610 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007611
Tim Northover3a4e1c72018-01-23 13:51:57 +00007612 if (Offset + sizeof(T) > Contents.size()) {
7613 outs() << "warning: attempt to read past end of buffer\n";
7614 return T();
7615 }
7616
7617 uint64_t Val =
7618 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7619 return Val;
7620}
7621
7622template <typename T>
7623static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7624 T Val = read<T>(Contents, Offset);
7625 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007626 return Val;
7627}
Tim Northover39c70bb2014-08-12 11:52:59 +00007628
Tim Northover4bd286a2014-08-01 13:07:19 +00007629struct CompactUnwindEntry {
7630 uint32_t OffsetInSection;
7631
7632 uint64_t FunctionAddr;
7633 uint32_t Length;
7634 uint32_t CompactEncoding;
7635 uint64_t PersonalityAddr;
7636 uint64_t LSDAAddr;
7637
7638 RelocationRef FunctionReloc;
7639 RelocationRef PersonalityReloc;
7640 RelocationRef LSDAReloc;
7641
7642 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007643 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007644 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007645 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007646 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007647 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007648 }
7649
7650private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007651 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7652 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7653 Length = readNext<uint32_t>(Contents, Offset);
7654 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7655 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7656 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007657 }
7658};
7659}
7660
7661/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7662/// and data being relocated, determine the best base Name and Addend to use for
7663/// display purposes.
7664///
7665/// 1. An Extern relocation will directly reference a symbol (and the data is
7666/// then already an addend), so use that.
7667/// 2. Otherwise the data is an offset in the object file's layout; try to find
7668// a symbol before it in the same section, and use the offset from there.
7669/// 3. Finally, if all that fails, fall back to an offset from the start of the
7670/// referenced section.
7671static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7672 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007673 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007674 StringRef &Name, uint64_t &Addend) {
7675 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007676 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007677 if (!NameOrErr)
7678 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007679 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007680 Addend = Addr;
7681 return;
7682 }
7683
7684 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007685 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007686
Rafael Espindola80291272014-10-08 15:28:58 +00007687 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007688
7689 auto Sym = Symbols.upper_bound(Addr);
7690 if (Sym == Symbols.begin()) {
7691 // The first symbol in the object is after this reference, the best we can
7692 // do is section-relative notation.
7693 RelocSection.getName(Name);
7694 Addend = Addr - SectionAddr;
7695 return;
7696 }
7697
7698 // Go back one so that SymbolAddress <= Addr.
7699 --Sym;
7700
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007701 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007702 if (!SectOrErr)
7703 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007704 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007705 if (RelocSection == *SymSection) {
7706 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007707 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007708 if (!NameOrErr)
7709 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007710 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007711 Addend = Addr - Sym->first;
7712 return;
7713 }
7714
7715 // There is a symbol before this reference, but it's in a different
7716 // section. Probably not helpful to mention it, so use the section name.
7717 RelocSection.getName(Name);
7718 Addend = Addr - SectionAddr;
7719}
7720
7721static void printUnwindRelocDest(const MachOObjectFile *Obj,
7722 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007723 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007724 StringRef Name;
7725 uint64_t Addend;
7726
Rafael Espindola854038e2015-06-26 14:51:16 +00007727 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007728 return;
7729
Tim Northover4bd286a2014-08-01 13:07:19 +00007730 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7731
7732 outs() << Name;
7733 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007734 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007735}
7736
7737static void
7738printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7739 std::map<uint64_t, SymbolRef> &Symbols,
7740 const SectionRef &CompactUnwind) {
7741
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007742 if (!Obj->isLittleEndian()) {
7743 outs() << "Skipping big-endian __compact_unwind section\n";
7744 return;
7745 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007746
7747 bool Is64 = Obj->is64Bit();
7748 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7749 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7750
7751 StringRef Contents;
7752 CompactUnwind.getContents(Contents);
7753
7754 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7755
7756 // First populate the initial raw offsets, encodings and so on from the entry.
7757 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007758 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007759 CompactUnwinds.push_back(Entry);
7760 }
7761
7762 // Next we need to look at the relocations to find out what objects are
7763 // actually being referred to.
7764 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007765 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007766
7767 uint32_t EntryIdx = RelocAddress / EntrySize;
7768 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7769 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7770
7771 if (OffsetInEntry == 0)
7772 Entry.FunctionReloc = Reloc;
7773 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7774 Entry.PersonalityReloc = Reloc;
7775 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7776 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007777 else {
7778 outs() << "Invalid relocation in __compact_unwind section\n";
7779 return;
7780 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007781 }
7782
7783 // Finally, we're ready to print the data we've gathered.
7784 outs() << "Contents of __compact_unwind section:\n";
7785 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007786 outs() << " Entry at offset "
7787 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007788
7789 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007790 outs() << " start: " << format("0x%" PRIx64,
7791 Entry.FunctionAddr) << ' ';
7792 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007793 outs() << '\n';
7794
7795 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007796 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7797 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007798 // 3. The 32-bit compact encoding.
7799 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007800 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007801
7802 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007803 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007804 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007805 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007806 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7807 Entry.PersonalityAddr);
7808 outs() << '\n';
7809 }
7810
7811 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007812 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007813 outs() << " LSDA: " << format("0x%" PRIx64,
7814 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007815 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7816 outs() << '\n';
7817 }
7818 }
7819}
7820
Tim Northover39c70bb2014-08-12 11:52:59 +00007821//===----------------------------------------------------------------------===//
7822// __unwind_info section dumping
7823//===----------------------------------------------------------------------===//
7824
Tim Northover3a4e1c72018-01-23 13:51:57 +00007825static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7826 ptrdiff_t Pos = 0;
7827 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007828 (void)Kind;
7829 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7830
Tim Northover3a4e1c72018-01-23 13:51:57 +00007831 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7832 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007833
Tim Northover3a4e1c72018-01-23 13:51:57 +00007834 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007835 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007836 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7837 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007838
7839 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007840 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7841 << ", "
7842 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007843 }
7844}
7845
7846static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007847 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007848 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007849 ptrdiff_t Pos = 0;
7850 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007851 (void)Kind;
7852 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7853
Tim Northover3a4e1c72018-01-23 13:51:57 +00007854 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7855 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007856
Tim Northover3a4e1c72018-01-23 13:51:57 +00007857 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7858 readNext<uint16_t>(PageData, Pos);
7859 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007860
Tim Northover3a4e1c72018-01-23 13:51:57 +00007861 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007862 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007863 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007864 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7865 uint32_t EncodingIdx = Entry >> 24;
7866
7867 uint32_t Encoding;
7868 if (EncodingIdx < CommonEncodings.size())
7869 Encoding = CommonEncodings[EncodingIdx];
7870 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007871 Encoding = read<uint32_t>(PageEncodings,
7872 sizeof(uint32_t) *
7873 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007874
7875 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007876 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7877 << ", "
7878 << "encoding[" << EncodingIdx
7879 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007880 }
7881}
7882
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007883static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7884 std::map<uint64_t, SymbolRef> &Symbols,
7885 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007886
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007887 if (!Obj->isLittleEndian()) {
7888 outs() << "Skipping big-endian __unwind_info section\n";
7889 return;
7890 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007891
7892 outs() << "Contents of __unwind_info section:\n";
7893
7894 StringRef Contents;
7895 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007896 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007897
7898 //===----------------------------------
7899 // Section header
7900 //===----------------------------------
7901
Tim Northover3a4e1c72018-01-23 13:51:57 +00007902 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007903 outs() << " Version: "
7904 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007905 if (Version != 1) {
7906 outs() << " Skipping section with unknown version\n";
7907 return;
7908 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007909
Tim Northover3a4e1c72018-01-23 13:51:57 +00007910 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007911 outs() << " Common encodings array section offset: "
7912 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007913 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007914 outs() << " Number of common encodings in array: "
7915 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7916
Tim Northover3a4e1c72018-01-23 13:51:57 +00007917 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007918 outs() << " Personality function array section offset: "
7919 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007920 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007921 outs() << " Number of personality functions in array: "
7922 << format("0x%" PRIx32, NumPersonalities) << '\n';
7923
Tim Northover3a4e1c72018-01-23 13:51:57 +00007924 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007925 outs() << " Index array section offset: "
7926 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007927 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007928 outs() << " Number of indices in array: "
7929 << format("0x%" PRIx32, NumIndices) << '\n';
7930
7931 //===----------------------------------
7932 // A shared list of common encodings
7933 //===----------------------------------
7934
7935 // These occupy indices in the range [0, N] whenever an encoding is referenced
7936 // from a compressed 2nd level index table. In practice the linker only
7937 // creates ~128 of these, so that indices are available to embed encodings in
7938 // the 2nd level index.
7939
7940 SmallVector<uint32_t, 64> CommonEncodings;
7941 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007942 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007943 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007944 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007945 CommonEncodings.push_back(Encoding);
7946
7947 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7948 << '\n';
7949 }
7950
Tim Northover39c70bb2014-08-12 11:52:59 +00007951 //===----------------------------------
7952 // Personality functions used in this executable
7953 //===----------------------------------
7954
7955 // There should be only a handful of these (one per source language,
7956 // roughly). Particularly since they only get 2 bits in the compact encoding.
7957
7958 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007959 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007960 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007961 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007962 outs() << " personality[" << i + 1
7963 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7964 }
7965
7966 //===----------------------------------
7967 // The level 1 index entries
7968 //===----------------------------------
7969
7970 // These specify an approximate place to start searching for the more detailed
7971 // information, sorted by PC.
7972
7973 struct IndexEntry {
7974 uint32_t FunctionOffset;
7975 uint32_t SecondLevelPageStart;
7976 uint32_t LSDAStart;
7977 };
7978
7979 SmallVector<IndexEntry, 4> IndexEntries;
7980
7981 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007982 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007983 for (unsigned i = 0; i < NumIndices; ++i) {
7984 IndexEntry Entry;
7985
Tim Northover3a4e1c72018-01-23 13:51:57 +00007986 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7987 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7988 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007989 IndexEntries.push_back(Entry);
7990
7991 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007992 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7993 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007994 << "2nd level page offset="
7995 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007996 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007997 }
7998
Tim Northover39c70bb2014-08-12 11:52:59 +00007999 //===----------------------------------
8000 // Next come the LSDA tables
8001 //===----------------------------------
8002
8003 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8004 // the first top-level index's LSDAOffset to the last (sentinel).
8005
8006 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00008007 Pos = IndexEntries[0].LSDAStart;
8008 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8009 int NumLSDAs =
8010 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8011
Tim Northover39c70bb2014-08-12 11:52:59 +00008012 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00008013 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8014 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008015 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008016 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8017 << ", "
8018 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00008019 }
8020
8021 //===----------------------------------
8022 // Finally, the 2nd level indices
8023 //===----------------------------------
8024
8025 // Generally these are 4K in size, and have 2 possible forms:
8026 // + Regular stores up to 511 entries with disparate encodings
8027 // + Compressed stores up to 1021 entries if few enough compact encoding
8028 // values are used.
8029 outs() << " Second level indices:\n";
8030 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8031 // The final sentinel top-level index has no associated 2nd level page
8032 if (IndexEntries[i].SecondLevelPageStart == 0)
8033 break;
8034
8035 outs() << " Second level index[" << i << "]: "
8036 << "offset in section="
8037 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8038 << ", "
8039 << "base function offset="
8040 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8041
Tim Northover3a4e1c72018-01-23 13:51:57 +00008042 Pos = IndexEntries[i].SecondLevelPageStart;
8043 if (Pos + sizeof(uint32_t) > Contents.size()) {
8044 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8045 continue;
8046 }
8047
8048 uint32_t Kind =
8049 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008050 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00008051 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00008052 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00008053 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8054 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00008055 CommonEncodings);
8056 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00008057 outs() << " Skipping 2nd level page with unknown kind " << Kind
8058 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00008059 }
8060}
8061
Tim Northover4bd286a2014-08-01 13:07:19 +00008062void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8063 std::map<uint64_t, SymbolRef> Symbols;
8064 for (const SymbolRef &SymRef : Obj->symbols()) {
8065 // Discard any undefined or absolute symbols. They're not going to take part
8066 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00008067 auto SectOrErr = SymRef.getSection();
8068 if (!SectOrErr) {
8069 // TODO: Actually report errors helpfully.
8070 consumeError(SectOrErr.takeError());
8071 continue;
8072 }
8073 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00008074 if (Section == Obj->section_end())
8075 continue;
8076
Rafael Espindoladea00162015-07-03 17:44:18 +00008077 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00008078 Symbols.insert(std::make_pair(Addr, SymRef));
8079 }
8080
8081 for (const SectionRef &Section : Obj->sections()) {
8082 StringRef SectName;
8083 Section.getName(SectName);
8084 if (SectName == "__compact_unwind")
8085 printMachOCompactUnwindSection(Obj, Symbols, Section);
8086 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00008087 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00008088 }
8089}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008090
8091static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8092 uint32_t cpusubtype, uint32_t filetype,
8093 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8094 bool verbose) {
8095 outs() << "Mach header\n";
8096 outs() << " magic cputype cpusubtype caps filetype ncmds "
8097 "sizeofcmds flags\n";
8098 if (verbose) {
8099 if (magic == MachO::MH_MAGIC)
8100 outs() << " MH_MAGIC";
8101 else if (magic == MachO::MH_MAGIC_64)
8102 outs() << "MH_MAGIC_64";
8103 else
8104 outs() << format(" 0x%08" PRIx32, magic);
8105 switch (cputype) {
8106 case MachO::CPU_TYPE_I386:
8107 outs() << " I386";
8108 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8109 case MachO::CPU_SUBTYPE_I386_ALL:
8110 outs() << " ALL";
8111 break;
8112 default:
8113 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8114 break;
8115 }
8116 break;
8117 case MachO::CPU_TYPE_X86_64:
8118 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00008119 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8120 case MachO::CPU_SUBTYPE_X86_64_ALL:
8121 outs() << " ALL";
8122 break;
8123 case MachO::CPU_SUBTYPE_X86_64_H:
8124 outs() << " Haswell";
8125 break;
8126 default:
8127 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8128 break;
8129 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008130 break;
8131 case MachO::CPU_TYPE_ARM:
8132 outs() << " ARM";
8133 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8134 case MachO::CPU_SUBTYPE_ARM_ALL:
8135 outs() << " ALL";
8136 break;
8137 case MachO::CPU_SUBTYPE_ARM_V4T:
8138 outs() << " V4T";
8139 break;
8140 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8141 outs() << " V5TEJ";
8142 break;
8143 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8144 outs() << " XSCALE";
8145 break;
8146 case MachO::CPU_SUBTYPE_ARM_V6:
8147 outs() << " V6";
8148 break;
8149 case MachO::CPU_SUBTYPE_ARM_V6M:
8150 outs() << " V6M";
8151 break;
8152 case MachO::CPU_SUBTYPE_ARM_V7:
8153 outs() << " V7";
8154 break;
8155 case MachO::CPU_SUBTYPE_ARM_V7EM:
8156 outs() << " V7EM";
8157 break;
8158 case MachO::CPU_SUBTYPE_ARM_V7K:
8159 outs() << " V7K";
8160 break;
8161 case MachO::CPU_SUBTYPE_ARM_V7M:
8162 outs() << " V7M";
8163 break;
8164 case MachO::CPU_SUBTYPE_ARM_V7S:
8165 outs() << " V7S";
8166 break;
8167 default:
8168 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8169 break;
8170 }
8171 break;
8172 case MachO::CPU_TYPE_ARM64:
8173 outs() << " ARM64";
8174 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8175 case MachO::CPU_SUBTYPE_ARM64_ALL:
8176 outs() << " ALL";
8177 break;
8178 default:
8179 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8180 break;
8181 }
8182 break;
8183 case MachO::CPU_TYPE_POWERPC:
8184 outs() << " PPC";
8185 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8186 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8187 outs() << " ALL";
8188 break;
8189 default:
8190 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8191 break;
8192 }
8193 break;
8194 case MachO::CPU_TYPE_POWERPC64:
8195 outs() << " PPC64";
8196 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8197 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8198 outs() << " ALL";
8199 break;
8200 default:
8201 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8202 break;
8203 }
8204 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00008205 default:
8206 outs() << format(" %7d", cputype);
8207 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8208 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008209 }
8210 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008211 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008212 } else {
8213 outs() << format(" 0x%02" PRIx32,
8214 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8215 }
8216 switch (filetype) {
8217 case MachO::MH_OBJECT:
8218 outs() << " OBJECT";
8219 break;
8220 case MachO::MH_EXECUTE:
8221 outs() << " EXECUTE";
8222 break;
8223 case MachO::MH_FVMLIB:
8224 outs() << " FVMLIB";
8225 break;
8226 case MachO::MH_CORE:
8227 outs() << " CORE";
8228 break;
8229 case MachO::MH_PRELOAD:
8230 outs() << " PRELOAD";
8231 break;
8232 case MachO::MH_DYLIB:
8233 outs() << " DYLIB";
8234 break;
8235 case MachO::MH_DYLIB_STUB:
8236 outs() << " DYLIB_STUB";
8237 break;
8238 case MachO::MH_DYLINKER:
8239 outs() << " DYLINKER";
8240 break;
8241 case MachO::MH_BUNDLE:
8242 outs() << " BUNDLE";
8243 break;
8244 case MachO::MH_DSYM:
8245 outs() << " DSYM";
8246 break;
8247 case MachO::MH_KEXT_BUNDLE:
8248 outs() << " KEXTBUNDLE";
8249 break;
8250 default:
8251 outs() << format(" %10u", filetype);
8252 break;
8253 }
8254 outs() << format(" %5u", ncmds);
8255 outs() << format(" %10u", sizeofcmds);
8256 uint32_t f = flags;
8257 if (f & MachO::MH_NOUNDEFS) {
8258 outs() << " NOUNDEFS";
8259 f &= ~MachO::MH_NOUNDEFS;
8260 }
8261 if (f & MachO::MH_INCRLINK) {
8262 outs() << " INCRLINK";
8263 f &= ~MachO::MH_INCRLINK;
8264 }
8265 if (f & MachO::MH_DYLDLINK) {
8266 outs() << " DYLDLINK";
8267 f &= ~MachO::MH_DYLDLINK;
8268 }
8269 if (f & MachO::MH_BINDATLOAD) {
8270 outs() << " BINDATLOAD";
8271 f &= ~MachO::MH_BINDATLOAD;
8272 }
8273 if (f & MachO::MH_PREBOUND) {
8274 outs() << " PREBOUND";
8275 f &= ~MachO::MH_PREBOUND;
8276 }
8277 if (f & MachO::MH_SPLIT_SEGS) {
8278 outs() << " SPLIT_SEGS";
8279 f &= ~MachO::MH_SPLIT_SEGS;
8280 }
8281 if (f & MachO::MH_LAZY_INIT) {
8282 outs() << " LAZY_INIT";
8283 f &= ~MachO::MH_LAZY_INIT;
8284 }
8285 if (f & MachO::MH_TWOLEVEL) {
8286 outs() << " TWOLEVEL";
8287 f &= ~MachO::MH_TWOLEVEL;
8288 }
8289 if (f & MachO::MH_FORCE_FLAT) {
8290 outs() << " FORCE_FLAT";
8291 f &= ~MachO::MH_FORCE_FLAT;
8292 }
8293 if (f & MachO::MH_NOMULTIDEFS) {
8294 outs() << " NOMULTIDEFS";
8295 f &= ~MachO::MH_NOMULTIDEFS;
8296 }
8297 if (f & MachO::MH_NOFIXPREBINDING) {
8298 outs() << " NOFIXPREBINDING";
8299 f &= ~MachO::MH_NOFIXPREBINDING;
8300 }
8301 if (f & MachO::MH_PREBINDABLE) {
8302 outs() << " PREBINDABLE";
8303 f &= ~MachO::MH_PREBINDABLE;
8304 }
8305 if (f & MachO::MH_ALLMODSBOUND) {
8306 outs() << " ALLMODSBOUND";
8307 f &= ~MachO::MH_ALLMODSBOUND;
8308 }
8309 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8310 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8311 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8312 }
8313 if (f & MachO::MH_CANONICAL) {
8314 outs() << " CANONICAL";
8315 f &= ~MachO::MH_CANONICAL;
8316 }
8317 if (f & MachO::MH_WEAK_DEFINES) {
8318 outs() << " WEAK_DEFINES";
8319 f &= ~MachO::MH_WEAK_DEFINES;
8320 }
8321 if (f & MachO::MH_BINDS_TO_WEAK) {
8322 outs() << " BINDS_TO_WEAK";
8323 f &= ~MachO::MH_BINDS_TO_WEAK;
8324 }
8325 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8326 outs() << " ALLOW_STACK_EXECUTION";
8327 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8328 }
8329 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8330 outs() << " DEAD_STRIPPABLE_DYLIB";
8331 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8332 }
8333 if (f & MachO::MH_PIE) {
8334 outs() << " PIE";
8335 f &= ~MachO::MH_PIE;
8336 }
8337 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8338 outs() << " NO_REEXPORTED_DYLIBS";
8339 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8340 }
8341 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8342 outs() << " MH_HAS_TLV_DESCRIPTORS";
8343 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8344 }
8345 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8346 outs() << " MH_NO_HEAP_EXECUTION";
8347 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8348 }
8349 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8350 outs() << " APP_EXTENSION_SAFE";
8351 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8352 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008353 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8354 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8355 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8356 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008357 if (f != 0 || flags == 0)
8358 outs() << format(" 0x%08" PRIx32, f);
8359 } else {
8360 outs() << format(" 0x%08" PRIx32, magic);
8361 outs() << format(" %7d", cputype);
8362 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8363 outs() << format(" 0x%02" PRIx32,
8364 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8365 outs() << format(" %10u", filetype);
8366 outs() << format(" %5u", ncmds);
8367 outs() << format(" %10u", sizeofcmds);
8368 outs() << format(" 0x%08" PRIx32, flags);
8369 }
8370 outs() << "\n";
8371}
8372
Kevin Enderby956366c2014-08-29 22:30:52 +00008373static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8374 StringRef SegName, uint64_t vmaddr,
8375 uint64_t vmsize, uint64_t fileoff,
8376 uint64_t filesize, uint32_t maxprot,
8377 uint32_t initprot, uint32_t nsects,
8378 uint32_t flags, uint32_t object_size,
8379 bool verbose) {
8380 uint64_t expected_cmdsize;
8381 if (cmd == MachO::LC_SEGMENT) {
8382 outs() << " cmd LC_SEGMENT\n";
8383 expected_cmdsize = nsects;
8384 expected_cmdsize *= sizeof(struct MachO::section);
8385 expected_cmdsize += sizeof(struct MachO::segment_command);
8386 } else {
8387 outs() << " cmd LC_SEGMENT_64\n";
8388 expected_cmdsize = nsects;
8389 expected_cmdsize *= sizeof(struct MachO::section_64);
8390 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8391 }
8392 outs() << " cmdsize " << cmdsize;
8393 if (cmdsize != expected_cmdsize)
8394 outs() << " Inconsistent size\n";
8395 else
8396 outs() << "\n";
8397 outs() << " segname " << SegName << "\n";
8398 if (cmd == MachO::LC_SEGMENT_64) {
8399 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8400 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8401 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008402 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8403 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008404 }
8405 outs() << " fileoff " << fileoff;
8406 if (fileoff > object_size)
8407 outs() << " (past end of file)\n";
8408 else
8409 outs() << "\n";
8410 outs() << " filesize " << filesize;
8411 if (fileoff + filesize > object_size)
8412 outs() << " (past end of file)\n";
8413 else
8414 outs() << "\n";
8415 if (verbose) {
8416 if ((maxprot &
8417 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8418 MachO::VM_PROT_EXECUTE)) != 0)
8419 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8420 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008421 outs() << " maxprot ";
8422 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8423 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8424 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008425 }
8426 if ((initprot &
8427 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8428 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008429 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008430 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008431 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008432 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8433 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8434 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008435 }
8436 } else {
8437 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8438 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8439 }
8440 outs() << " nsects " << nsects << "\n";
8441 if (verbose) {
8442 outs() << " flags";
8443 if (flags == 0)
8444 outs() << " (none)\n";
8445 else {
8446 if (flags & MachO::SG_HIGHVM) {
8447 outs() << " HIGHVM";
8448 flags &= ~MachO::SG_HIGHVM;
8449 }
8450 if (flags & MachO::SG_FVMLIB) {
8451 outs() << " FVMLIB";
8452 flags &= ~MachO::SG_FVMLIB;
8453 }
8454 if (flags & MachO::SG_NORELOC) {
8455 outs() << " NORELOC";
8456 flags &= ~MachO::SG_NORELOC;
8457 }
8458 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8459 outs() << " PROTECTED_VERSION_1";
8460 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8461 }
8462 if (flags)
8463 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8464 else
8465 outs() << "\n";
8466 }
8467 } else {
8468 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8469 }
8470}
8471
8472static void PrintSection(const char *sectname, const char *segname,
8473 uint64_t addr, uint64_t size, uint32_t offset,
8474 uint32_t align, uint32_t reloff, uint32_t nreloc,
8475 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8476 uint32_t cmd, const char *sg_segname,
8477 uint32_t filetype, uint32_t object_size,
8478 bool verbose) {
8479 outs() << "Section\n";
8480 outs() << " sectname " << format("%.16s\n", sectname);
8481 outs() << " segname " << format("%.16s", segname);
8482 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8483 outs() << " (does not match segment)\n";
8484 else
8485 outs() << "\n";
8486 if (cmd == MachO::LC_SEGMENT_64) {
8487 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8488 outs() << " size " << format("0x%016" PRIx64, size);
8489 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008490 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8491 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008492 }
8493 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8494 outs() << " (past end of file)\n";
8495 else
8496 outs() << "\n";
8497 outs() << " offset " << offset;
8498 if (offset > object_size)
8499 outs() << " (past end of file)\n";
8500 else
8501 outs() << "\n";
8502 uint32_t align_shifted = 1 << align;
8503 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8504 outs() << " reloff " << reloff;
8505 if (reloff > object_size)
8506 outs() << " (past end of file)\n";
8507 else
8508 outs() << "\n";
8509 outs() << " nreloc " << nreloc;
8510 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8511 outs() << " (past end of file)\n";
8512 else
8513 outs() << "\n";
8514 uint32_t section_type = flags & MachO::SECTION_TYPE;
8515 if (verbose) {
8516 outs() << " type";
8517 if (section_type == MachO::S_REGULAR)
8518 outs() << " S_REGULAR\n";
8519 else if (section_type == MachO::S_ZEROFILL)
8520 outs() << " S_ZEROFILL\n";
8521 else if (section_type == MachO::S_CSTRING_LITERALS)
8522 outs() << " S_CSTRING_LITERALS\n";
8523 else if (section_type == MachO::S_4BYTE_LITERALS)
8524 outs() << " S_4BYTE_LITERALS\n";
8525 else if (section_type == MachO::S_8BYTE_LITERALS)
8526 outs() << " S_8BYTE_LITERALS\n";
8527 else if (section_type == MachO::S_16BYTE_LITERALS)
8528 outs() << " S_16BYTE_LITERALS\n";
8529 else if (section_type == MachO::S_LITERAL_POINTERS)
8530 outs() << " S_LITERAL_POINTERS\n";
8531 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8532 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8533 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8534 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8535 else if (section_type == MachO::S_SYMBOL_STUBS)
8536 outs() << " S_SYMBOL_STUBS\n";
8537 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8538 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8539 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8540 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8541 else if (section_type == MachO::S_COALESCED)
8542 outs() << " S_COALESCED\n";
8543 else if (section_type == MachO::S_INTERPOSING)
8544 outs() << " S_INTERPOSING\n";
8545 else if (section_type == MachO::S_DTRACE_DOF)
8546 outs() << " S_DTRACE_DOF\n";
8547 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8548 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8549 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8550 outs() << " S_THREAD_LOCAL_REGULAR\n";
8551 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8552 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8553 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8554 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8555 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8556 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8557 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8558 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8559 else
8560 outs() << format("0x%08" PRIx32, section_type) << "\n";
8561 outs() << "attributes";
8562 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8563 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8564 outs() << " PURE_INSTRUCTIONS";
8565 if (section_attributes & MachO::S_ATTR_NO_TOC)
8566 outs() << " NO_TOC";
8567 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8568 outs() << " STRIP_STATIC_SYMS";
8569 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8570 outs() << " NO_DEAD_STRIP";
8571 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8572 outs() << " LIVE_SUPPORT";
8573 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8574 outs() << " SELF_MODIFYING_CODE";
8575 if (section_attributes & MachO::S_ATTR_DEBUG)
8576 outs() << " DEBUG";
8577 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8578 outs() << " SOME_INSTRUCTIONS";
8579 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8580 outs() << " EXT_RELOC";
8581 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8582 outs() << " LOC_RELOC";
8583 if (section_attributes == 0)
8584 outs() << " (none)";
8585 outs() << "\n";
8586 } else
8587 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8588 outs() << " reserved1 " << reserved1;
8589 if (section_type == MachO::S_SYMBOL_STUBS ||
8590 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8591 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8592 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8593 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8594 outs() << " (index into indirect symbol table)\n";
8595 else
8596 outs() << "\n";
8597 outs() << " reserved2 " << reserved2;
8598 if (section_type == MachO::S_SYMBOL_STUBS)
8599 outs() << " (size of stubs)\n";
8600 else
8601 outs() << "\n";
8602}
8603
David Majnemer73cc6ff2014-11-13 19:48:56 +00008604static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008605 uint32_t object_size) {
8606 outs() << " cmd LC_SYMTAB\n";
8607 outs() << " cmdsize " << st.cmdsize;
8608 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8609 outs() << " Incorrect size\n";
8610 else
8611 outs() << "\n";
8612 outs() << " symoff " << st.symoff;
8613 if (st.symoff > object_size)
8614 outs() << " (past end of file)\n";
8615 else
8616 outs() << "\n";
8617 outs() << " nsyms " << st.nsyms;
8618 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008619 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008620 big_size = st.nsyms;
8621 big_size *= sizeof(struct MachO::nlist_64);
8622 big_size += st.symoff;
8623 if (big_size > object_size)
8624 outs() << " (past end of file)\n";
8625 else
8626 outs() << "\n";
8627 } else {
8628 big_size = st.nsyms;
8629 big_size *= sizeof(struct MachO::nlist);
8630 big_size += st.symoff;
8631 if (big_size > object_size)
8632 outs() << " (past end of file)\n";
8633 else
8634 outs() << "\n";
8635 }
8636 outs() << " stroff " << st.stroff;
8637 if (st.stroff > object_size)
8638 outs() << " (past end of file)\n";
8639 else
8640 outs() << "\n";
8641 outs() << " strsize " << st.strsize;
8642 big_size = st.stroff;
8643 big_size += st.strsize;
8644 if (big_size > object_size)
8645 outs() << " (past end of file)\n";
8646 else
8647 outs() << "\n";
8648}
8649
8650static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8651 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008652 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008653 outs() << " cmd LC_DYSYMTAB\n";
8654 outs() << " cmdsize " << dyst.cmdsize;
8655 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8656 outs() << " Incorrect size\n";
8657 else
8658 outs() << "\n";
8659 outs() << " ilocalsym " << dyst.ilocalsym;
8660 if (dyst.ilocalsym > nsyms)
8661 outs() << " (greater than the number of symbols)\n";
8662 else
8663 outs() << "\n";
8664 outs() << " nlocalsym " << dyst.nlocalsym;
8665 uint64_t big_size;
8666 big_size = dyst.ilocalsym;
8667 big_size += dyst.nlocalsym;
8668 if (big_size > nsyms)
8669 outs() << " (past the end of the symbol table)\n";
8670 else
8671 outs() << "\n";
8672 outs() << " iextdefsym " << dyst.iextdefsym;
8673 if (dyst.iextdefsym > nsyms)
8674 outs() << " (greater than the number of symbols)\n";
8675 else
8676 outs() << "\n";
8677 outs() << " nextdefsym " << dyst.nextdefsym;
8678 big_size = dyst.iextdefsym;
8679 big_size += dyst.nextdefsym;
8680 if (big_size > nsyms)
8681 outs() << " (past the end of the symbol table)\n";
8682 else
8683 outs() << "\n";
8684 outs() << " iundefsym " << dyst.iundefsym;
8685 if (dyst.iundefsym > nsyms)
8686 outs() << " (greater than the number of symbols)\n";
8687 else
8688 outs() << "\n";
8689 outs() << " nundefsym " << dyst.nundefsym;
8690 big_size = dyst.iundefsym;
8691 big_size += dyst.nundefsym;
8692 if (big_size > nsyms)
8693 outs() << " (past the end of the symbol table)\n";
8694 else
8695 outs() << "\n";
8696 outs() << " tocoff " << dyst.tocoff;
8697 if (dyst.tocoff > object_size)
8698 outs() << " (past end of file)\n";
8699 else
8700 outs() << "\n";
8701 outs() << " ntoc " << dyst.ntoc;
8702 big_size = dyst.ntoc;
8703 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8704 big_size += dyst.tocoff;
8705 if (big_size > object_size)
8706 outs() << " (past end of file)\n";
8707 else
8708 outs() << "\n";
8709 outs() << " modtaboff " << dyst.modtaboff;
8710 if (dyst.modtaboff > object_size)
8711 outs() << " (past end of file)\n";
8712 else
8713 outs() << "\n";
8714 outs() << " nmodtab " << dyst.nmodtab;
8715 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008716 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008717 modtabend = dyst.nmodtab;
8718 modtabend *= sizeof(struct MachO::dylib_module_64);
8719 modtabend += dyst.modtaboff;
8720 } else {
8721 modtabend = dyst.nmodtab;
8722 modtabend *= sizeof(struct MachO::dylib_module);
8723 modtabend += dyst.modtaboff;
8724 }
8725 if (modtabend > object_size)
8726 outs() << " (past end of file)\n";
8727 else
8728 outs() << "\n";
8729 outs() << " extrefsymoff " << dyst.extrefsymoff;
8730 if (dyst.extrefsymoff > object_size)
8731 outs() << " (past end of file)\n";
8732 else
8733 outs() << "\n";
8734 outs() << " nextrefsyms " << dyst.nextrefsyms;
8735 big_size = dyst.nextrefsyms;
8736 big_size *= sizeof(struct MachO::dylib_reference);
8737 big_size += dyst.extrefsymoff;
8738 if (big_size > object_size)
8739 outs() << " (past end of file)\n";
8740 else
8741 outs() << "\n";
8742 outs() << " indirectsymoff " << dyst.indirectsymoff;
8743 if (dyst.indirectsymoff > object_size)
8744 outs() << " (past end of file)\n";
8745 else
8746 outs() << "\n";
8747 outs() << " nindirectsyms " << dyst.nindirectsyms;
8748 big_size = dyst.nindirectsyms;
8749 big_size *= sizeof(uint32_t);
8750 big_size += dyst.indirectsymoff;
8751 if (big_size > object_size)
8752 outs() << " (past end of file)\n";
8753 else
8754 outs() << "\n";
8755 outs() << " extreloff " << dyst.extreloff;
8756 if (dyst.extreloff > object_size)
8757 outs() << " (past end of file)\n";
8758 else
8759 outs() << "\n";
8760 outs() << " nextrel " << dyst.nextrel;
8761 big_size = dyst.nextrel;
8762 big_size *= sizeof(struct MachO::relocation_info);
8763 big_size += dyst.extreloff;
8764 if (big_size > object_size)
8765 outs() << " (past end of file)\n";
8766 else
8767 outs() << "\n";
8768 outs() << " locreloff " << dyst.locreloff;
8769 if (dyst.locreloff > object_size)
8770 outs() << " (past end of file)\n";
8771 else
8772 outs() << "\n";
8773 outs() << " nlocrel " << dyst.nlocrel;
8774 big_size = dyst.nlocrel;
8775 big_size *= sizeof(struct MachO::relocation_info);
8776 big_size += dyst.locreloff;
8777 if (big_size > object_size)
8778 outs() << " (past end of file)\n";
8779 else
8780 outs() << "\n";
8781}
8782
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008783static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8784 uint32_t object_size) {
8785 if (dc.cmd == MachO::LC_DYLD_INFO)
8786 outs() << " cmd LC_DYLD_INFO\n";
8787 else
8788 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8789 outs() << " cmdsize " << dc.cmdsize;
8790 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8791 outs() << " Incorrect size\n";
8792 else
8793 outs() << "\n";
8794 outs() << " rebase_off " << dc.rebase_off;
8795 if (dc.rebase_off > object_size)
8796 outs() << " (past end of file)\n";
8797 else
8798 outs() << "\n";
8799 outs() << " rebase_size " << dc.rebase_size;
8800 uint64_t big_size;
8801 big_size = dc.rebase_off;
8802 big_size += dc.rebase_size;
8803 if (big_size > object_size)
8804 outs() << " (past end of file)\n";
8805 else
8806 outs() << "\n";
8807 outs() << " bind_off " << dc.bind_off;
8808 if (dc.bind_off > object_size)
8809 outs() << " (past end of file)\n";
8810 else
8811 outs() << "\n";
8812 outs() << " bind_size " << dc.bind_size;
8813 big_size = dc.bind_off;
8814 big_size += dc.bind_size;
8815 if (big_size > object_size)
8816 outs() << " (past end of file)\n";
8817 else
8818 outs() << "\n";
8819 outs() << " weak_bind_off " << dc.weak_bind_off;
8820 if (dc.weak_bind_off > object_size)
8821 outs() << " (past end of file)\n";
8822 else
8823 outs() << "\n";
8824 outs() << " weak_bind_size " << dc.weak_bind_size;
8825 big_size = dc.weak_bind_off;
8826 big_size += dc.weak_bind_size;
8827 if (big_size > object_size)
8828 outs() << " (past end of file)\n";
8829 else
8830 outs() << "\n";
8831 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8832 if (dc.lazy_bind_off > object_size)
8833 outs() << " (past end of file)\n";
8834 else
8835 outs() << "\n";
8836 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8837 big_size = dc.lazy_bind_off;
8838 big_size += dc.lazy_bind_size;
8839 if (big_size > object_size)
8840 outs() << " (past end of file)\n";
8841 else
8842 outs() << "\n";
8843 outs() << " export_off " << dc.export_off;
8844 if (dc.export_off > object_size)
8845 outs() << " (past end of file)\n";
8846 else
8847 outs() << "\n";
8848 outs() << " export_size " << dc.export_size;
8849 big_size = dc.export_off;
8850 big_size += dc.export_size;
8851 if (big_size > object_size)
8852 outs() << " (past end of file)\n";
8853 else
8854 outs() << "\n";
8855}
8856
8857static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8858 const char *Ptr) {
8859 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8860 outs() << " cmd LC_ID_DYLINKER\n";
8861 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8862 outs() << " cmd LC_LOAD_DYLINKER\n";
8863 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8864 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8865 else
8866 outs() << " cmd ?(" << dyld.cmd << ")\n";
8867 outs() << " cmdsize " << dyld.cmdsize;
8868 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8869 outs() << " Incorrect size\n";
8870 else
8871 outs() << "\n";
8872 if (dyld.name >= dyld.cmdsize)
8873 outs() << " name ?(bad offset " << dyld.name << ")\n";
8874 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008875 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008876 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8877 }
8878}
8879
8880static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8881 outs() << " cmd LC_UUID\n";
8882 outs() << " cmdsize " << uuid.cmdsize;
8883 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8884 outs() << " Incorrect size\n";
8885 else
8886 outs() << "\n";
8887 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008888 for (int i = 0; i < 16; ++i) {
8889 outs() << format("%02" PRIX32, uuid.uuid[i]);
8890 if (i == 3 || i == 5 || i == 7 || i == 9)
8891 outs() << "-";
8892 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008893 outs() << "\n";
8894}
8895
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008896static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008897 outs() << " cmd LC_RPATH\n";
8898 outs() << " cmdsize " << rpath.cmdsize;
8899 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8900 outs() << " Incorrect size\n";
8901 else
8902 outs() << "\n";
8903 if (rpath.path >= rpath.cmdsize)
8904 outs() << " path ?(bad offset " << rpath.path << ")\n";
8905 else {
8906 const char *P = (const char *)(Ptr) + rpath.path;
8907 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8908 }
8909}
8910
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008911static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008912 StringRef LoadCmdName;
8913 switch (vd.cmd) {
8914 case MachO::LC_VERSION_MIN_MACOSX:
8915 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8916 break;
8917 case MachO::LC_VERSION_MIN_IPHONEOS:
8918 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8919 break;
8920 case MachO::LC_VERSION_MIN_TVOS:
8921 LoadCmdName = "LC_VERSION_MIN_TVOS";
8922 break;
8923 case MachO::LC_VERSION_MIN_WATCHOS:
8924 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8925 break;
8926 default:
8927 llvm_unreachable("Unknown version min load command");
8928 }
8929
8930 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008931 outs() << " cmdsize " << vd.cmdsize;
8932 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8933 outs() << " Incorrect size\n";
8934 else
8935 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008936 outs() << " version "
8937 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8938 << MachOObjectFile::getVersionMinMinor(vd, false);
8939 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8940 if (Update != 0)
8941 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008942 outs() << "\n";
8943 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008944 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008945 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008946 outs() << " sdk "
8947 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8948 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008949 }
Davide Italiano56baef32015-08-26 12:26:11 +00008950 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8951 if (Update != 0)
8952 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008953 outs() << "\n";
8954}
8955
Kevin Enderbya4579c42017-01-19 17:36:31 +00008956static void PrintNoteLoadCommand(MachO::note_command Nt) {
8957 outs() << " cmd LC_NOTE\n";
8958 outs() << " cmdsize " << Nt.cmdsize;
8959 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8960 outs() << " Incorrect size\n";
8961 else
8962 outs() << "\n";
8963 const char *d = Nt.data_owner;
8964 outs() << "data_owner " << format("%.16s\n", d);
8965 outs() << " offset " << Nt.offset << "\n";
8966 outs() << " size " << Nt.size << "\n";
8967}
8968
Steven Wu5b54a422017-01-23 20:07:55 +00008969static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8970 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8971 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8972 << "\n";
8973}
8974
8975static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8976 MachO::build_version_command bd) {
8977 outs() << " cmd LC_BUILD_VERSION\n";
8978 outs() << " cmdsize " << bd.cmdsize;
8979 if (bd.cmdsize !=
8980 sizeof(struct MachO::build_version_command) +
8981 bd.ntools * sizeof(struct MachO::build_tool_version))
8982 outs() << " Incorrect size\n";
8983 else
8984 outs() << "\n";
8985 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8986 << "\n";
8987 if (bd.sdk)
8988 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8989 << "\n";
8990 else
8991 outs() << " sdk n/a\n";
8992 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8993 << "\n";
8994 outs() << " ntools " << bd.ntools << "\n";
8995 for (unsigned i = 0; i < bd.ntools; ++i) {
8996 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8997 PrintBuildToolVersion(bv);
8998 }
8999}
9000
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009001static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9002 outs() << " cmd LC_SOURCE_VERSION\n";
9003 outs() << " cmdsize " << sd.cmdsize;
9004 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9005 outs() << " Incorrect size\n";
9006 else
9007 outs() << "\n";
9008 uint64_t a = (sd.version >> 40) & 0xffffff;
9009 uint64_t b = (sd.version >> 30) & 0x3ff;
9010 uint64_t c = (sd.version >> 20) & 0x3ff;
9011 uint64_t d = (sd.version >> 10) & 0x3ff;
9012 uint64_t e = sd.version & 0x3ff;
9013 outs() << " version " << a << "." << b;
9014 if (e != 0)
9015 outs() << "." << c << "." << d << "." << e;
9016 else if (d != 0)
9017 outs() << "." << c << "." << d;
9018 else if (c != 0)
9019 outs() << "." << c;
9020 outs() << "\n";
9021}
9022
9023static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9024 outs() << " cmd LC_MAIN\n";
9025 outs() << " cmdsize " << ep.cmdsize;
9026 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9027 outs() << " Incorrect size\n";
9028 else
9029 outs() << "\n";
9030 outs() << " entryoff " << ep.entryoff << "\n";
9031 outs() << " stacksize " << ep.stacksize << "\n";
9032}
9033
Kevin Enderby0804f4672014-12-16 23:25:52 +00009034static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9035 uint32_t object_size) {
9036 outs() << " cmd LC_ENCRYPTION_INFO\n";
9037 outs() << " cmdsize " << ec.cmdsize;
9038 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9039 outs() << " Incorrect size\n";
9040 else
9041 outs() << "\n";
9042 outs() << " cryptoff " << ec.cryptoff;
9043 if (ec.cryptoff > object_size)
9044 outs() << " (past end of file)\n";
9045 else
9046 outs() << "\n";
9047 outs() << " cryptsize " << ec.cryptsize;
9048 if (ec.cryptsize > object_size)
9049 outs() << " (past end of file)\n";
9050 else
9051 outs() << "\n";
9052 outs() << " cryptid " << ec.cryptid << "\n";
9053}
9054
Kevin Enderby57538292014-12-17 01:01:30 +00009055static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009056 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00009057 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
9058 outs() << " cmdsize " << ec.cmdsize;
9059 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9060 outs() << " Incorrect size\n";
9061 else
9062 outs() << "\n";
9063 outs() << " cryptoff " << ec.cryptoff;
9064 if (ec.cryptoff > object_size)
9065 outs() << " (past end of file)\n";
9066 else
9067 outs() << "\n";
9068 outs() << " cryptsize " << ec.cryptsize;
9069 if (ec.cryptsize > object_size)
9070 outs() << " (past end of file)\n";
9071 else
9072 outs() << "\n";
9073 outs() << " cryptid " << ec.cryptid << "\n";
9074 outs() << " pad " << ec.pad << "\n";
9075}
9076
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009077static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9078 const char *Ptr) {
9079 outs() << " cmd LC_LINKER_OPTION\n";
9080 outs() << " cmdsize " << lo.cmdsize;
9081 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9082 outs() << " Incorrect size\n";
9083 else
9084 outs() << "\n";
9085 outs() << " count " << lo.count << "\n";
9086 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9087 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9088 uint32_t i = 0;
9089 while (left > 0) {
9090 while (*string == '\0' && left > 0) {
9091 string++;
9092 left--;
9093 }
9094 if (left > 0) {
9095 i++;
9096 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00009097 uint32_t NullPos = StringRef(string, left).find('\0');
9098 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009099 string += len;
9100 left -= len;
9101 }
9102 }
9103 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009104 outs() << " count " << lo.count << " does not match number of strings "
9105 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009106}
9107
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009108static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9109 const char *Ptr) {
9110 outs() << " cmd LC_SUB_FRAMEWORK\n";
9111 outs() << " cmdsize " << sub.cmdsize;
9112 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9113 outs() << " Incorrect size\n";
9114 else
9115 outs() << "\n";
9116 if (sub.umbrella < sub.cmdsize) {
9117 const char *P = Ptr + sub.umbrella;
9118 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9119 } else {
9120 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9121 }
9122}
9123
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009124static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9125 const char *Ptr) {
9126 outs() << " cmd LC_SUB_UMBRELLA\n";
9127 outs() << " cmdsize " << sub.cmdsize;
9128 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9129 outs() << " Incorrect size\n";
9130 else
9131 outs() << "\n";
9132 if (sub.sub_umbrella < sub.cmdsize) {
9133 const char *P = Ptr + sub.sub_umbrella;
9134 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9135 } else {
9136 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9137 }
9138}
9139
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009140static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009141 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009142 outs() << " cmd LC_SUB_LIBRARY\n";
9143 outs() << " cmdsize " << sub.cmdsize;
9144 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9145 outs() << " Incorrect size\n";
9146 else
9147 outs() << "\n";
9148 if (sub.sub_library < sub.cmdsize) {
9149 const char *P = Ptr + sub.sub_library;
9150 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9151 } else {
9152 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9153 }
9154}
9155
Kevin Enderby186eac32014-12-19 21:06:24 +00009156static void PrintSubClientCommand(MachO::sub_client_command sub,
9157 const char *Ptr) {
9158 outs() << " cmd LC_SUB_CLIENT\n";
9159 outs() << " cmdsize " << sub.cmdsize;
9160 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9161 outs() << " Incorrect size\n";
9162 else
9163 outs() << "\n";
9164 if (sub.client < sub.cmdsize) {
9165 const char *P = Ptr + sub.client;
9166 outs() << " client " << P << " (offset " << sub.client << ")\n";
9167 } else {
9168 outs() << " client ?(bad offset " << sub.client << ")\n";
9169 }
9170}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009171
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009172static void PrintRoutinesCommand(MachO::routines_command r) {
9173 outs() << " cmd LC_ROUTINES\n";
9174 outs() << " cmdsize " << r.cmdsize;
9175 if (r.cmdsize != sizeof(struct MachO::routines_command))
9176 outs() << " Incorrect size\n";
9177 else
9178 outs() << "\n";
9179 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9180 outs() << " init_module " << r.init_module << "\n";
9181 outs() << " reserved1 " << r.reserved1 << "\n";
9182 outs() << " reserved2 " << r.reserved2 << "\n";
9183 outs() << " reserved3 " << r.reserved3 << "\n";
9184 outs() << " reserved4 " << r.reserved4 << "\n";
9185 outs() << " reserved5 " << r.reserved5 << "\n";
9186 outs() << " reserved6 " << r.reserved6 << "\n";
9187}
9188
9189static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9190 outs() << " cmd LC_ROUTINES_64\n";
9191 outs() << " cmdsize " << r.cmdsize;
9192 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9193 outs() << " Incorrect size\n";
9194 else
9195 outs() << "\n";
9196 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9197 outs() << " init_module " << r.init_module << "\n";
9198 outs() << " reserved1 " << r.reserved1 << "\n";
9199 outs() << " reserved2 " << r.reserved2 << "\n";
9200 outs() << " reserved3 " << r.reserved3 << "\n";
9201 outs() << " reserved4 " << r.reserved4 << "\n";
9202 outs() << " reserved5 " << r.reserved5 << "\n";
9203 outs() << " reserved6 " << r.reserved6 << "\n";
9204}
9205
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009206static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9207 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9208 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9209 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9210 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9211 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9212 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9213 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9214 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9215 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9216 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9217 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9218 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9219 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9220 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9221 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9222 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9223}
9224
Kevin Enderby48ef5342014-12-23 22:56:39 +00009225static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9226 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9227 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9228 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9229 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9230 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9231 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9232 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9233 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9234 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9235 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9236 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9237 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9238 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9239 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9240 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9241 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9242 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9243 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9244 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9245 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9246 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9247}
9248
Kevin Enderby227df342014-12-23 23:43:59 +00009249static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009250 uint32_t f;
9251 outs() << "\t mmst_reg ";
9252 for (f = 0; f < 10; f++)
9253 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9254 outs() << "\n";
9255 outs() << "\t mmst_rsrv ";
9256 for (f = 0; f < 6; f++)
9257 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9258 outs() << "\n";
9259}
9260
Kevin Enderbyaefb0032014-12-24 00:16:51 +00009261static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009262 uint32_t f;
9263 outs() << "\t xmm_reg ";
9264 for (f = 0; f < 16; f++)
9265 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9266 outs() << "\n";
9267}
9268
9269static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9270 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9271 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9272 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9273 outs() << " denorm " << fpu.fpu_fcw.denorm;
9274 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9275 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9276 outs() << " undfl " << fpu.fpu_fcw.undfl;
9277 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9278 outs() << "\t\t pc ";
9279 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9280 outs() << "FP_PREC_24B ";
9281 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9282 outs() << "FP_PREC_53B ";
9283 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9284 outs() << "FP_PREC_64B ";
9285 else
9286 outs() << fpu.fpu_fcw.pc << " ";
9287 outs() << "rc ";
9288 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9289 outs() << "FP_RND_NEAR ";
9290 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9291 outs() << "FP_RND_DOWN ";
9292 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9293 outs() << "FP_RND_UP ";
9294 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009295 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009296 outs() << "\n";
9297 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9298 outs() << " denorm " << fpu.fpu_fsw.denorm;
9299 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9300 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9301 outs() << " undfl " << fpu.fpu_fsw.undfl;
9302 outs() << " precis " << fpu.fpu_fsw.precis;
9303 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9304 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9305 outs() << " c0 " << fpu.fpu_fsw.c0;
9306 outs() << " c1 " << fpu.fpu_fsw.c1;
9307 outs() << " c2 " << fpu.fpu_fsw.c2;
9308 outs() << " tos " << fpu.fpu_fsw.tos;
9309 outs() << " c3 " << fpu.fpu_fsw.c3;
9310 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9311 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9312 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9313 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9314 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9315 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9316 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9317 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9318 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9319 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9320 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9321 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9322 outs() << "\n";
9323 outs() << "\t fpu_stmm0:\n";
9324 Print_mmst_reg(fpu.fpu_stmm0);
9325 outs() << "\t fpu_stmm1:\n";
9326 Print_mmst_reg(fpu.fpu_stmm1);
9327 outs() << "\t fpu_stmm2:\n";
9328 Print_mmst_reg(fpu.fpu_stmm2);
9329 outs() << "\t fpu_stmm3:\n";
9330 Print_mmst_reg(fpu.fpu_stmm3);
9331 outs() << "\t fpu_stmm4:\n";
9332 Print_mmst_reg(fpu.fpu_stmm4);
9333 outs() << "\t fpu_stmm5:\n";
9334 Print_mmst_reg(fpu.fpu_stmm5);
9335 outs() << "\t fpu_stmm6:\n";
9336 Print_mmst_reg(fpu.fpu_stmm6);
9337 outs() << "\t fpu_stmm7:\n";
9338 Print_mmst_reg(fpu.fpu_stmm7);
9339 outs() << "\t fpu_xmm0:\n";
9340 Print_xmm_reg(fpu.fpu_xmm0);
9341 outs() << "\t fpu_xmm1:\n";
9342 Print_xmm_reg(fpu.fpu_xmm1);
9343 outs() << "\t fpu_xmm2:\n";
9344 Print_xmm_reg(fpu.fpu_xmm2);
9345 outs() << "\t fpu_xmm3:\n";
9346 Print_xmm_reg(fpu.fpu_xmm3);
9347 outs() << "\t fpu_xmm4:\n";
9348 Print_xmm_reg(fpu.fpu_xmm4);
9349 outs() << "\t fpu_xmm5:\n";
9350 Print_xmm_reg(fpu.fpu_xmm5);
9351 outs() << "\t fpu_xmm6:\n";
9352 Print_xmm_reg(fpu.fpu_xmm6);
9353 outs() << "\t fpu_xmm7:\n";
9354 Print_xmm_reg(fpu.fpu_xmm7);
9355 outs() << "\t fpu_xmm8:\n";
9356 Print_xmm_reg(fpu.fpu_xmm8);
9357 outs() << "\t fpu_xmm9:\n";
9358 Print_xmm_reg(fpu.fpu_xmm9);
9359 outs() << "\t fpu_xmm10:\n";
9360 Print_xmm_reg(fpu.fpu_xmm10);
9361 outs() << "\t fpu_xmm11:\n";
9362 Print_xmm_reg(fpu.fpu_xmm11);
9363 outs() << "\t fpu_xmm12:\n";
9364 Print_xmm_reg(fpu.fpu_xmm12);
9365 outs() << "\t fpu_xmm13:\n";
9366 Print_xmm_reg(fpu.fpu_xmm13);
9367 outs() << "\t fpu_xmm14:\n";
9368 Print_xmm_reg(fpu.fpu_xmm14);
9369 outs() << "\t fpu_xmm15:\n";
9370 Print_xmm_reg(fpu.fpu_xmm15);
9371 outs() << "\t fpu_rsrv4:\n";
9372 for (uint32_t f = 0; f < 6; f++) {
9373 outs() << "\t ";
9374 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009375 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009376 outs() << "\n";
9377 }
9378 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9379 outs() << "\n";
9380}
9381
9382static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9383 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9384 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9385 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9386}
9387
Kevin Enderby41c9c002016-10-21 18:22:35 +00009388static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9389 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9390 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9391 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9392 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9393 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9394 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9395 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9396 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9397 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9398 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9399 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9400 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9401 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9402 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9403 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9404 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9405 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9406}
9407
Kevin Enderby7747cb52016-11-03 20:51:28 +00009408static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9409 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9410 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9411 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9412 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9413 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9414 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9415 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9416 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9417 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9418 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9419 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9420 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9421 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9422 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9423 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9424 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9425 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9426 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9427 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9428 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9429 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9430 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9431 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9432 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9433 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9434 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9435 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9436 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9437 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9438 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9439 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9440 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9441 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9442 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9443}
9444
Kevin Enderby48ef5342014-12-23 22:56:39 +00009445static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9446 bool isLittleEndian, uint32_t cputype) {
9447 if (t.cmd == MachO::LC_THREAD)
9448 outs() << " cmd LC_THREAD\n";
9449 else if (t.cmd == MachO::LC_UNIXTHREAD)
9450 outs() << " cmd LC_UNIXTHREAD\n";
9451 else
9452 outs() << " cmd " << t.cmd << " (unknown)\n";
9453 outs() << " cmdsize " << t.cmdsize;
9454 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9455 outs() << " Incorrect size\n";
9456 else
9457 outs() << "\n";
9458
9459 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9460 const char *end = Ptr + t.cmdsize;
9461 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009462 if (cputype == MachO::CPU_TYPE_I386) {
9463 while (begin < end) {
9464 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9465 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9466 begin += sizeof(uint32_t);
9467 } else {
9468 flavor = 0;
9469 begin = end;
9470 }
9471 if (isLittleEndian != sys::IsLittleEndianHost)
9472 sys::swapByteOrder(flavor);
9473 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9474 memcpy((char *)&count, begin, sizeof(uint32_t));
9475 begin += sizeof(uint32_t);
9476 } else {
9477 count = 0;
9478 begin = end;
9479 }
9480 if (isLittleEndian != sys::IsLittleEndianHost)
9481 sys::swapByteOrder(count);
9482 if (flavor == MachO::x86_THREAD_STATE32) {
9483 outs() << " flavor i386_THREAD_STATE\n";
9484 if (count == MachO::x86_THREAD_STATE32_COUNT)
9485 outs() << " count i386_THREAD_STATE_COUNT\n";
9486 else
9487 outs() << " count " << count
9488 << " (not x86_THREAD_STATE32_COUNT)\n";
9489 MachO::x86_thread_state32_t cpu32;
9490 left = end - begin;
9491 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9492 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9493 begin += sizeof(MachO::x86_thread_state32_t);
9494 } else {
9495 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9496 memcpy(&cpu32, begin, left);
9497 begin += left;
9498 }
9499 if (isLittleEndian != sys::IsLittleEndianHost)
9500 swapStruct(cpu32);
9501 Print_x86_thread_state32_t(cpu32);
9502 } else if (flavor == MachO::x86_THREAD_STATE) {
9503 outs() << " flavor x86_THREAD_STATE\n";
9504 if (count == MachO::x86_THREAD_STATE_COUNT)
9505 outs() << " count x86_THREAD_STATE_COUNT\n";
9506 else
9507 outs() << " count " << count
9508 << " (not x86_THREAD_STATE_COUNT)\n";
9509 struct MachO::x86_thread_state_t ts;
9510 left = end - begin;
9511 if (left >= sizeof(MachO::x86_thread_state_t)) {
9512 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9513 begin += sizeof(MachO::x86_thread_state_t);
9514 } else {
9515 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9516 memcpy(&ts, begin, left);
9517 begin += left;
9518 }
9519 if (isLittleEndian != sys::IsLittleEndianHost)
9520 swapStruct(ts);
9521 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9522 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9523 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9524 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9525 else
9526 outs() << "tsh.count " << ts.tsh.count
9527 << " (not x86_THREAD_STATE32_COUNT\n";
9528 Print_x86_thread_state32_t(ts.uts.ts32);
9529 } else {
9530 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9531 << ts.tsh.count << "\n";
9532 }
9533 } else {
9534 outs() << " flavor " << flavor << " (unknown)\n";
9535 outs() << " count " << count << "\n";
9536 outs() << " state (unknown)\n";
9537 begin += count * sizeof(uint32_t);
9538 }
9539 }
9540 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009541 while (begin < end) {
9542 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9543 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9544 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009545 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009546 flavor = 0;
9547 begin = end;
9548 }
9549 if (isLittleEndian != sys::IsLittleEndianHost)
9550 sys::swapByteOrder(flavor);
9551 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9552 memcpy((char *)&count, begin, sizeof(uint32_t));
9553 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009554 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009555 count = 0;
9556 begin = end;
9557 }
9558 if (isLittleEndian != sys::IsLittleEndianHost)
9559 sys::swapByteOrder(count);
9560 if (flavor == MachO::x86_THREAD_STATE64) {
9561 outs() << " flavor x86_THREAD_STATE64\n";
9562 if (count == MachO::x86_THREAD_STATE64_COUNT)
9563 outs() << " count x86_THREAD_STATE64_COUNT\n";
9564 else
9565 outs() << " count " << count
9566 << " (not x86_THREAD_STATE64_COUNT)\n";
9567 MachO::x86_thread_state64_t cpu64;
9568 left = end - begin;
9569 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9570 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9571 begin += sizeof(MachO::x86_thread_state64_t);
9572 } else {
9573 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9574 memcpy(&cpu64, begin, left);
9575 begin += left;
9576 }
9577 if (isLittleEndian != sys::IsLittleEndianHost)
9578 swapStruct(cpu64);
9579 Print_x86_thread_state64_t(cpu64);
9580 } else if (flavor == MachO::x86_THREAD_STATE) {
9581 outs() << " flavor x86_THREAD_STATE\n";
9582 if (count == MachO::x86_THREAD_STATE_COUNT)
9583 outs() << " count x86_THREAD_STATE_COUNT\n";
9584 else
9585 outs() << " count " << count
9586 << " (not x86_THREAD_STATE_COUNT)\n";
9587 struct MachO::x86_thread_state_t ts;
9588 left = end - begin;
9589 if (left >= sizeof(MachO::x86_thread_state_t)) {
9590 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9591 begin += sizeof(MachO::x86_thread_state_t);
9592 } else {
9593 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9594 memcpy(&ts, begin, left);
9595 begin += left;
9596 }
9597 if (isLittleEndian != sys::IsLittleEndianHost)
9598 swapStruct(ts);
9599 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9600 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9601 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9602 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9603 else
9604 outs() << "tsh.count " << ts.tsh.count
9605 << " (not x86_THREAD_STATE64_COUNT\n";
9606 Print_x86_thread_state64_t(ts.uts.ts64);
9607 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009608 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9609 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009610 }
9611 } else if (flavor == MachO::x86_FLOAT_STATE) {
9612 outs() << " flavor x86_FLOAT_STATE\n";
9613 if (count == MachO::x86_FLOAT_STATE_COUNT)
9614 outs() << " count x86_FLOAT_STATE_COUNT\n";
9615 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009616 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009617 struct MachO::x86_float_state_t fs;
9618 left = end - begin;
9619 if (left >= sizeof(MachO::x86_float_state_t)) {
9620 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9621 begin += sizeof(MachO::x86_float_state_t);
9622 } else {
9623 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9624 memcpy(&fs, begin, left);
9625 begin += left;
9626 }
9627 if (isLittleEndian != sys::IsLittleEndianHost)
9628 swapStruct(fs);
9629 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9630 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009631 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009632 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9633 else
9634 outs() << "fsh.count " << fs.fsh.count
9635 << " (not x86_FLOAT_STATE64_COUNT\n";
9636 Print_x86_float_state_t(fs.ufs.fs64);
9637 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009638 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9639 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009640 }
9641 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9642 outs() << " flavor x86_EXCEPTION_STATE\n";
9643 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9644 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9645 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009646 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009647 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9648 struct MachO::x86_exception_state_t es;
9649 left = end - begin;
9650 if (left >= sizeof(MachO::x86_exception_state_t)) {
9651 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9652 begin += sizeof(MachO::x86_exception_state_t);
9653 } else {
9654 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9655 memcpy(&es, begin, left);
9656 begin += left;
9657 }
9658 if (isLittleEndian != sys::IsLittleEndianHost)
9659 swapStruct(es);
9660 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9661 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009662 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009663 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9664 else
9665 outs() << "\t esh.count " << es.esh.count
9666 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9667 Print_x86_exception_state_t(es.ues.es64);
9668 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009669 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9670 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009671 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009672 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9673 outs() << " flavor x86_EXCEPTION_STATE64\n";
9674 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9675 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9676 else
9677 outs() << " count " << count
9678 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9679 struct MachO::x86_exception_state64_t es64;
9680 left = end - begin;
9681 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9682 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9683 begin += sizeof(MachO::x86_exception_state64_t);
9684 } else {
9685 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9686 memcpy(&es64, begin, left);
9687 begin += left;
9688 }
9689 if (isLittleEndian != sys::IsLittleEndianHost)
9690 swapStruct(es64);
9691 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009692 } else {
9693 outs() << " flavor " << flavor << " (unknown)\n";
9694 outs() << " count " << count << "\n";
9695 outs() << " state (unknown)\n";
9696 begin += count * sizeof(uint32_t);
9697 }
9698 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009699 } else if (cputype == MachO::CPU_TYPE_ARM) {
9700 while (begin < end) {
9701 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9702 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9703 begin += sizeof(uint32_t);
9704 } else {
9705 flavor = 0;
9706 begin = end;
9707 }
9708 if (isLittleEndian != sys::IsLittleEndianHost)
9709 sys::swapByteOrder(flavor);
9710 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9711 memcpy((char *)&count, begin, sizeof(uint32_t));
9712 begin += sizeof(uint32_t);
9713 } else {
9714 count = 0;
9715 begin = end;
9716 }
9717 if (isLittleEndian != sys::IsLittleEndianHost)
9718 sys::swapByteOrder(count);
9719 if (flavor == MachO::ARM_THREAD_STATE) {
9720 outs() << " flavor ARM_THREAD_STATE\n";
9721 if (count == MachO::ARM_THREAD_STATE_COUNT)
9722 outs() << " count ARM_THREAD_STATE_COUNT\n";
9723 else
9724 outs() << " count " << count
9725 << " (not ARM_THREAD_STATE_COUNT)\n";
9726 MachO::arm_thread_state32_t cpu32;
9727 left = end - begin;
9728 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9729 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9730 begin += sizeof(MachO::arm_thread_state32_t);
9731 } else {
9732 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9733 memcpy(&cpu32, begin, left);
9734 begin += left;
9735 }
9736 if (isLittleEndian != sys::IsLittleEndianHost)
9737 swapStruct(cpu32);
9738 Print_arm_thread_state32_t(cpu32);
9739 } else {
9740 outs() << " flavor " << flavor << " (unknown)\n";
9741 outs() << " count " << count << "\n";
9742 outs() << " state (unknown)\n";
9743 begin += count * sizeof(uint32_t);
9744 }
9745 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009746 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9747 while (begin < end) {
9748 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9749 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9750 begin += sizeof(uint32_t);
9751 } else {
9752 flavor = 0;
9753 begin = end;
9754 }
9755 if (isLittleEndian != sys::IsLittleEndianHost)
9756 sys::swapByteOrder(flavor);
9757 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9758 memcpy((char *)&count, begin, sizeof(uint32_t));
9759 begin += sizeof(uint32_t);
9760 } else {
9761 count = 0;
9762 begin = end;
9763 }
9764 if (isLittleEndian != sys::IsLittleEndianHost)
9765 sys::swapByteOrder(count);
9766 if (flavor == MachO::ARM_THREAD_STATE64) {
9767 outs() << " flavor ARM_THREAD_STATE64\n";
9768 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9769 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9770 else
9771 outs() << " count " << count
9772 << " (not ARM_THREAD_STATE64_COUNT)\n";
9773 MachO::arm_thread_state64_t cpu64;
9774 left = end - begin;
9775 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9776 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9777 begin += sizeof(MachO::arm_thread_state64_t);
9778 } else {
9779 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9780 memcpy(&cpu64, begin, left);
9781 begin += left;
9782 }
9783 if (isLittleEndian != sys::IsLittleEndianHost)
9784 swapStruct(cpu64);
9785 Print_arm_thread_state64_t(cpu64);
9786 } else {
9787 outs() << " flavor " << flavor << " (unknown)\n";
9788 outs() << " count " << count << "\n";
9789 outs() << " state (unknown)\n";
9790 begin += count * sizeof(uint32_t);
9791 }
9792 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009793 } else {
9794 while (begin < end) {
9795 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9796 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9797 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009798 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009799 flavor = 0;
9800 begin = end;
9801 }
9802 if (isLittleEndian != sys::IsLittleEndianHost)
9803 sys::swapByteOrder(flavor);
9804 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9805 memcpy((char *)&count, begin, sizeof(uint32_t));
9806 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009807 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009808 count = 0;
9809 begin = end;
9810 }
9811 if (isLittleEndian != sys::IsLittleEndianHost)
9812 sys::swapByteOrder(count);
9813 outs() << " flavor " << flavor << "\n";
9814 outs() << " count " << count << "\n";
9815 outs() << " state (Unknown cputype/cpusubtype)\n";
9816 begin += count * sizeof(uint32_t);
9817 }
9818 }
9819}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009820
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009821static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9822 if (dl.cmd == MachO::LC_ID_DYLIB)
9823 outs() << " cmd LC_ID_DYLIB\n";
9824 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9825 outs() << " cmd LC_LOAD_DYLIB\n";
9826 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9827 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9828 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9829 outs() << " cmd LC_REEXPORT_DYLIB\n";
9830 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9831 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9832 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9833 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9834 else
9835 outs() << " cmd " << dl.cmd << " (unknown)\n";
9836 outs() << " cmdsize " << dl.cmdsize;
9837 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9838 outs() << " Incorrect size\n";
9839 else
9840 outs() << "\n";
9841 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009842 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009843 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9844 } else {
9845 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9846 }
9847 outs() << " time stamp " << dl.dylib.timestamp << " ";
9848 time_t t = dl.dylib.timestamp;
9849 outs() << ctime(&t);
9850 outs() << " current version ";
9851 if (dl.dylib.current_version == 0xffffffff)
9852 outs() << "n/a\n";
9853 else
9854 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9855 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9856 << (dl.dylib.current_version & 0xff) << "\n";
9857 outs() << "compatibility version ";
9858 if (dl.dylib.compatibility_version == 0xffffffff)
9859 outs() << "n/a\n";
9860 else
9861 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9862 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9863 << (dl.dylib.compatibility_version & 0xff) << "\n";
9864}
9865
9866static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9867 uint32_t object_size) {
9868 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009869 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009870 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9871 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9872 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9873 outs() << " cmd LC_FUNCTION_STARTS\n";
9874 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9875 outs() << " cmd LC_DATA_IN_CODE\n";
9876 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9877 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9878 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9879 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9880 else
9881 outs() << " cmd " << ld.cmd << " (?)\n";
9882 outs() << " cmdsize " << ld.cmdsize;
9883 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9884 outs() << " Incorrect size\n";
9885 else
9886 outs() << "\n";
9887 outs() << " dataoff " << ld.dataoff;
9888 if (ld.dataoff > object_size)
9889 outs() << " (past end of file)\n";
9890 else
9891 outs() << "\n";
9892 outs() << " datasize " << ld.datasize;
9893 uint64_t big_size = ld.dataoff;
9894 big_size += ld.datasize;
9895 if (big_size > object_size)
9896 outs() << " (past end of file)\n";
9897 else
9898 outs() << "\n";
9899}
9900
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009901static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9902 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009903 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009904 unsigned Index = 0;
9905 for (const auto &Command : Obj->load_commands()) {
9906 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009907 if (Command.C.cmd == MachO::LC_SEGMENT) {
9908 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9909 const char *sg_segname = SLC.segname;
9910 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9911 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9912 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9913 verbose);
9914 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009915 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009916 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9917 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9918 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9919 }
9920 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9921 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9922 const char *sg_segname = SLC_64.segname;
9923 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9924 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9925 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9926 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9927 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9928 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9929 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9930 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9931 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9932 sg_segname, filetype, Buf.size(), verbose);
9933 }
9934 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9935 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009936 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009937 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9938 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9939 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009940 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9941 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009942 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9943 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9944 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9945 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9946 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9947 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9948 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9949 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9950 PrintDyldLoadCommand(Dyld, Command.Ptr);
9951 } else if (Command.C.cmd == MachO::LC_UUID) {
9952 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9953 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009954 } else if (Command.C.cmd == MachO::LC_RPATH) {
9955 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9956 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009957 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009958 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9959 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9960 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009961 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9962 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009963 } else if (Command.C.cmd == MachO::LC_NOTE) {
9964 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9965 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009966 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9967 MachO::build_version_command Bv =
9968 Obj->getBuildVersionLoadCommand(Command);
9969 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009970 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9971 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9972 PrintSourceVersionCommand(Sd);
9973 } else if (Command.C.cmd == MachO::LC_MAIN) {
9974 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9975 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009976 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009977 MachO::encryption_info_command Ei =
9978 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009979 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009980 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009981 MachO::encryption_info_command_64 Ei =
9982 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009983 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009984 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009985 MachO::linker_option_command Lo =
9986 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009987 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009988 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9989 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9990 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009991 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9992 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9993 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009994 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9995 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9996 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009997 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9998 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9999 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +000010000 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10001 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10002 PrintRoutinesCommand(Rc);
10003 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10004 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10005 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +000010006 } else if (Command.C.cmd == MachO::LC_THREAD ||
10007 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10008 MachO::thread_command Tc = Obj->getThreadCommand(Command);
10009 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +000010010 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10011 Command.C.cmd == MachO::LC_ID_DYLIB ||
10012 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10013 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10014 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10015 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +000010016 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10017 PrintDylibCommand(Dl, Command.Ptr);
10018 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10019 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10020 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10021 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10022 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10023 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10024 MachO::linkedit_data_command Ld =
10025 Obj->getLinkeditDataLoadCommand(Command);
10026 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +000010027 } else {
10028 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10029 << ")\n";
10030 outs() << " cmdsize " << Command.C.cmdsize << "\n";
10031 // TODO: get and print the raw bytes of the load command.
10032 }
10033 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +000010034 }
10035}
10036
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010037static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +000010038 if (Obj->is64Bit()) {
10039 MachO::mach_header_64 H_64;
10040 H_64 = Obj->getHeader64();
10041 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10042 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10043 } else {
10044 MachO::mach_header H;
10045 H = Obj->getHeader();
10046 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10047 H.sizeofcmds, H.flags, verbose);
10048 }
10049}
10050
10051void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
10052 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010053 PrintMachHeader(file, !NonVerbose);
10054}
10055
10056void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
10057 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +000010058 uint32_t filetype = 0;
10059 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010060 if (file->is64Bit()) {
10061 MachO::mach_header_64 H_64;
10062 H_64 = file->getHeader64();
10063 filetype = H_64.filetype;
10064 cputype = H_64.cputype;
10065 } else {
10066 MachO::mach_header H;
10067 H = file->getHeader();
10068 filetype = H.filetype;
10069 cputype = H.cputype;
10070 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +000010071 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +000010072}
Nick Kledzikd04bc352014-08-30 00:20:14 +000010073
10074//===----------------------------------------------------------------------===//
10075// export trie dumping
10076//===----------------------------------------------------------------------===//
10077
10078void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010079 uint64_t BaseSegmentAddress = 0;
10080 for (const auto &Command : Obj->load_commands()) {
10081 if (Command.C.cmd == MachO::LC_SEGMENT) {
10082 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10083 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10084 BaseSegmentAddress = Seg.vmaddr;
10085 break;
10086 }
10087 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10088 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10089 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10090 BaseSegmentAddress = Seg.vmaddr;
10091 break;
10092 }
10093 }
10094 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010095 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +000010096 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010097 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010098 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10099 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10100 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10101 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10102 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10103 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10104 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10105 if (ReExport)
10106 outs() << "[re-export] ";
10107 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010108 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010109 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010110 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010111 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010112 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +000010113 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010114 if (WeakDef) {
10115 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010116 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010117 }
10118 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010119 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010120 outs() << ", ";
10121 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010122 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010123 }
10124 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010125 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010126 outs() << ", ";
10127 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010128 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010129 }
10130 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010131 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010132 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010133 outs() << format("resolver=0x%08llX", Entry.other());
10134 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010135 }
10136 outs() << "]";
10137 }
10138 if (ReExport) {
10139 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010140 int Ordinal = Entry.other() - 1;
10141 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10142 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +000010143 outs() << " (from " << DylibName << ")";
10144 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010145 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010146 }
10147 outs() << "\n";
10148 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010149 if (Err)
10150 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +000010151}
Nick Kledzikac431442014-09-12 21:34:15 +000010152
Nick Kledzikac431442014-09-12 21:34:15 +000010153//===----------------------------------------------------------------------===//
10154// rebase table dumping
10155//===----------------------------------------------------------------------===//
10156
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010157void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +000010158 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010159 Error Err = Error::success();
10160 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10161 StringRef SegmentName = Entry.segmentName();
10162 StringRef SectionName = Entry.sectionName();
10163 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +000010164
10165 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010166 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10167 SegmentName.str().c_str(), SectionName.str().c_str(),
10168 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +000010169 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010170 if (Err)
10171 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +000010172}
Nick Kledzik56ebef42014-09-16 01:41:51 +000010173
10174static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10175 StringRef DylibName;
10176 switch (Ordinal) {
10177 case MachO::BIND_SPECIAL_DYLIB_SELF:
10178 return "this-image";
10179 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10180 return "main-executable";
10181 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10182 return "flat-namespace";
10183 default:
Nick Kledzikabd29872014-09-16 22:03:13 +000010184 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010185 std::error_code EC =
10186 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +000010187 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +000010188 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +000010189 return DylibName;
10190 }
Nick Kledzik56ebef42014-09-16 01:41:51 +000010191 }
Nick Kledzikabd29872014-09-16 22:03:13 +000010192 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010193}
10194
10195//===----------------------------------------------------------------------===//
10196// bind table dumping
10197//===----------------------------------------------------------------------===//
10198
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010199void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010200 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010201 outs() << "segment section address type "
10202 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010203 Error Err = Error::success();
10204 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010205 StringRef SegmentName = Entry.segmentName();
10206 StringRef SectionName = Entry.sectionName();
10207 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010208
10209 // Table lines look like:
10210 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010211 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +000010212 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010213 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010214 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010215 << left_justify(SectionName, 18) << " "
10216 << format_hex(Address, 10, true) << " "
10217 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010218 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010219 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010220 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010221 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010222 if (Err)
10223 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +000010224}
10225
10226//===----------------------------------------------------------------------===//
10227// lazy bind table dumping
10228//===----------------------------------------------------------------------===//
10229
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010230void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010231 outs() << "segment section address "
10232 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010233 Error Err = Error::success();
10234 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010235 StringRef SegmentName = Entry.segmentName();
10236 StringRef SectionName = Entry.sectionName();
10237 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010238
10239 // Table lines look like:
10240 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010241 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010242 << left_justify(SectionName, 18) << " "
10243 << format_hex(Address, 10, true) << " "
10244 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010245 << Entry.symbolName() << "\n";
10246 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010247 if (Err)
10248 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +000010249}
10250
Nick Kledzik56ebef42014-09-16 01:41:51 +000010251//===----------------------------------------------------------------------===//
10252// weak bind table dumping
10253//===----------------------------------------------------------------------===//
10254
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010255void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010256 outs() << "segment section address "
10257 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010258 Error Err = Error::success();
10259 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010260 // Strong symbols don't have a location to update.
10261 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010262 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010263 << Entry.symbolName() << "\n";
10264 continue;
10265 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010266 StringRef SegmentName = Entry.segmentName();
10267 StringRef SectionName = Entry.sectionName();
10268 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010269
10270 // Table lines look like:
10271 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010272 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010273 << left_justify(SectionName, 18) << " "
10274 << format_hex(Address, 10, true) << " "
10275 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010276 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10277 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010278 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010279 if (Err)
10280 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +000010281}
10282
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010283// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10284// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10285// information for that address. If the address is found its binding symbol
10286// name is returned. If not nullptr is returned.
10287static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10288 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010289 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010290 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010291 Error Err = Error::success();
10292 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010293 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010294 StringRef name = Entry.symbolName();
10295 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010296 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010297 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010298 if (Err)
10299 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010300 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010301 auto name = info->bindtable->lookup(ReferenceValue);
10302 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010303}
Michael Trent1854ecc2017-12-05 07:50:00 +000010304