blob: 23dc18f151d998e752ed572c1f468dc8bc0a9c51 [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the MachO-specific dumper for llvm-objdump.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000014#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000016#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000018#include "llvm/BinaryFormat/MachO.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000019#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000020#include "llvm/DebugInfo/DIContext.h"
21#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000022#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000024#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000025#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000028#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000030#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000031#include "llvm/MC/MCSubtargetInfo.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000033#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000034#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000037#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000041#include "llvm/Support/LEB128.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000045#include "llvm/Support/ToolOutputFile.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000046#include "llvm/Support/WithColor.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include <algorithm>
49#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000050#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000051
Kevin Enderby9873e2c2016-05-23 21:34:12 +000052#ifdef HAVE_LIBXAR
53extern "C" {
54#include <xar/xar.h>
55}
56#endif
57
Benjamin Kramer43a772e2011-09-19 17:56:04 +000058using namespace llvm;
59using namespace object;
60
61static cl::opt<bool>
Matthew Voss0f436772019-02-19 19:46:08 +000062 UseDbg("g", cl::Grouping,
Kevin Enderbyb28ed012014-10-29 21:28:24 +000063 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<std::string> DSYMFile("dsym",
66 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000070
Kevin Enderbyf9d60f02016-11-29 21:43:40 +000071static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
72 cl::desc("Print no leading headers"));
73
Kevin Enderby13023a12015-01-15 23:19:11 +000074cl::opt<bool> llvm::UniversalHeaders("universal-headers",
75 cl::desc("Print Mach-O universal headers "
76 "(requires -macho)"));
77
Kevin Enderby131d1772015-01-09 19:22:37 +000078cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000079 ArchiveMemberOffsets("archive-member-offsets",
80 cl::desc("Print the offset to each archive member for "
81 "Mach-O archives (requires -macho and "
82 "-archive-headers)"));
83
84cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000085 llvm::IndirectSymbols("indirect-symbols",
86 cl::desc("Print indirect symbol table for Mach-O "
87 "objects (requires -macho)"));
88
Kevin Enderby69fe98d2015-01-23 18:52:17 +000089cl::opt<bool>
90 llvm::DataInCode("data-in-code",
91 cl::desc("Print the data in code table for Mach-O objects "
92 "(requires -macho)"));
93
Kevin Enderby9a509442015-01-27 21:28:24 +000094cl::opt<bool>
95 llvm::LinkOptHints("link-opt-hints",
96 cl::desc("Print the linker optimization hints for "
97 "Mach-O objects (requires -macho)"));
98
Kevin Enderbycd66be52015-03-11 22:06:32 +000099cl::opt<bool>
100 llvm::InfoPlist("info-plist",
101 cl::desc("Print the info plist section as strings for "
102 "Mach-O objects (requires -macho)"));
103
Kevin Enderbyf0640752015-03-13 17:56:32 +0000104cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000105 llvm::DylibsUsed("dylibs-used",
106 cl::desc("Print the shared libraries used for linked "
107 "Mach-O files (requires -macho)"));
108
109cl::opt<bool>
110 llvm::DylibId("dylib-id",
111 cl::desc("Print the shared library's id for the dylib Mach-O "
112 "file (requires -macho)"));
113
114cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000115 llvm::NonVerbose("non-verbose",
116 cl::desc("Print the info for Mach-O objects in "
117 "non-verbose or numeric form (requires -macho)"));
118
Kevin Enderby0fc11822015-04-01 20:57:01 +0000119cl::opt<bool>
120 llvm::ObjcMetaData("objc-meta-data",
121 cl::desc("Print the Objective-C runtime meta data for "
122 "Mach-O files (requires -macho)"));
123
Kevin Enderby6a221752015-03-17 17:10:57 +0000124cl::opt<std::string> llvm::DisSymName(
125 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000126 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000127
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000128static cl::opt<bool> NoSymbolicOperands(
129 "no-symbolic-operands",
130 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
131
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000132static cl::list<std::string>
133 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
134 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000135
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000136bool ArchAll = false;
137
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000138static std::string ThumbTripleName;
139
140static const Target *GetTarget(const MachOObjectFile *MachOObj,
141 const char **McpuDefault,
142 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000143 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000144 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000145 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000146 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000147 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000148 }
149
150 if (TT.getArch() == Triple::arm) {
151 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
152 // that support ARM are also capable of Thumb mode.
153 llvm::Triple ThumbTriple = TT;
154 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
155 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000156 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 }
158
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000159 // Get the target specific parser.
160 std::string Error;
161 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000162 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000163 return TheTarget;
164
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000165 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
166 if (*ThumbTarget)
167 return TheTarget;
168
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000169 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 if (!TheTarget)
171 errs() << TripleName;
172 else
173 errs() << ThumbTripleName;
174 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000175 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000176}
177
Owen Andersond9243c42011-10-17 21:37:35 +0000178struct SymbolSorter {
179 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000180 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000181 if (!ATypeOrErr)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000182 report_error(ATypeOrErr.takeError(), A.getObject()->getFileName());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000183 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000184 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000185 if (!BTypeOrErr)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000186 report_error(BTypeOrErr.takeError(), B.getObject()->getFileName());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000187 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000188 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
189 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000190 return AAddr < BAddr;
191 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000192};
193
Kevin Enderby273ae012013-06-06 17:20:50 +0000194// Types for the storted data in code table that is built before disassembly
195// and the predicate function to sort them.
196typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
197typedef std::vector<DiceTableEntry> DiceTable;
198typedef DiceTable::iterator dice_table_iterator;
199
Francis Ricci195a66f2017-10-06 15:54:20 +0000200#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000201namespace {
202struct ScopedXarFile {
203 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000204 ScopedXarFile(const char *filename, int32_t flags)
205 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000206 ~ScopedXarFile() {
207 if (xar)
208 xar_close(xar);
209 }
210 ScopedXarFile(const ScopedXarFile &) = delete;
211 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
212 operator xar_t() { return xar; }
213};
214
215struct ScopedXarIter {
216 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000217 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000218 ~ScopedXarIter() {
219 if (iter)
220 xar_iter_free(iter);
221 }
222 ScopedXarIter(const ScopedXarIter &) = delete;
223 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
224 operator xar_iter_t() { return iter; }
225};
226} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000227#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000228
Kevin Enderby930fdc72014-11-06 19:00:13 +0000229// This is used to search for a data in code table entry for the PC being
230// disassembled. The j parameter has the PC in j.first. A single data in code
231// table entry can cover many bytes for each of its Kind's. So if the offset,
232// aka the i.first value, of the data in code table entry plus its Length
233// covers the PC being searched for this will return true. If not it will
234// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000235static bool compareDiceTableEntries(const DiceTableEntry &i,
236 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 uint16_t Length;
238 i.second.getLength(Length);
239
240 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000241}
242
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000243static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000244 unsigned short Kind) {
245 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000246
247 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000249 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 if (Length >= 4) {
251 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000252 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000253 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000254 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000255 Size = 4;
256 } else if (Length >= 2) {
257 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000258 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000259 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000260 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000261 Size = 2;
262 } else {
263 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000264 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000265 Value = bytes[0];
266 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000268 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000269 if (Kind == MachO::DICE_KIND_DATA)
270 outs() << "\t@ KIND_DATA\n";
271 else
272 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000273 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000274 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000275 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000276 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000277 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000278 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
279 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000280 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000281 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000282 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000283 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000284 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000285 outs() << "\t.short " << format("%5u", Value & 0xffff)
286 << "\t@ KIND_JUMP_TABLE16\n";
287 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000288 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000289 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000290 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
291 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000292 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000293 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000294 outs() << "\t.long " << Value;
295 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
296 outs() << "\t@ KIND_JUMP_TABLE32\n";
297 else
298 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
299 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000300 break;
301 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000302 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000303}
304
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000305static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000306 std::vector<SectionRef> &Sections,
307 std::vector<SymbolRef> &Symbols,
308 SmallVectorImpl<uint64_t> &FoundFns,
309 uint64_t &BaseSegmentAddress) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000310 const StringRef FileName = MachOObj->getFileName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000311 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000312 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
313 if (!SymName.startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000314 Symbols.push_back(Symbol);
315 }
Owen Andersond9243c42011-10-17 21:37:35 +0000316
Alexey Samsonov48803e52014-03-13 14:37:36 +0000317 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000318 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000319 Section.getName(SectName);
320 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000321 }
322
Kevin Enderby273ae012013-06-06 17:20:50 +0000323 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000324 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000325 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000326 // We found a function starts segment, parse the addresses for later
327 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000328 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000329 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000330
Charles Davis8bdfafd2013-09-01 04:28:48 +0000331 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000332 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
333 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000334 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000335 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000336 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000337 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000338 }
339 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000340 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000341}
342
George Rimarc1964882019-01-18 11:33:26 +0000343static void printRelocationTargetName(const MachOObjectFile *O,
344 const MachO::any_relocation_info &RE,
345 raw_string_ostream &Fmt) {
346 // Target of a scattered relocation is an address. In the interest of
347 // generating pretty output, scan through the symbol table looking for a
348 // symbol that aligns with that address. If we find one, print it.
349 // Otherwise, we just print the hex address of the target.
Fangrui Songe7834bd2019-04-07 08:19:55 +0000350 const StringRef FileName = O->getFileName();
George Rimarc1964882019-01-18 11:33:26 +0000351 if (O->isRelocationScattered(RE)) {
352 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
353
354 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000355 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
356 if (Addr != Val)
George Rimarc1964882019-01-18 11:33:26 +0000357 continue;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000358 Fmt << unwrapOrError(Symbol.getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000359 return;
360 }
361
362 // If we couldn't find a symbol that this relocation refers to, try
363 // to find a section beginning instead.
364 for (const SectionRef &Section : ToolSectionFilter(*O)) {
365 std::error_code ec;
366
367 StringRef Name;
368 uint64_t Addr = Section.getAddress();
369 if (Addr != Val)
370 continue;
371 if ((ec = Section.getName(Name)))
372 report_error(O->getFileName(), ec);
373 Fmt << Name;
374 return;
375 }
376
377 Fmt << format("0x%x", Val);
378 return;
379 }
380
381 StringRef S;
382 bool isExtern = O->getPlainRelocationExternal(RE);
383 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
384
385 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
386 Fmt << format("0x%0" PRIx64, Val);
387 return;
388 }
389
390 if (isExtern) {
391 symbol_iterator SI = O->symbol_begin();
392 advance(SI, Val);
Fangrui Songe7834bd2019-04-07 08:19:55 +0000393 S = unwrapOrError(SI->getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000394 } else {
395 section_iterator SI = O->section_begin();
396 // Adjust for the fact that sections are 1-indexed.
397 if (Val == 0) {
398 Fmt << "0 (?,?)";
399 return;
400 }
401 uint32_t I = Val - 1;
402 while (I != 0 && SI != O->section_end()) {
403 --I;
404 advance(SI, 1);
405 }
406 if (SI == O->section_end())
407 Fmt << Val << " (?,?)";
408 else
409 SI->getName(S);
410 }
411
412 Fmt << S;
413}
414
Fangrui Songf67de6c2019-04-08 16:24:08 +0000415Error llvm::getMachORelocationValueString(const MachOObjectFile *Obj,
416 const RelocationRef &RelRef,
417 SmallVectorImpl<char> &Result) {
George Rimarc1964882019-01-18 11:33:26 +0000418 DataRefImpl Rel = RelRef.getRawDataRefImpl();
419 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
420
421 unsigned Arch = Obj->getArch();
422
423 std::string FmtBuf;
424 raw_string_ostream Fmt(FmtBuf);
425 unsigned Type = Obj->getAnyRelocationType(RE);
426 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
427
428 // Determine any addends that should be displayed with the relocation.
429 // These require decoding the relocation type, which is triple-specific.
430
431 // X86_64 has entirely custom relocation types.
432 if (Arch == Triple::x86_64) {
433 switch (Type) {
434 case MachO::X86_64_RELOC_GOT_LOAD:
435 case MachO::X86_64_RELOC_GOT: {
436 printRelocationTargetName(Obj, RE, Fmt);
437 Fmt << "@GOT";
438 if (IsPCRel)
439 Fmt << "PCREL";
440 break;
441 }
442 case MachO::X86_64_RELOC_SUBTRACTOR: {
443 DataRefImpl RelNext = Rel;
444 Obj->moveRelocationNext(RelNext);
445 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
446
447 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
448 // X86_64_RELOC_UNSIGNED.
449 // NOTE: Scattered relocations don't exist on x86_64.
450 unsigned RType = Obj->getAnyRelocationType(RENext);
451 if (RType != MachO::X86_64_RELOC_UNSIGNED)
452 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
453 "X86_64_RELOC_SUBTRACTOR.");
454
455 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
456 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
457 printRelocationTargetName(Obj, RENext, Fmt);
458 Fmt << "-";
459 printRelocationTargetName(Obj, RE, Fmt);
460 break;
461 }
462 case MachO::X86_64_RELOC_TLV:
463 printRelocationTargetName(Obj, RE, Fmt);
464 Fmt << "@TLV";
465 if (IsPCRel)
466 Fmt << "P";
467 break;
468 case MachO::X86_64_RELOC_SIGNED_1:
469 printRelocationTargetName(Obj, RE, Fmt);
470 Fmt << "-1";
471 break;
472 case MachO::X86_64_RELOC_SIGNED_2:
473 printRelocationTargetName(Obj, RE, Fmt);
474 Fmt << "-2";
475 break;
476 case MachO::X86_64_RELOC_SIGNED_4:
477 printRelocationTargetName(Obj, RE, Fmt);
478 Fmt << "-4";
479 break;
480 default:
481 printRelocationTargetName(Obj, RE, Fmt);
482 break;
483 }
484 // X86 and ARM share some relocation types in common.
485 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
486 Arch == Triple::ppc) {
487 // Generic relocation types...
488 switch (Type) {
489 case MachO::GENERIC_RELOC_PAIR: // prints no info
Fangrui Songf67de6c2019-04-08 16:24:08 +0000490 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000491 case MachO::GENERIC_RELOC_SECTDIFF: {
492 DataRefImpl RelNext = Rel;
493 Obj->moveRelocationNext(RelNext);
494 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
495
496 // X86 sect diff's must be followed by a relocation of type
497 // GENERIC_RELOC_PAIR.
498 unsigned RType = Obj->getAnyRelocationType(RENext);
499
500 if (RType != MachO::GENERIC_RELOC_PAIR)
501 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
502 "GENERIC_RELOC_SECTDIFF.");
503
504 printRelocationTargetName(Obj, RE, Fmt);
505 Fmt << "-";
506 printRelocationTargetName(Obj, RENext, Fmt);
507 break;
508 }
509 }
510
511 if (Arch == Triple::x86 || Arch == Triple::ppc) {
512 switch (Type) {
513 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
514 DataRefImpl RelNext = Rel;
515 Obj->moveRelocationNext(RelNext);
516 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
517
518 // X86 sect diff's must be followed by a relocation of type
519 // GENERIC_RELOC_PAIR.
520 unsigned RType = Obj->getAnyRelocationType(RENext);
521 if (RType != MachO::GENERIC_RELOC_PAIR)
522 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
523 "GENERIC_RELOC_LOCAL_SECTDIFF.");
524
525 printRelocationTargetName(Obj, RE, Fmt);
526 Fmt << "-";
527 printRelocationTargetName(Obj, RENext, Fmt);
528 break;
529 }
530 case MachO::GENERIC_RELOC_TLV: {
531 printRelocationTargetName(Obj, RE, Fmt);
532 Fmt << "@TLV";
533 if (IsPCRel)
534 Fmt << "P";
535 break;
536 }
537 default:
538 printRelocationTargetName(Obj, RE, Fmt);
539 }
540 } else { // ARM-specific relocations
541 switch (Type) {
542 case MachO::ARM_RELOC_HALF:
543 case MachO::ARM_RELOC_HALF_SECTDIFF: {
544 // Half relocations steal a bit from the length field to encode
545 // whether this is an upper16 or a lower16 relocation.
546 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
547
548 if (isUpper)
549 Fmt << ":upper16:(";
550 else
551 Fmt << ":lower16:(";
552 printRelocationTargetName(Obj, RE, Fmt);
553
554 DataRefImpl RelNext = Rel;
555 Obj->moveRelocationNext(RelNext);
556 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
557
558 // ARM half relocs must be followed by a relocation of type
559 // ARM_RELOC_PAIR.
560 unsigned RType = Obj->getAnyRelocationType(RENext);
561 if (RType != MachO::ARM_RELOC_PAIR)
562 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
563 "ARM_RELOC_HALF");
564
565 // NOTE: The half of the target virtual address is stashed in the
566 // address field of the secondary relocation, but we can't reverse
567 // engineer the constant offset from it without decoding the movw/movt
568 // instruction to find the other half in its immediate field.
569
570 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
571 // symbol/section pointer of the follow-on relocation.
572 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
573 Fmt << "-";
574 printRelocationTargetName(Obj, RENext, Fmt);
575 }
576
577 Fmt << ")";
578 break;
579 }
580 default: {
581 printRelocationTargetName(Obj, RE, Fmt);
582 }
583 }
584 }
585 } else
586 printRelocationTargetName(Obj, RE, Fmt);
587
588 Fmt.flush();
589 Result.append(FmtBuf.begin(), FmtBuf.end());
Fangrui Songf67de6c2019-04-08 16:24:08 +0000590 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000591}
592
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000593static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
594 uint32_t n, uint32_t count,
595 uint32_t stride, uint64_t addr) {
596 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
597 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
598 if (n > nindirectsyms)
599 outs() << " (entries start past the end of the indirect symbol "
600 "table) (reserved1 field greater than the table size)";
601 else if (n + count > nindirectsyms)
602 outs() << " (entries extends past the end of the indirect symbol "
603 "table)";
604 outs() << "\n";
605 uint32_t cputype = O->getHeader().cputype;
606 if (cputype & MachO::CPU_ARCH_ABI64)
607 outs() << "address index";
608 else
609 outs() << "address index";
610 if (verbose)
611 outs() << " name\n";
612 else
613 outs() << "\n";
614 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
615 if (cputype & MachO::CPU_ARCH_ABI64)
616 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
617 else
Tim Northover43978372016-04-26 18:29:16 +0000618 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000619 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
620 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
621 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
622 outs() << "LOCAL\n";
623 continue;
624 }
625 if (indirect_symbol ==
626 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
627 outs() << "LOCAL ABSOLUTE\n";
628 continue;
629 }
630 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
631 outs() << "ABSOLUTE\n";
632 continue;
633 }
634 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000635 if (verbose) {
636 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
637 if (indirect_symbol < Symtab.nsyms) {
638 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
639 SymbolRef Symbol = *Sym;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000640 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
Kevin Enderbyf0640752015-03-13 17:56:32 +0000641 } else {
642 outs() << "?";
643 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000644 }
645 outs() << "\n";
646 }
647}
648
649static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000650 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000651 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
652 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
653 for (unsigned J = 0; J < Seg.nsects; ++J) {
654 MachO::section_64 Sec = O->getSection64(Load, J);
655 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
656 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
657 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
658 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
659 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
660 section_type == MachO::S_SYMBOL_STUBS) {
661 uint32_t stride;
662 if (section_type == MachO::S_SYMBOL_STUBS)
663 stride = Sec.reserved2;
664 else
665 stride = 8;
666 if (stride == 0) {
667 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
668 << Sec.sectname << ") "
669 << "(size of stubs in reserved2 field is zero)\n";
670 continue;
671 }
672 uint32_t count = Sec.size / stride;
673 outs() << "Indirect symbols for (" << Sec.segname << ","
674 << Sec.sectname << ") " << count << " entries";
675 uint32_t n = Sec.reserved1;
676 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
677 }
678 }
679 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
680 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
681 for (unsigned J = 0; J < Seg.nsects; ++J) {
682 MachO::section Sec = O->getSection(Load, J);
683 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
684 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
685 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
686 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
687 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
688 section_type == MachO::S_SYMBOL_STUBS) {
689 uint32_t stride;
690 if (section_type == MachO::S_SYMBOL_STUBS)
691 stride = Sec.reserved2;
692 else
693 stride = 4;
694 if (stride == 0) {
695 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
696 << Sec.sectname << ") "
697 << "(size of stubs in reserved2 field is zero)\n";
698 continue;
699 }
700 uint32_t count = Sec.size / stride;
701 outs() << "Indirect symbols for (" << Sec.segname << ","
702 << Sec.sectname << ") " << count << " entries";
703 uint32_t n = Sec.reserved1;
704 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
705 }
706 }
707 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000708 }
709}
710
Michael Trenta1703b12017-12-15 17:57:40 +0000711static void PrintRType(const uint64_t cputype, const unsigned r_type) {
712 static char const *generic_r_types[] = {
713 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
714 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
715 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
716 };
717 static char const *x86_64_r_types[] = {
718 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
719 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
720 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
721 };
722 static char const *arm_r_types[] = {
723 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
724 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
725 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
726 };
727 static char const *arm64_r_types[] = {
728 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
729 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
730 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
731 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000732
Michael Trenta1703b12017-12-15 17:57:40 +0000733 if (r_type > 0xf){
734 outs() << format("%-7u", r_type) << " ";
735 return;
736 }
737 switch (cputype) {
738 case MachO::CPU_TYPE_I386:
739 outs() << generic_r_types[r_type];
740 break;
741 case MachO::CPU_TYPE_X86_64:
742 outs() << x86_64_r_types[r_type];
743 break;
744 case MachO::CPU_TYPE_ARM:
745 outs() << arm_r_types[r_type];
746 break;
747 case MachO::CPU_TYPE_ARM64:
748 outs() << arm64_r_types[r_type];
749 break;
750 default:
751 outs() << format("%-7u ", r_type);
752 }
753}
754
755static void PrintRLength(const uint64_t cputype, const unsigned r_type,
756 const unsigned r_length, const bool previous_arm_half){
757 if (cputype == MachO::CPU_TYPE_ARM &&
758 (r_type == llvm::MachO::ARM_RELOC_HALF ||
759 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
760 previous_arm_half == true)) {
761 if ((r_length & 0x1) == 0)
762 outs() << "lo/";
763 else
764 outs() << "hi/";
765 if ((r_length & 0x1) == 0)
766 outs() << "arm ";
767 else
768 outs() << "thm ";
769 } else {
770 switch (r_length) {
771 case 0:
772 outs() << "byte ";
773 break;
774 case 1:
775 outs() << "word ";
776 break;
777 case 2:
778 outs() << "long ";
779 break;
780 case 3:
781 if (cputype == MachO::CPU_TYPE_X86_64)
782 outs() << "quad ";
783 else
784 outs() << format("?(%2d) ", r_length);
785 break;
786 default:
787 outs() << format("?(%2d) ", r_length);
788 }
789 }
790}
791
792static void PrintRelocationEntries(const MachOObjectFile *O,
793 const relocation_iterator Begin,
794 const relocation_iterator End,
795 const uint64_t cputype,
796 const bool verbose) {
797 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
798 bool previous_arm_half = false;
799 bool previous_sectdiff = false;
800 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000801
Michael Trenta1703b12017-12-15 17:57:40 +0000802 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
803 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
804 const MachO::any_relocation_info RE = O->getRelocation(Rel);
805 const unsigned r_type = O->getAnyRelocationType(RE);
806 const bool r_scattered = O->isRelocationScattered(RE);
807 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
808 const unsigned r_length = O->getAnyRelocationLength(RE);
809 const unsigned r_address = O->getAnyRelocationAddress(RE);
810 const bool r_extern = (r_scattered ? false :
811 O->getPlainRelocationExternal(RE));
812 const uint32_t r_value = (r_scattered ?
813 O->getScatteredRelocationValue(RE) : 0);
814 const unsigned r_symbolnum = (r_scattered ? 0 :
815 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000816
Michael Trenta1703b12017-12-15 17:57:40 +0000817 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
818 if (verbose) {
819 // scattered: address
820 if ((cputype == MachO::CPU_TYPE_I386 &&
821 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
822 (cputype == MachO::CPU_TYPE_ARM &&
823 r_type == llvm::MachO::ARM_RELOC_PAIR))
824 outs() << " ";
825 else
826 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000827
Michael Trenta1703b12017-12-15 17:57:40 +0000828 // scattered: pcrel
829 if (r_pcrel)
830 outs() << "True ";
831 else
832 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000833
Michael Trenta1703b12017-12-15 17:57:40 +0000834 // scattered: length
835 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000836
Michael Trenta1703b12017-12-15 17:57:40 +0000837 // scattered: extern & type
838 outs() << "n/a ";
839 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000840
Michael Trenta1703b12017-12-15 17:57:40 +0000841 // scattered: scattered & value
842 outs() << format("True 0x%08x", (unsigned int)r_value);
843 if (previous_sectdiff == false) {
844 if ((cputype == MachO::CPU_TYPE_ARM &&
845 r_type == llvm::MachO::ARM_RELOC_PAIR))
846 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
847 }
848 else if (cputype == MachO::CPU_TYPE_ARM &&
849 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
850 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
851 if ((cputype == MachO::CPU_TYPE_I386 &&
852 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
853 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
854 (cputype == MachO::CPU_TYPE_ARM &&
855 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
856 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
857 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
858 previous_sectdiff = true;
859 sectdiff_r_type = r_type;
860 }
861 else {
862 previous_sectdiff = false;
863 sectdiff_r_type = 0;
864 }
865 if (cputype == MachO::CPU_TYPE_ARM &&
866 (r_type == llvm::MachO::ARM_RELOC_HALF ||
867 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
868 previous_arm_half = true;
869 else
870 previous_arm_half = false;
871 outs() << "\n";
872 }
873 else {
874 // scattered: address pcrel length extern type scattered value
875 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
876 (unsigned int)r_address, r_pcrel, r_length, r_type,
877 (unsigned int)r_value);
878 }
879 }
880 else {
881 if (verbose) {
882 // plain: address
883 if (cputype == MachO::CPU_TYPE_ARM &&
884 r_type == llvm::MachO::ARM_RELOC_PAIR)
885 outs() << " ";
886 else
887 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000888
Michael Trenta1703b12017-12-15 17:57:40 +0000889 // plain: pcrel
890 if (r_pcrel)
891 outs() << "True ";
892 else
893 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000894
Michael Trenta1703b12017-12-15 17:57:40 +0000895 // plain: length
896 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000897
Michael Trenta1703b12017-12-15 17:57:40 +0000898 if (r_extern) {
899 // plain: extern & type & scattered
900 outs() << "True ";
901 PrintRType(cputype, r_type);
902 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000903
Michael Trenta1703b12017-12-15 17:57:40 +0000904 // plain: symbolnum/value
905 if (r_symbolnum > Symtab.nsyms)
906 outs() << format("?(%d)\n", r_symbolnum);
907 else {
908 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
909 Expected<StringRef> SymNameNext = Symbol.getName();
910 const char *name = NULL;
911 if (SymNameNext)
912 name = SymNameNext->data();
913 if (name == NULL)
914 outs() << format("?(%d)\n", r_symbolnum);
915 else
916 outs() << name << "\n";
917 }
918 }
919 else {
920 // plain: extern & type & scattered
921 outs() << "False ";
922 PrintRType(cputype, r_type);
923 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000924
Michael Trenta1703b12017-12-15 17:57:40 +0000925 // plain: symbolnum/value
926 if (cputype == MachO::CPU_TYPE_ARM &&
927 r_type == llvm::MachO::ARM_RELOC_PAIR)
928 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
929 else if (cputype == MachO::CPU_TYPE_ARM64 &&
930 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
931 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
932 else {
933 outs() << format("%d ", r_symbolnum);
934 if (r_symbolnum == llvm::MachO::R_ABS)
935 outs() << "R_ABS\n";
936 else {
937 // in this case, r_symbolnum is actually a 1-based section number
938 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
939 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
940 llvm::object::DataRefImpl DRI;
941 DRI.d.a = r_symbolnum-1;
942 StringRef SegName = O->getSectionFinalSegmentName(DRI);
943 StringRef SectName;
944 if (O->getSectionName(DRI, SectName))
945 outs() << "(?,?)\n";
946 else
947 outs() << "(" << SegName << "," << SectName << ")\n";
948 }
949 else {
950 outs() << "(?,?)\n";
951 }
952 }
953 }
954 }
955 if (cputype == MachO::CPU_TYPE_ARM &&
956 (r_type == llvm::MachO::ARM_RELOC_HALF ||
957 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
958 previous_arm_half = true;
959 else
960 previous_arm_half = false;
961 }
962 else {
963 // plain: address pcrel length extern type scattered symbolnum/section
964 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
965 (unsigned int)r_address, r_pcrel, r_length, r_extern,
966 r_type, r_symbolnum);
967 }
968 }
969 }
970}
971
972static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
973 const uint64_t cputype = O->getHeader().cputype;
974 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
975 if (Dysymtab.nextrel != 0) {
976 outs() << "External relocation information " << Dysymtab.nextrel
977 << " entries";
978 outs() << "\naddress pcrel length extern type scattered "
979 "symbolnum/value\n";
980 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
981 verbose);
982 }
983 if (Dysymtab.nlocrel != 0) {
984 outs() << format("Local relocation information %u entries",
985 Dysymtab.nlocrel);
986 outs() << "\naddress pcrel length extern type scattered "
987 "symbolnum/value\n";
988 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
989 verbose);
990 }
991 for (const auto &Load : O->load_commands()) {
992 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
993 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
994 for (unsigned J = 0; J < Seg.nsects; ++J) {
995 const MachO::section_64 Sec = O->getSection64(Load, J);
996 if (Sec.nreloc != 0) {
997 DataRefImpl DRI;
998 DRI.d.a = J;
999 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1000 StringRef SectName;
1001 if (O->getSectionName(DRI, SectName))
1002 outs() << "Relocation information (" << SegName << ",?) "
1003 << format("%u entries", Sec.nreloc);
1004 else
1005 outs() << "Relocation information (" << SegName << ","
1006 << SectName << format(") %u entries", Sec.nreloc);
1007 outs() << "\naddress pcrel length extern type scattered "
1008 "symbolnum/value\n";
1009 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1010 O->section_rel_end(DRI), cputype, verbose);
1011 }
1012 }
1013 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1014 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1015 for (unsigned J = 0; J < Seg.nsects; ++J) {
1016 const MachO::section Sec = O->getSection(Load, J);
1017 if (Sec.nreloc != 0) {
1018 DataRefImpl DRI;
1019 DRI.d.a = J;
1020 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1021 StringRef SectName;
1022 if (O->getSectionName(DRI, SectName))
1023 outs() << "Relocation information (" << SegName << ",?) "
1024 << format("%u entries", Sec.nreloc);
1025 else
1026 outs() << "Relocation information (" << SegName << ","
1027 << SectName << format(") %u entries", Sec.nreloc);
1028 outs() << "\naddress pcrel length extern type scattered "
1029 "symbolnum/value\n";
1030 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1031 O->section_rel_end(DRI), cputype, verbose);
1032 }
1033 }
1034 }
1035 }
1036}
1037
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001038static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1039 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1040 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1041 outs() << "Data in code table (" << nentries << " entries)\n";
1042 outs() << "offset length kind\n";
1043 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1044 ++DI) {
1045 uint32_t Offset;
1046 DI->getOffset(Offset);
1047 outs() << format("0x%08" PRIx32, Offset) << " ";
1048 uint16_t Length;
1049 DI->getLength(Length);
1050 outs() << format("%6u", Length) << " ";
1051 uint16_t Kind;
1052 DI->getKind(Kind);
1053 if (verbose) {
1054 switch (Kind) {
1055 case MachO::DICE_KIND_DATA:
1056 outs() << "DATA";
1057 break;
1058 case MachO::DICE_KIND_JUMP_TABLE8:
1059 outs() << "JUMP_TABLE8";
1060 break;
1061 case MachO::DICE_KIND_JUMP_TABLE16:
1062 outs() << "JUMP_TABLE16";
1063 break;
1064 case MachO::DICE_KIND_JUMP_TABLE32:
1065 outs() << "JUMP_TABLE32";
1066 break;
1067 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1068 outs() << "ABS_JUMP_TABLE32";
1069 break;
1070 default:
1071 outs() << format("0x%04" PRIx32, Kind);
1072 break;
1073 }
1074 } else
1075 outs() << format("0x%04" PRIx32, Kind);
1076 outs() << "\n";
1077 }
1078}
1079
Kevin Enderby9a509442015-01-27 21:28:24 +00001080static void PrintLinkOptHints(MachOObjectFile *O) {
1081 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1082 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1083 uint32_t nloh = LohLC.datasize;
1084 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1085 for (uint32_t i = 0; i < nloh;) {
1086 unsigned n;
1087 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1088 i += n;
1089 outs() << " identifier " << identifier << " ";
1090 if (i >= nloh)
1091 return;
1092 switch (identifier) {
1093 case 1:
1094 outs() << "AdrpAdrp\n";
1095 break;
1096 case 2:
1097 outs() << "AdrpLdr\n";
1098 break;
1099 case 3:
1100 outs() << "AdrpAddLdr\n";
1101 break;
1102 case 4:
1103 outs() << "AdrpLdrGotLdr\n";
1104 break;
1105 case 5:
1106 outs() << "AdrpAddStr\n";
1107 break;
1108 case 6:
1109 outs() << "AdrpLdrGotStr\n";
1110 break;
1111 case 7:
1112 outs() << "AdrpAdd\n";
1113 break;
1114 case 8:
1115 outs() << "AdrpLdrGot\n";
1116 break;
1117 default:
1118 outs() << "Unknown identifier value\n";
1119 break;
1120 }
1121 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1122 i += n;
1123 outs() << " narguments " << narguments << "\n";
1124 if (i >= nloh)
1125 return;
1126
1127 for (uint32_t j = 0; j < narguments; j++) {
1128 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1129 i += n;
1130 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1131 if (i >= nloh)
1132 return;
1133 }
1134 }
1135}
1136
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001137static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001138 unsigned Index = 0;
1139 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001140 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1141 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1142 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1143 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1144 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1145 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1146 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1147 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1148 if (dl.dylib.name < dl.cmdsize) {
1149 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1150 if (JustId)
1151 outs() << p << "\n";
1152 else {
1153 outs() << "\t" << p;
1154 outs() << " (compatibility version "
1155 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1156 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1157 << (dl.dylib.compatibility_version & 0xff) << ",";
1158 outs() << " current version "
1159 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1160 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1161 << (dl.dylib.current_version & 0xff) << ")\n";
1162 }
1163 } else {
1164 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1165 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1166 outs() << "LC_ID_DYLIB ";
1167 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1168 outs() << "LC_LOAD_DYLIB ";
1169 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1170 outs() << "LC_LOAD_WEAK_DYLIB ";
1171 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1172 outs() << "LC_LAZY_LOAD_DYLIB ";
1173 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1174 outs() << "LC_REEXPORT_DYLIB ";
1175 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1176 outs() << "LC_LOAD_UPWARD_DYLIB ";
1177 else
1178 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001179 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001180 }
1181 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001182 }
1183}
1184
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001185typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1186
1187static void CreateSymbolAddressMap(MachOObjectFile *O,
1188 SymbolAddressMap *AddrMap) {
1189 // Create a map of symbol addresses to symbol names.
Fangrui Songe7834bd2019-04-07 08:19:55 +00001190 const StringRef FileName = O->getFileName();
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001191 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00001192 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001193 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1194 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00001195 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00001196 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
Kevin Enderby846c0002015-04-16 17:19:59 +00001197 if (!SymName.startswith(".objc"))
1198 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001199 }
1200 }
1201}
1202
1203// GuessSymbolName is passed the address of what might be a symbol and a
1204// pointer to the SymbolAddressMap. It returns the name of a symbol
1205// with that address or nullptr if no symbol is found with that address.
1206static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1207 const char *SymbolName = nullptr;
1208 // A DenseMap can't lookup up some values.
1209 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1210 StringRef name = AddrMap->lookup(value);
1211 if (!name.empty())
1212 SymbolName = name.data();
1213 }
1214 return SymbolName;
1215}
1216
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001217static void DumpCstringChar(const char c) {
1218 char p[2];
1219 p[0] = c;
1220 p[1] = '\0';
1221 outs().write_escaped(p);
1222}
1223
Kevin Enderby10ba0412015-02-04 21:38:42 +00001224static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1225 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001226 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +00001227 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001228 if (print_addresses) {
1229 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001230 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001231 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001232 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001233 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001234 for (; i < sect_size && sect[i] != '\0'; i++)
1235 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001236 if (i < sect_size && sect[i] == '\0')
1237 outs() << "\n";
1238 }
1239}
1240
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001241static void DumpLiteral4(uint32_t l, float f) {
1242 outs() << format("0x%08" PRIx32, l);
1243 if ((l & 0x7f800000) != 0x7f800000)
1244 outs() << format(" (%.16e)\n", f);
1245 else {
1246 if (l == 0x7f800000)
1247 outs() << " (+Infinity)\n";
1248 else if (l == 0xff800000)
1249 outs() << " (-Infinity)\n";
1250 else if ((l & 0x00400000) == 0x00400000)
1251 outs() << " (non-signaling Not-a-Number)\n";
1252 else
1253 outs() << " (signaling Not-a-Number)\n";
1254 }
1255}
1256
1257static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1258 uint32_t sect_size, uint64_t sect_addr,
1259 bool print_addresses) {
1260 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1261 if (print_addresses) {
1262 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001263 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001264 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001265 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001266 }
1267 float f;
1268 memcpy(&f, sect + i, sizeof(float));
1269 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1270 sys::swapByteOrder(f);
1271 uint32_t l;
1272 memcpy(&l, sect + i, sizeof(uint32_t));
1273 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1274 sys::swapByteOrder(l);
1275 DumpLiteral4(l, f);
1276 }
1277}
1278
1279static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1280 double d) {
1281 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1282 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001283 Hi = (O->isLittleEndian()) ? l1 : l0;
1284 Lo = (O->isLittleEndian()) ? l0 : l1;
1285
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001286 // Hi is the high word, so this is equivalent to if(isfinite(d))
1287 if ((Hi & 0x7ff00000) != 0x7ff00000)
1288 outs() << format(" (%.16e)\n", d);
1289 else {
1290 if (Hi == 0x7ff00000 && Lo == 0)
1291 outs() << " (+Infinity)\n";
1292 else if (Hi == 0xfff00000 && Lo == 0)
1293 outs() << " (-Infinity)\n";
1294 else if ((Hi & 0x00080000) == 0x00080000)
1295 outs() << " (non-signaling Not-a-Number)\n";
1296 else
1297 outs() << " (signaling Not-a-Number)\n";
1298 }
1299}
1300
1301static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1302 uint32_t sect_size, uint64_t sect_addr,
1303 bool print_addresses) {
1304 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1305 if (print_addresses) {
1306 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001307 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001308 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001309 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001310 }
1311 double d;
1312 memcpy(&d, sect + i, sizeof(double));
1313 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1314 sys::swapByteOrder(d);
1315 uint32_t l0, l1;
1316 memcpy(&l0, sect + i, sizeof(uint32_t));
1317 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1318 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1319 sys::swapByteOrder(l0);
1320 sys::swapByteOrder(l1);
1321 }
1322 DumpLiteral8(O, l0, l1, d);
1323 }
1324}
1325
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001326static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1327 outs() << format("0x%08" PRIx32, l0) << " ";
1328 outs() << format("0x%08" PRIx32, l1) << " ";
1329 outs() << format("0x%08" PRIx32, l2) << " ";
1330 outs() << format("0x%08" PRIx32, l3) << "\n";
1331}
1332
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001333static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1334 uint32_t sect_size, uint64_t sect_addr,
1335 bool print_addresses) {
1336 for (uint32_t i = 0; i < sect_size; i += 16) {
1337 if (print_addresses) {
1338 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001339 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001340 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001341 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001342 }
1343 uint32_t l0, l1, l2, l3;
1344 memcpy(&l0, sect + i, sizeof(uint32_t));
1345 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1346 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1347 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1348 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1349 sys::swapByteOrder(l0);
1350 sys::swapByteOrder(l1);
1351 sys::swapByteOrder(l2);
1352 sys::swapByteOrder(l3);
1353 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001354 DumpLiteral16(l0, l1, l2, l3);
1355 }
1356}
1357
1358static void DumpLiteralPointerSection(MachOObjectFile *O,
1359 const SectionRef &Section,
1360 const char *sect, uint32_t sect_size,
1361 uint64_t sect_addr,
1362 bool print_addresses) {
1363 // Collect the literal sections in this Mach-O file.
1364 std::vector<SectionRef> LiteralSections;
1365 for (const SectionRef &Section : O->sections()) {
1366 DataRefImpl Ref = Section.getRawDataRefImpl();
1367 uint32_t section_type;
1368 if (O->is64Bit()) {
1369 const MachO::section_64 Sec = O->getSection64(Ref);
1370 section_type = Sec.flags & MachO::SECTION_TYPE;
1371 } else {
1372 const MachO::section Sec = O->getSection(Ref);
1373 section_type = Sec.flags & MachO::SECTION_TYPE;
1374 }
1375 if (section_type == MachO::S_CSTRING_LITERALS ||
1376 section_type == MachO::S_4BYTE_LITERALS ||
1377 section_type == MachO::S_8BYTE_LITERALS ||
1378 section_type == MachO::S_16BYTE_LITERALS)
1379 LiteralSections.push_back(Section);
1380 }
1381
1382 // Set the size of the literal pointer.
1383 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1384
Eric Christopher572e03a2015-06-19 01:53:21 +00001385 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001386 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1387 for (const RelocationRef &Reloc : Section.relocations()) {
1388 DataRefImpl Rel;
1389 MachO::any_relocation_info RE;
1390 bool isExtern = false;
1391 Rel = Reloc.getRawDataRefImpl();
1392 RE = O->getRelocation(Rel);
1393 isExtern = O->getPlainRelocationExternal(RE);
1394 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001395 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001396 symbol_iterator RelocSym = Reloc.getSymbol();
1397 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1398 }
1399 }
1400 array_pod_sort(Relocs.begin(), Relocs.end());
1401
1402 // Dump each literal pointer.
1403 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1404 if (print_addresses) {
1405 if (O->is64Bit())
1406 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1407 else
1408 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1409 }
1410 uint64_t lp;
1411 if (O->is64Bit()) {
1412 memcpy(&lp, sect + i, sizeof(uint64_t));
1413 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1414 sys::swapByteOrder(lp);
1415 } else {
1416 uint32_t li;
1417 memcpy(&li, sect + i, sizeof(uint32_t));
1418 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1419 sys::swapByteOrder(li);
1420 lp = li;
1421 }
1422
1423 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001424 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1425 return P.first == i;
1426 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001427 if (Reloc != Relocs.end()) {
1428 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001429 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1430 outs() << "external relocation entry for symbol:" << SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001431 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001432 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001433
1434 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001435 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1436 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1437 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001438 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001439 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001440 continue;
1441 }
1442
1443 uint64_t SectAddress = Sect->getAddress();
1444 uint64_t SectSize = Sect->getSize();
1445
1446 StringRef SectName;
1447 Sect->getName(SectName);
1448 DataRefImpl Ref = Sect->getRawDataRefImpl();
1449 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1450 outs() << SegmentName << ":" << SectName << ":";
1451
1452 uint32_t section_type;
1453 if (O->is64Bit()) {
1454 const MachO::section_64 Sec = O->getSection64(Ref);
1455 section_type = Sec.flags & MachO::SECTION_TYPE;
1456 } else {
1457 const MachO::section Sec = O->getSection(Ref);
1458 section_type = Sec.flags & MachO::SECTION_TYPE;
1459 }
1460
1461 StringRef BytesStr;
1462 Sect->getContents(BytesStr);
1463 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1464
1465 switch (section_type) {
1466 case MachO::S_CSTRING_LITERALS:
1467 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1468 i++) {
1469 DumpCstringChar(Contents[i]);
1470 }
1471 outs() << "\n";
1472 break;
1473 case MachO::S_4BYTE_LITERALS:
1474 float f;
1475 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1476 uint32_t l;
1477 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1478 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1479 sys::swapByteOrder(f);
1480 sys::swapByteOrder(l);
1481 }
1482 DumpLiteral4(l, f);
1483 break;
1484 case MachO::S_8BYTE_LITERALS: {
1485 double d;
1486 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1487 uint32_t l0, l1;
1488 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1489 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1490 sizeof(uint32_t));
1491 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1492 sys::swapByteOrder(f);
1493 sys::swapByteOrder(l0);
1494 sys::swapByteOrder(l1);
1495 }
1496 DumpLiteral8(O, l0, l1, d);
1497 break;
1498 }
1499 case MachO::S_16BYTE_LITERALS: {
1500 uint32_t l0, l1, l2, l3;
1501 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1502 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1503 sizeof(uint32_t));
1504 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1505 sizeof(uint32_t));
1506 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1507 sizeof(uint32_t));
1508 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1509 sys::swapByteOrder(l0);
1510 sys::swapByteOrder(l1);
1511 sys::swapByteOrder(l2);
1512 sys::swapByteOrder(l3);
1513 }
1514 DumpLiteral16(l0, l1, l2, l3);
1515 break;
1516 }
1517 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001518 }
1519}
1520
Kevin Enderby85b7a662018-03-20 20:29:52 +00001521static void DumpInitTermPointerSection(MachOObjectFile *O,
1522 const SectionRef &Section,
1523 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001524 uint32_t sect_size, uint64_t sect_addr,
1525 SymbolAddressMap *AddrMap,
1526 bool verbose) {
1527 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001528 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001529
1530 // Collect the external relocation symbols for the pointers.
1531 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1532 for (const RelocationRef &Reloc : Section.relocations()) {
1533 DataRefImpl Rel;
1534 MachO::any_relocation_info RE;
1535 bool isExtern = false;
1536 Rel = Reloc.getRawDataRefImpl();
1537 RE = O->getRelocation(Rel);
1538 isExtern = O->getPlainRelocationExternal(RE);
1539 if (isExtern) {
1540 uint64_t RelocOffset = Reloc.getOffset();
1541 symbol_iterator RelocSym = Reloc.getSymbol();
1542 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1543 }
1544 }
1545 array_pod_sort(Relocs.begin(), Relocs.end());
1546
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001547 for (uint32_t i = 0; i < sect_size; i += stride) {
1548 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001549 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001550 if (O->is64Bit()) {
1551 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1552 uint64_t pointer_value;
1553 memcpy(&pointer_value, sect + i, stride);
1554 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1555 sys::swapByteOrder(pointer_value);
1556 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001557 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001558 } else {
1559 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1560 uint32_t pointer_value;
1561 memcpy(&pointer_value, sect + i, stride);
1562 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1563 sys::swapByteOrder(pointer_value);
1564 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001565 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001566 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001567 if (verbose) {
1568 // First look for an external relocation entry for this pointer.
1569 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1570 return P.first == i;
1571 });
1572 if (Reloc != Relocs.end()) {
1573 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001574 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
Kevin Enderby85b7a662018-03-20 20:29:52 +00001575 } else {
1576 SymbolName = GuessSymbolName(p, AddrMap);
1577 if (SymbolName)
1578 outs() << " " << SymbolName;
1579 }
1580 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001581 outs() << "\n";
1582 }
1583}
1584
1585static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1586 uint32_t size, uint64_t addr) {
1587 uint32_t cputype = O->getHeader().cputype;
1588 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1589 uint32_t j;
1590 for (uint32_t i = 0; i < size; i += j, addr += j) {
1591 if (O->is64Bit())
1592 outs() << format("%016" PRIx64, addr) << "\t";
1593 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001594 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001595 for (j = 0; j < 16 && i + j < size; j++) {
1596 uint8_t byte_word = *(sect + i + j);
1597 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1598 }
1599 outs() << "\n";
1600 }
1601 } else {
1602 uint32_t j;
1603 for (uint32_t i = 0; i < size; i += j, addr += j) {
1604 if (O->is64Bit())
1605 outs() << format("%016" PRIx64, addr) << "\t";
1606 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001607 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001608 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1609 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001610 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001611 uint32_t long_word;
1612 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1613 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1614 sys::swapByteOrder(long_word);
1615 outs() << format("%08" PRIx32, long_word) << " ";
1616 } else {
1617 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001618 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001619 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1620 }
1621 }
1622 }
1623 outs() << "\n";
1624 }
1625 }
1626}
1627
Kevin Enderby95df54c2015-02-04 01:01:38 +00001628static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1629 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001630static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1631 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001632#ifdef HAVE_LIBXAR
1633static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1634 uint32_t size, bool verbose,
1635 bool PrintXarHeader, bool PrintXarFileHeaders,
1636 std::string XarMemberName);
1637#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001638
1639static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1640 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001641 SymbolAddressMap AddrMap;
1642 if (verbose)
1643 CreateSymbolAddressMap(O, &AddrMap);
1644
Colin LeMahieufcc32762015-07-29 19:08:10 +00001645 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1646 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001647 std::pair<StringRef, StringRef> DumpSegSectName;
1648 DumpSegSectName = DumpSection.split(',');
1649 StringRef DumpSegName, DumpSectName;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001650 if (!DumpSegSectName.second.empty()) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001651 DumpSegName = DumpSegSectName.first;
1652 DumpSectName = DumpSegSectName.second;
1653 } else {
1654 DumpSegName = "";
1655 DumpSectName = DumpSegSectName.first;
1656 }
1657 for (const SectionRef &Section : O->sections()) {
1658 StringRef SectName;
1659 Section.getName(SectName);
1660 DataRefImpl Ref = Section.getRawDataRefImpl();
1661 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1662 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1663 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001664
Kevin Enderby95df54c2015-02-04 01:01:38 +00001665 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001666 if (O->is64Bit()) {
1667 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001668 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001669
1670 } else {
1671 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001672 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001673 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001674 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001675
1676 StringRef BytesStr;
1677 Section.getContents(BytesStr);
1678 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1679 uint32_t sect_size = BytesStr.size();
1680 uint64_t sect_addr = Section.getAddress();
1681
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001682 outs() << "Contents of (" << SegName << "," << SectName
1683 << ") section\n";
1684
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001685 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001686 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1687 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1688 DisassembleMachO(Filename, O, SegName, SectName);
1689 continue;
1690 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001691 if (SegName == "__TEXT" && SectName == "__info_plist") {
1692 outs() << sect;
1693 continue;
1694 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001695 if (SegName == "__OBJC" && SectName == "__protocol") {
1696 DumpProtocolSection(O, sect, sect_size, sect_addr);
1697 continue;
1698 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001699#ifdef HAVE_LIBXAR
1700 if (SegName == "__LLVM" && SectName == "__bundle") {
1701 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1702 ArchiveHeaders, "");
1703 continue;
1704 }
1705#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001706 switch (section_type) {
1707 case MachO::S_REGULAR:
1708 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1709 break;
1710 case MachO::S_ZEROFILL:
1711 outs() << "zerofill section and has no contents in the file\n";
1712 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001713 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001714 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001715 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001716 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001717 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001718 break;
1719 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001720 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001721 break;
1722 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001723 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1724 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001725 case MachO::S_LITERAL_POINTERS:
1726 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001727 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001728 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001729 case MachO::S_MOD_INIT_FUNC_POINTERS:
1730 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001731 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1732 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001733 break;
1734 default:
1735 outs() << "Unknown section type ("
1736 << format("0x%08" PRIx32, section_type) << ")\n";
1737 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1738 break;
1739 }
1740 } else {
1741 if (section_type == MachO::S_ZEROFILL)
1742 outs() << "zerofill section and has no contents in the file\n";
1743 else
1744 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1745 }
1746 }
1747 }
1748 }
1749}
1750
Kevin Enderbycd66be52015-03-11 22:06:32 +00001751static void DumpInfoPlistSectionContents(StringRef Filename,
1752 MachOObjectFile *O) {
1753 for (const SectionRef &Section : O->sections()) {
1754 StringRef SectName;
1755 Section.getName(SectName);
1756 DataRefImpl Ref = Section.getRawDataRefImpl();
1757 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1758 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001759 if (!NoLeadingHeaders)
1760 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001761 StringRef BytesStr;
1762 Section.getContents(BytesStr);
1763 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001764 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001765 return;
1766 }
1767 }
1768}
1769
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001770// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1771// and if it is and there is a list of architecture flags is specified then
1772// check to make sure this Mach-O file is one of those architectures or all
1773// architectures were specified. If not then an error is generated and this
1774// routine returns false. Else it returns true.
1775static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001776 auto *MachO = dyn_cast<MachOObjectFile>(O);
1777
1778 if (!MachO || ArchAll || ArchFlags.empty())
1779 return true;
1780
1781 MachO::mach_header H;
1782 MachO::mach_header_64 H_64;
1783 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001784 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001785 if (MachO->is64Bit()) {
1786 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001787 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1788 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001789 } else {
1790 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001791 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1792 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001793 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001794 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001795 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001796 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001797 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001798 WithColor::error(errs(), "llvm-objdump")
1799 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001800 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001801 }
1802 return true;
1803}
1804
Kevin Enderby0fc11822015-04-01 20:57:01 +00001805static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1806
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001807// ProcessMachO() is passed a single opened Mach-O file, which may be an
1808// archive member and or in a slice of a universal file. It prints the
1809// the file name and header info and then processes it according to the
1810// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001811static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001812 StringRef ArchiveMemberName = StringRef(),
1813 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001814 // If we are doing some processing here on the Mach-O file print the header
1815 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001816 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001817 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1818 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1819 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001820 (!FilterSections.empty())) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001821 if (!NoLeadingHeaders) {
1822 outs() << Name;
1823 if (!ArchiveMemberName.empty())
1824 outs() << '(' << ArchiveMemberName << ')';
1825 if (!ArchitectureName.empty())
1826 outs() << " (architecture " << ArchitectureName << ")";
1827 outs() << ":\n";
1828 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001829 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001830 // To use the report_error() form with an ArchiveName and FileName set
1831 // these up based on what is passed for Name and ArchiveMemberName.
1832 StringRef ArchiveName;
1833 StringRef FileName;
1834 if (!ArchiveMemberName.empty()) {
1835 ArchiveName = Name;
1836 FileName = ArchiveMemberName;
1837 } else {
1838 ArchiveName = StringRef();
1839 FileName = Name;
1840 }
1841
1842 // If we need the symbol table to do the operation then check it here to
1843 // produce a good error message as to where the Mach-O file comes from in
1844 // the error message.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001845 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001846 if (Error Err = MachOOF->checkSymbolTable())
Fangrui Songe7834bd2019-04-07 08:19:55 +00001847 report_error(std::move(Err), ArchiveName, FileName, ArchitectureName);
1848
Michael Trent7e660212019-01-15 20:41:30 +00001849 if (DisassembleAll) {
1850 for (const SectionRef &Section : MachOOF->sections()) {
1851 StringRef SectName;
1852 Section.getName(SectName);
1853 if (SectName.equals("__text")) {
1854 DataRefImpl Ref = Section.getRawDataRefImpl();
1855 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1856 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1857 }
1858 }
1859 }
1860 else if (Disassemble) {
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001861 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001862 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001863 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1864 else
1865 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1866 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001867 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001868 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001869 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001870 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001871 if (LinkOptHints)
1872 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001873 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001874 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001875 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001876 printSectionHeaders(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001877 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001878 printSectionContents(MachOOF);
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001879 if (!FilterSections.empty())
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001880 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001881 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001882 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001883 if (DylibsUsed)
1884 PrintDylibs(MachOOF, false);
1885 if (DylibId)
1886 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001887 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001888 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001889 if (UnwindInfo)
1890 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001891 if (PrivateHeaders) {
1892 printMachOFileHeader(MachOOF);
1893 printMachOLoadCommands(MachOOF);
1894 }
1895 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001896 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001897 if (ObjcMetaData)
1898 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001899 if (ExportsTrie)
1900 printExportsTrie(MachOOF);
1901 if (Rebase)
1902 printRebaseTable(MachOOF);
1903 if (Bind)
1904 printBindTable(MachOOF);
1905 if (LazyBind)
1906 printLazyBindTable(MachOOF);
1907 if (WeakBind)
1908 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001909
1910 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001911 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001912 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001913 DIDumpOptions DumpOpts;
1914 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001915 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001916 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001917}
1918
Kevin Enderby131d1772015-01-09 19:22:37 +00001919// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1920static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1921 outs() << " cputype (" << cputype << ")\n";
1922 outs() << " cpusubtype (" << cpusubtype << ")\n";
1923}
1924
1925// printCPUType() helps print_fat_headers by printing the cputype and
1926// pusubtype (symbolically for the one's it knows about).
1927static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1928 switch (cputype) {
1929 case MachO::CPU_TYPE_I386:
1930 switch (cpusubtype) {
1931 case MachO::CPU_SUBTYPE_I386_ALL:
1932 outs() << " cputype CPU_TYPE_I386\n";
1933 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1934 break;
1935 default:
1936 printUnknownCPUType(cputype, cpusubtype);
1937 break;
1938 }
1939 break;
1940 case MachO::CPU_TYPE_X86_64:
1941 switch (cpusubtype) {
1942 case MachO::CPU_SUBTYPE_X86_64_ALL:
1943 outs() << " cputype CPU_TYPE_X86_64\n";
1944 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1945 break;
1946 case MachO::CPU_SUBTYPE_X86_64_H:
1947 outs() << " cputype CPU_TYPE_X86_64\n";
1948 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1949 break;
1950 default:
1951 printUnknownCPUType(cputype, cpusubtype);
1952 break;
1953 }
1954 break;
1955 case MachO::CPU_TYPE_ARM:
1956 switch (cpusubtype) {
1957 case MachO::CPU_SUBTYPE_ARM_ALL:
1958 outs() << " cputype CPU_TYPE_ARM\n";
1959 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1960 break;
1961 case MachO::CPU_SUBTYPE_ARM_V4T:
1962 outs() << " cputype CPU_TYPE_ARM\n";
1963 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1964 break;
1965 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1966 outs() << " cputype CPU_TYPE_ARM\n";
1967 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1968 break;
1969 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1970 outs() << " cputype CPU_TYPE_ARM\n";
1971 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1972 break;
1973 case MachO::CPU_SUBTYPE_ARM_V6:
1974 outs() << " cputype CPU_TYPE_ARM\n";
1975 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1976 break;
1977 case MachO::CPU_SUBTYPE_ARM_V6M:
1978 outs() << " cputype CPU_TYPE_ARM\n";
1979 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1980 break;
1981 case MachO::CPU_SUBTYPE_ARM_V7:
1982 outs() << " cputype CPU_TYPE_ARM\n";
1983 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1984 break;
1985 case MachO::CPU_SUBTYPE_ARM_V7EM:
1986 outs() << " cputype CPU_TYPE_ARM\n";
1987 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1988 break;
1989 case MachO::CPU_SUBTYPE_ARM_V7K:
1990 outs() << " cputype CPU_TYPE_ARM\n";
1991 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1992 break;
1993 case MachO::CPU_SUBTYPE_ARM_V7M:
1994 outs() << " cputype CPU_TYPE_ARM\n";
1995 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1996 break;
1997 case MachO::CPU_SUBTYPE_ARM_V7S:
1998 outs() << " cputype CPU_TYPE_ARM\n";
1999 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2000 break;
2001 default:
2002 printUnknownCPUType(cputype, cpusubtype);
2003 break;
2004 }
2005 break;
2006 case MachO::CPU_TYPE_ARM64:
2007 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2008 case MachO::CPU_SUBTYPE_ARM64_ALL:
2009 outs() << " cputype CPU_TYPE_ARM64\n";
2010 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2011 break;
Shoaib Meenai867131a2019-04-08 21:37:08 +00002012 case MachO::CPU_SUBTYPE_ARM64E:
2013 outs() << " cputype CPU_TYPE_ARM64\n";
2014 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2015 break;
Kevin Enderby131d1772015-01-09 19:22:37 +00002016 default:
2017 printUnknownCPUType(cputype, cpusubtype);
2018 break;
2019 }
2020 break;
2021 default:
2022 printUnknownCPUType(cputype, cpusubtype);
2023 break;
2024 }
2025}
2026
2027static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2028 bool verbose) {
2029 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00002030 if (verbose) {
2031 if (UB->getMagic() == MachO::FAT_MAGIC)
2032 outs() << "fat_magic FAT_MAGIC\n";
2033 else // UB->getMagic() == MachO::FAT_MAGIC_64
2034 outs() << "fat_magic FAT_MAGIC_64\n";
2035 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00002036 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2037
2038 uint32_t nfat_arch = UB->getNumberOfObjects();
2039 StringRef Buf = UB->getData();
2040 uint64_t size = Buf.size();
2041 uint64_t big_size = sizeof(struct MachO::fat_header) +
2042 nfat_arch * sizeof(struct MachO::fat_arch);
2043 outs() << "nfat_arch " << UB->getNumberOfObjects();
2044 if (nfat_arch == 0)
2045 outs() << " (malformed, contains zero architecture types)\n";
2046 else if (big_size > size)
2047 outs() << " (malformed, architectures past end of file)\n";
2048 else
2049 outs() << "\n";
2050
2051 for (uint32_t i = 0; i < nfat_arch; ++i) {
2052 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2053 uint32_t cputype = OFA.getCPUType();
2054 uint32_t cpusubtype = OFA.getCPUSubType();
2055 outs() << "architecture ";
2056 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2057 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2058 uint32_t other_cputype = other_OFA.getCPUType();
2059 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00002060 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00002061 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00002062 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00002063 outs() << "(illegal duplicate architecture) ";
2064 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00002065 }
Kevin Enderby131d1772015-01-09 19:22:37 +00002066 }
2067 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00002068 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00002069 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2070 } else {
2071 outs() << i << "\n";
2072 outs() << " cputype " << cputype << "\n";
2073 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2074 << "\n";
2075 }
2076 if (verbose &&
2077 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2078 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2079 else
2080 outs() << " capabilities "
2081 << format("0x%" PRIx32,
2082 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2083 outs() << " offset " << OFA.getOffset();
2084 if (OFA.getOffset() > size)
2085 outs() << " (past end of file)";
2086 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2087 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2088 outs() << "\n";
2089 outs() << " size " << OFA.getSize();
2090 big_size = OFA.getOffset() + OFA.getSize();
2091 if (big_size > size)
2092 outs() << " (past end of file)";
2093 outs() << "\n";
2094 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2095 << ")\n";
2096 }
2097}
2098
Kevin Enderby6524bd82016-07-19 20:47:07 +00002099static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2100 bool verbose, bool print_offset,
2101 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00002102 if (print_offset)
2103 outs() << C.getChildOffset() << "\t";
Fangrui Songe7834bd2019-04-07 08:19:55 +00002104 sys::fs::perms Mode =
2105 unwrapOrError(C.getAccessMode(), Filename, C, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002106 if (verbose) {
2107 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2108 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2109 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00002110 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2111 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2112 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2113 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2114 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2115 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2116 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2117 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2118 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00002119 } else {
2120 outs() << format("0%o ", Mode);
2121 }
2122
Fangrui Songe7834bd2019-04-07 08:19:55 +00002123 outs() << format(
2124 "%3d/%-3d %5" PRId64 " ",
2125 unwrapOrError(C.getUID(), Filename, C, ArchitectureName),
2126 unwrapOrError(C.getGID(), Filename, C, ArchitectureName),
2127 unwrapOrError(C.getRawSize(), Filename, C, ArchitectureName));
Kevin Enderby13023a12015-01-15 23:19:11 +00002128
2129 StringRef RawLastModified = C.getRawLastModified();
2130 if (verbose) {
2131 unsigned Seconds;
2132 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002133 outs() << "(date: \"" << RawLastModified
2134 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002135 else {
2136 // Since cime(3) returns a 26 character string of the form:
2137 // "Sun Sep 16 01:03:52 1973\n\0"
2138 // just print 24 characters.
2139 time_t t = Seconds;
2140 outs() << format("%.24s ", ctime(&t));
2141 }
2142 } else {
2143 outs() << RawLastModified << " ";
2144 }
2145
2146 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002147 Expected<StringRef> NameOrErr = C.getName();
2148 if (!NameOrErr) {
2149 consumeError(NameOrErr.takeError());
Fangrui Songe7834bd2019-04-07 08:19:55 +00002150 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2151 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002152 } else {
2153 StringRef Name = NameOrErr.get();
2154 outs() << Name << "\n";
2155 }
2156 } else {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002157 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2158 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002159 }
2160}
2161
Kevin Enderby6524bd82016-07-19 20:47:07 +00002162static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2163 bool print_offset,
2164 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002165 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002166 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00002167 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
2168
Lang Hamesfc209622016-07-14 02:24:01 +00002169 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002170 report_error(std::move(Err), StringRef(), Filename, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002171}
2172
Dave Lee3fb120f2018-08-03 00:06:38 +00002173static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002174 // Check for -arch all and verifiy the -arch flags are valid.
2175 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2176 if (ArchFlags[i] == "all") {
2177 ArchAll = true;
2178 } else {
2179 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002180 WithColor::error(errs(), "llvm-objdump")
2181 << "unknown architecture named '" + ArchFlags[i] +
2182 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002183 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002184 }
2185 }
2186 }
Dave Lee3fb120f2018-08-03 00:06:38 +00002187 return true;
2188}
2189
2190// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2191// -arch flags selecting just those slices as specified by them and also parses
2192// archive files. Then for each individual Mach-O file ProcessMachO() is
2193// called to process the file based on the command line options.
George Rimar73a27232019-01-15 09:19:18 +00002194void llvm::parseInputMachO(StringRef Filename) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002195 if (!ValidateArchFlags())
2196 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002197
2198 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002199 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002200 if (!BinaryOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002201 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2202 report_error(std::move(E), Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002203 else
2204 outs() << Filename << ": is not an object file\n";
2205 return;
2206 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002207 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00002208
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002209 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2210 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002211 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002212 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2213
Mehdi Amini41af4302016-11-11 04:28:40 +00002214 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002215 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002216 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2217 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002218 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2219 report_error(std::move(E), Filename, C);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002220 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002221 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002222 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2223 if (!checkMachOAndArchFlags(O, Filename))
2224 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002225 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002226 }
2227 }
Lang Hamesfc209622016-07-14 02:24:01 +00002228 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002229 report_error(std::move(Err), Filename);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002230 return;
2231 }
2232 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
George Rimar73a27232019-01-15 09:19:18 +00002233 parseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002234 return;
2235 }
2236 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2237 if (!checkMachOAndArchFlags(O, Filename))
2238 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002239 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002240 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002241 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002242 WithColor::error(errs(), "llvm-objdump")
2243 << Filename << "': "
2244 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002245 return;
2246 }
2247 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002248}
2249
George Rimar73a27232019-01-15 09:19:18 +00002250void llvm::parseInputMachO(MachOUniversalBinary *UB) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002251 if (!ValidateArchFlags())
2252 return;
2253
2254 auto Filename = UB->getFileName();
2255
2256 if (UniversalHeaders)
2257 printMachOUniversalHeaders(UB, !NonVerbose);
2258
2259 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002260 if (!ArchAll && !ArchFlags.empty()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002261 // Look for a slice in the universal binary that matches each ArchFlag.
2262 bool ArchFound;
2263 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2264 ArchFound = false;
2265 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2266 E = UB->end_objects();
2267 I != E; ++I) {
2268 if (ArchFlags[i] == I->getArchFlagName()) {
2269 ArchFound = true;
2270 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2271 I->getAsObjectFile();
2272 std::string ArchitectureName = "";
2273 if (ArchFlags.size() > 1)
2274 ArchitectureName = I->getArchFlagName();
2275 if (ObjOrErr) {
2276 ObjectFile &O = *ObjOrErr.get();
2277 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2278 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002279 } else if (Error E = isNotObjectErrorInvalidFileType(
2280 ObjOrErr.takeError())) {
2281 report_error(std::move(E), Filename, StringRef(), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002282 continue;
2283 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002284 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002285 std::unique_ptr<Archive> &A = *AOrErr;
2286 outs() << "Archive : " << Filename;
2287 if (!ArchitectureName.empty())
2288 outs() << " (architecture " << ArchitectureName << ")";
2289 outs() << "\n";
2290 if (ArchiveHeaders)
2291 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2292 ArchiveMemberOffsets, ArchitectureName);
2293 Error Err = Error::success();
2294 for (auto &C : A->children(Err)) {
2295 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2296 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002297 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2298 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002299 continue;
2300 }
2301 if (MachOObjectFile *O =
2302 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2303 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2304 }
2305 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002306 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002307 } else {
2308 consumeError(AOrErr.takeError());
2309 error("Mach-O universal file: " + Filename + " for " +
2310 "architecture " + StringRef(I->getArchFlagName()) +
2311 " is not a Mach-O file or an archive file");
2312 }
2313 }
2314 }
2315 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002316 WithColor::error(errs(), "llvm-objdump")
2317 << "file: " + Filename + " does not contain "
2318 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002319 return;
2320 }
2321 }
2322 return;
2323 }
2324 // No architecture flags were specified so if this contains a slice that
2325 // matches the host architecture dump only that.
2326 if (!ArchAll) {
2327 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2328 E = UB->end_objects();
2329 I != E; ++I) {
2330 if (MachOObjectFile::getHostArch().getArchName() ==
2331 I->getArchFlagName()) {
2332 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2333 std::string ArchiveName;
2334 ArchiveName.clear();
2335 if (ObjOrErr) {
2336 ObjectFile &O = *ObjOrErr.get();
2337 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2338 ProcessMachO(Filename, MachOOF);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002339 } else if (Error E =
2340 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2341 report_error(std::move(E), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002342 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002343 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002344 std::unique_ptr<Archive> &A = *AOrErr;
2345 outs() << "Archive : " << Filename << "\n";
2346 if (ArchiveHeaders)
2347 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2348 ArchiveMemberOffsets);
2349 Error Err = Error::success();
2350 for (auto &C : A->children(Err)) {
2351 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2352 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002353 if (Error E =
2354 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2355 report_error(std::move(E), Filename, C);
Dave Lee3fb120f2018-08-03 00:06:38 +00002356 continue;
2357 }
2358 if (MachOObjectFile *O =
2359 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2360 ProcessMachO(Filename, O, O->getFileName());
2361 }
2362 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002363 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002364 } else {
2365 consumeError(AOrErr.takeError());
2366 error("Mach-O universal file: " + Filename + " for architecture " +
2367 StringRef(I->getArchFlagName()) +
2368 " is not a Mach-O file or an archive file");
2369 }
2370 return;
2371 }
2372 }
2373 }
2374 // Either all architectures have been specified or none have been specified
2375 // and this does not contain the host architecture so dump all the slices.
2376 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2377 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2378 E = UB->end_objects();
2379 I != E; ++I) {
2380 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2381 std::string ArchitectureName = "";
2382 if (moreThanOneArch)
2383 ArchitectureName = I->getArchFlagName();
2384 if (ObjOrErr) {
2385 ObjectFile &Obj = *ObjOrErr.get();
2386 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2387 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002388 } else if (Error E =
2389 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2390 report_error(std::move(E), StringRef(), Filename, ArchitectureName);
2391 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002392 std::unique_ptr<Archive> &A = *AOrErr;
2393 outs() << "Archive : " << Filename;
2394 if (!ArchitectureName.empty())
2395 outs() << " (architecture " << ArchitectureName << ")";
2396 outs() << "\n";
2397 if (ArchiveHeaders)
2398 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2399 ArchiveMemberOffsets, ArchitectureName);
2400 Error Err = Error::success();
2401 for (auto &C : A->children(Err)) {
2402 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2403 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002404 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2405 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002406 continue;
2407 }
2408 if (MachOObjectFile *O =
2409 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2410 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2411 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2412 ArchitectureName);
2413 }
2414 }
2415 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002416 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002417 } else {
2418 consumeError(AOrErr.takeError());
2419 error("Mach-O universal file: " + Filename + " for architecture " +
2420 StringRef(I->getArchFlagName()) +
2421 " is not a Mach-O file or an archive file");
2422 }
2423 }
2424}
2425
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002426// The block of info used by the Symbolizer call backs.
2427struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002428 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2429 std::vector<SectionRef> *Sections, bool verbose)
2430 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002431 bool verbose;
2432 MachOObjectFile *O;
2433 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002434 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002435 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002436 const char *class_name = nullptr;
2437 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002438 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002439 char *demangled_name = nullptr;
2440 uint64_t adrp_addr = 0;
2441 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002442 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002443 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002444};
2445
2446// SymbolizerGetOpInfo() is the operand information call back function.
2447// This is called to get the symbolic information for operand(s) of an
2448// instruction when it is being done. This routine does this from
2449// the relocation information, symbol table, etc. That block of information
2450// is a pointer to the struct DisassembleInfo that was passed when the
2451// disassembler context was created and passed to back to here when
2452// called back by the disassembler for instruction operands that could have
2453// relocation information. The address of the instruction containing operand is
2454// at the Pc parameter. The immediate value the operand has is passed in
2455// op_info->Value and is at Offset past the start of the instruction and has a
2456// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2457// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2458// names and addends of the symbolic expression to add for the operand. The
2459// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2460// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002461static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2462 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002463 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2464 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002465 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002466
2467 // Make sure all fields returned are zero if we don't set them.
2468 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2469 op_info->Value = value;
2470
2471 // If the TagType is not the value 1 which it code knows about or if no
2472 // verbose symbolic information is wanted then just return 0, indicating no
2473 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002474 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002475 return 0;
2476
2477 unsigned int Arch = info->O->getArch();
2478 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002479 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2480 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002481 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2482 // TODO:
2483 // Search the external relocation entries of a fully linked image
2484 // (if any) for an entry that matches this segment offset.
2485 // uint32_t seg_offset = (Pc + Offset);
2486 return 0;
2487 }
2488 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2489 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002490 uint32_t sect_addr = info->S.getAddress();
2491 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2492 bool reloc_found = false;
2493 DataRefImpl Rel;
2494 MachO::any_relocation_info RE;
2495 bool isExtern = false;
2496 SymbolRef Symbol;
2497 bool r_scattered = false;
2498 uint32_t r_value, pair_r_value, r_type;
2499 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002500 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002501 if (RelocOffset == sect_offset) {
2502 Rel = Reloc.getRawDataRefImpl();
2503 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002504 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002505 r_scattered = info->O->isRelocationScattered(RE);
2506 if (r_scattered) {
2507 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002508 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2509 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2510 DataRefImpl RelNext = Rel;
2511 info->O->moveRelocationNext(RelNext);
2512 MachO::any_relocation_info RENext;
2513 RENext = info->O->getRelocation(RelNext);
2514 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002515 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002516 else
2517 return 0;
2518 }
2519 } else {
2520 isExtern = info->O->getPlainRelocationExternal(RE);
2521 if (isExtern) {
2522 symbol_iterator RelocSym = Reloc.getSymbol();
2523 Symbol = *RelocSym;
2524 }
2525 }
2526 reloc_found = true;
2527 break;
2528 }
2529 }
2530 if (reloc_found && isExtern) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002531 op_info->AddSymbol.Present = 1;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002532 op_info->AddSymbol.Name =
2533 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002534 // For i386 extern relocation entries the value in the instruction is
2535 // the offset from the symbol, and value is already set in op_info->Value.
2536 return 1;
2537 }
2538 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2539 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002540 const char *add = GuessSymbolName(r_value, info->AddrMap);
2541 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002542 uint32_t offset = value - (r_value - pair_r_value);
2543 op_info->AddSymbol.Present = 1;
2544 if (add != nullptr)
2545 op_info->AddSymbol.Name = add;
2546 else
2547 op_info->AddSymbol.Value = r_value;
2548 op_info->SubtractSymbol.Present = 1;
2549 if (sub != nullptr)
2550 op_info->SubtractSymbol.Name = sub;
2551 else
2552 op_info->SubtractSymbol.Value = pair_r_value;
2553 op_info->Value = offset;
2554 return 1;
2555 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002556 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002557 }
2558 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002559 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2560 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002561 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2562 // relocation entries of a linked image (if any) for an entry that matches
2563 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002564 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002565 uint64_t seg_offset = Pc + Offset;
2566 bool reloc_found = false;
2567 DataRefImpl Rel;
2568 MachO::any_relocation_info RE;
2569 bool isExtern = false;
2570 SymbolRef Symbol;
2571 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2572 uint64_t RelocOffset = Reloc.getOffset();
2573 if (RelocOffset == seg_offset) {
2574 Rel = Reloc.getRawDataRefImpl();
2575 RE = info->O->getRelocation(Rel);
2576 // external relocation entries should always be external.
2577 isExtern = info->O->getPlainRelocationExternal(RE);
2578 if (isExtern) {
2579 symbol_iterator RelocSym = Reloc.getSymbol();
2580 Symbol = *RelocSym;
2581 }
2582 reloc_found = true;
2583 break;
2584 }
2585 }
2586 if (reloc_found && isExtern) {
2587 // The Value passed in will be adjusted by the Pc if the instruction
2588 // adds the Pc. But for x86_64 external relocation entries the Value
2589 // is the offset from the external symbol.
2590 if (info->O->getAnyRelocationPCRel(RE))
2591 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002592 const char *name =
2593 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002594 op_info->AddSymbol.Present = 1;
2595 op_info->AddSymbol.Name = name;
2596 return 1;
2597 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002598 return 0;
2599 }
2600 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2601 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002602 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002603 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2604 bool reloc_found = false;
2605 DataRefImpl Rel;
2606 MachO::any_relocation_info RE;
2607 bool isExtern = false;
2608 SymbolRef Symbol;
2609 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002610 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002611 if (RelocOffset == sect_offset) {
2612 Rel = Reloc.getRawDataRefImpl();
2613 RE = info->O->getRelocation(Rel);
2614 // NOTE: Scattered relocations don't exist on x86_64.
2615 isExtern = info->O->getPlainRelocationExternal(RE);
2616 if (isExtern) {
2617 symbol_iterator RelocSym = Reloc.getSymbol();
2618 Symbol = *RelocSym;
2619 }
2620 reloc_found = true;
2621 break;
2622 }
2623 }
2624 if (reloc_found && isExtern) {
2625 // The Value passed in will be adjusted by the Pc if the instruction
2626 // adds the Pc. But for x86_64 external relocation entries the Value
2627 // is the offset from the external symbol.
2628 if (info->O->getAnyRelocationPCRel(RE))
2629 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002630 const char *name =
2631 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002632 unsigned Type = info->O->getAnyRelocationType(RE);
2633 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2634 DataRefImpl RelNext = Rel;
2635 info->O->moveRelocationNext(RelNext);
2636 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2637 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2638 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2639 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2640 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2641 op_info->SubtractSymbol.Present = 1;
2642 op_info->SubtractSymbol.Name = name;
2643 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2644 Symbol = *RelocSymNext;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002645 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002646 }
2647 }
2648 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2649 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2650 op_info->AddSymbol.Present = 1;
2651 op_info->AddSymbol.Name = name;
2652 return 1;
2653 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002654 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002655 }
2656 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002657 if (Offset != 0 || (Size != 4 && Size != 2))
2658 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002659 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2660 // TODO:
2661 // Search the external relocation entries of a fully linked image
2662 // (if any) for an entry that matches this segment offset.
2663 // uint32_t seg_offset = (Pc + Offset);
2664 return 0;
2665 }
2666 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2667 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002668 uint32_t sect_addr = info->S.getAddress();
2669 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002670 DataRefImpl Rel;
2671 MachO::any_relocation_info RE;
2672 bool isExtern = false;
2673 SymbolRef Symbol;
2674 bool r_scattered = false;
2675 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002676 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002677 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2678 uint64_t RelocOffset = Reloc.getOffset();
2679 return RelocOffset == sect_offset;
2680 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002681
2682 if (Reloc == info->S.relocations().end())
2683 return 0;
2684
2685 Rel = Reloc->getRawDataRefImpl();
2686 RE = info->O->getRelocation(Rel);
2687 r_length = info->O->getAnyRelocationLength(RE);
2688 r_scattered = info->O->isRelocationScattered(RE);
2689 if (r_scattered) {
2690 r_value = info->O->getScatteredRelocationValue(RE);
2691 r_type = info->O->getScatteredRelocationType(RE);
2692 } else {
2693 r_type = info->O->getAnyRelocationType(RE);
2694 isExtern = info->O->getPlainRelocationExternal(RE);
2695 if (isExtern) {
2696 symbol_iterator RelocSym = Reloc->getSymbol();
2697 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002698 }
2699 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002700 if (r_type == MachO::ARM_RELOC_HALF ||
2701 r_type == MachO::ARM_RELOC_SECTDIFF ||
2702 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2703 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2704 DataRefImpl RelNext = Rel;
2705 info->O->moveRelocationNext(RelNext);
2706 MachO::any_relocation_info RENext;
2707 RENext = info->O->getRelocation(RelNext);
2708 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2709 if (info->O->isRelocationScattered(RENext))
2710 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2711 }
2712
2713 if (isExtern) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002714 const char *name =
2715 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002716 op_info->AddSymbol.Present = 1;
2717 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002718 switch (r_type) {
2719 case MachO::ARM_RELOC_HALF:
2720 if ((r_length & 0x1) == 1) {
2721 op_info->Value = value << 16 | other_half;
2722 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2723 } else {
2724 op_info->Value = other_half << 16 | value;
2725 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002726 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002727 break;
2728 default:
2729 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002730 }
2731 return 1;
2732 }
2733 // If we have a branch that is not an external relocation entry then
2734 // return 0 so the code in tryAddingSymbolicOperand() can use the
2735 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002736 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002737 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2738 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002739 return 0;
2740
2741 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002742 if (r_type == MachO::ARM_RELOC_HALF ||
2743 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2744 if ((r_length & 0x1) == 1)
2745 value = value << 16 | other_half;
2746 else
2747 value = other_half << 16 | value;
2748 }
2749 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2750 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2751 offset = value - r_value;
2752 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002753 }
2754
David Blaikie33dd45d02015-03-23 18:39:02 +00002755 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002756 if ((r_length & 0x1) == 1)
2757 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2758 else
2759 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002760 const char *add = GuessSymbolName(r_value, info->AddrMap);
2761 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002762 int32_t offset = value - (r_value - pair_r_value);
2763 op_info->AddSymbol.Present = 1;
2764 if (add != nullptr)
2765 op_info->AddSymbol.Name = add;
2766 else
2767 op_info->AddSymbol.Value = r_value;
2768 op_info->SubtractSymbol.Present = 1;
2769 if (sub != nullptr)
2770 op_info->SubtractSymbol.Name = sub;
2771 else
2772 op_info->SubtractSymbol.Value = pair_r_value;
2773 op_info->Value = offset;
2774 return 1;
2775 }
2776
Kevin Enderby930fdc72014-11-06 19:00:13 +00002777 op_info->AddSymbol.Present = 1;
2778 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002779 if (r_type == MachO::ARM_RELOC_HALF) {
2780 if ((r_length & 0x1) == 1)
2781 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2782 else
2783 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002784 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002785 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002786 if (add != nullptr) {
2787 op_info->AddSymbol.Name = add;
2788 return 1;
2789 }
2790 op_info->AddSymbol.Value = value;
2791 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002792 }
2793 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002794 if (Offset != 0 || Size != 4)
2795 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002796 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2797 // TODO:
2798 // Search the external relocation entries of a fully linked image
2799 // (if any) for an entry that matches this segment offset.
2800 // uint64_t seg_offset = (Pc + Offset);
2801 return 0;
2802 }
2803 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2804 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002805 uint64_t sect_addr = info->S.getAddress();
2806 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002807 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002808 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2809 uint64_t RelocOffset = Reloc.getOffset();
2810 return RelocOffset == sect_offset;
2811 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002812
David Blaikie33dd45d02015-03-23 18:39:02 +00002813 if (Reloc == info->S.relocations().end())
2814 return 0;
2815
2816 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2817 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2818 uint32_t r_type = info->O->getAnyRelocationType(RE);
2819 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2820 DataRefImpl RelNext = Rel;
2821 info->O->moveRelocationNext(RelNext);
2822 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2823 if (value == 0) {
2824 value = info->O->getPlainRelocationSymbolNum(RENext);
2825 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002826 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002827 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002828 // NOTE: Scattered relocations don't exist on arm64.
2829 if (!info->O->getPlainRelocationExternal(RE))
2830 return 0;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002831 const char *name =
2832 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2833 .data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002834 op_info->AddSymbol.Present = 1;
2835 op_info->AddSymbol.Name = name;
2836
2837 switch (r_type) {
2838 case MachO::ARM64_RELOC_PAGE21:
2839 /* @page */
2840 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2841 break;
2842 case MachO::ARM64_RELOC_PAGEOFF12:
2843 /* @pageoff */
2844 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2845 break;
2846 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2847 /* @gotpage */
2848 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2849 break;
2850 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2851 /* @gotpageoff */
2852 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2853 break;
2854 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2855 /* @tvlppage is not implemented in llvm-mc */
2856 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2857 break;
2858 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2859 /* @tvlppageoff is not implemented in llvm-mc */
2860 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2861 break;
2862 default:
2863 case MachO::ARM64_RELOC_BRANCH26:
2864 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2865 break;
2866 }
2867 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002868 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002869 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002870}
2871
Kevin Enderbybf246f52014-09-24 23:08:22 +00002872// GuessCstringPointer is passed the address of what might be a pointer to a
2873// literal string in a cstring section. If that address is in a cstring section
2874// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002875static const char *GuessCstringPointer(uint64_t ReferenceValue,
2876 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002877 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002878 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2879 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2880 for (unsigned J = 0; J < Seg.nsects; ++J) {
2881 MachO::section_64 Sec = info->O->getSection64(Load, J);
2882 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2883 if (section_type == MachO::S_CSTRING_LITERALS &&
2884 ReferenceValue >= Sec.addr &&
2885 ReferenceValue < Sec.addr + Sec.size) {
2886 uint64_t sect_offset = ReferenceValue - Sec.addr;
2887 uint64_t object_offset = Sec.offset + sect_offset;
2888 StringRef MachOContents = info->O->getData();
2889 uint64_t object_size = MachOContents.size();
2890 const char *object_addr = (const char *)MachOContents.data();
2891 if (object_offset < object_size) {
2892 const char *name = object_addr + object_offset;
2893 return name;
2894 } else {
2895 return nullptr;
2896 }
2897 }
2898 }
2899 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2900 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2901 for (unsigned J = 0; J < Seg.nsects; ++J) {
2902 MachO::section Sec = info->O->getSection(Load, J);
2903 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2904 if (section_type == MachO::S_CSTRING_LITERALS &&
2905 ReferenceValue >= Sec.addr &&
2906 ReferenceValue < Sec.addr + Sec.size) {
2907 uint64_t sect_offset = ReferenceValue - Sec.addr;
2908 uint64_t object_offset = Sec.offset + sect_offset;
2909 StringRef MachOContents = info->O->getData();
2910 uint64_t object_size = MachOContents.size();
2911 const char *object_addr = (const char *)MachOContents.data();
2912 if (object_offset < object_size) {
2913 const char *name = object_addr + object_offset;
2914 return name;
2915 } else {
2916 return nullptr;
2917 }
2918 }
2919 }
2920 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002921 }
2922 return nullptr;
2923}
2924
Kevin Enderby85974882014-09-26 22:20:44 +00002925// GuessIndirectSymbol returns the name of the indirect symbol for the
2926// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2927// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2928// symbol name being referenced by the stub or pointer.
2929static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2930 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002931 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2932 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002933 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002934 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2935 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2936 for (unsigned J = 0; J < Seg.nsects; ++J) {
2937 MachO::section_64 Sec = info->O->getSection64(Load, J);
2938 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2939 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2940 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2941 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2942 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2943 section_type == MachO::S_SYMBOL_STUBS) &&
2944 ReferenceValue >= Sec.addr &&
2945 ReferenceValue < Sec.addr + Sec.size) {
2946 uint32_t stride;
2947 if (section_type == MachO::S_SYMBOL_STUBS)
2948 stride = Sec.reserved2;
2949 else
2950 stride = 8;
2951 if (stride == 0)
2952 return nullptr;
2953 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2954 if (index < Dysymtab.nindirectsyms) {
2955 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002956 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002957 if (indirect_symbol < Symtab.nsyms) {
2958 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002959 return unwrapOrError(Sym->getName(), info->O->getFileName())
2960 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00002961 }
2962 }
2963 }
2964 }
2965 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2966 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2967 for (unsigned J = 0; J < Seg.nsects; ++J) {
2968 MachO::section Sec = info->O->getSection(Load, J);
2969 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2970 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2971 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2972 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2973 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2974 section_type == MachO::S_SYMBOL_STUBS) &&
2975 ReferenceValue >= Sec.addr &&
2976 ReferenceValue < Sec.addr + Sec.size) {
2977 uint32_t stride;
2978 if (section_type == MachO::S_SYMBOL_STUBS)
2979 stride = Sec.reserved2;
2980 else
2981 stride = 4;
2982 if (stride == 0)
2983 return nullptr;
2984 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2985 if (index < Dysymtab.nindirectsyms) {
2986 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002987 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002988 if (indirect_symbol < Symtab.nsyms) {
2989 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002990 return unwrapOrError(Sym->getName(), info->O->getFileName())
2991 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00002992 }
2993 }
2994 }
2995 }
2996 }
Kevin Enderby85974882014-09-26 22:20:44 +00002997 }
2998 return nullptr;
2999}
3000
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003001// method_reference() is called passing it the ReferenceName that might be
3002// a reference it to an Objective-C method call. If so then it allocates and
3003// assembles a method call string with the values last seen and saved in
3004// the DisassembleInfo's class_name and selector_name fields. This is saved
3005// into the method field of the info and any previous string is free'ed.
3006// Then the class_name field in the info is set to nullptr. The method call
3007// string is set into ReferenceName and ReferenceType is set to
3008// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3009// then both ReferenceType and ReferenceName are left unchanged.
3010static void method_reference(struct DisassembleInfo *info,
3011 uint64_t *ReferenceType,
3012 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003013 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003014 if (*ReferenceName != nullptr) {
3015 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003016 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003017 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003018 info->method = llvm::make_unique<char[]>(
3019 5 + strlen(info->class_name) + strlen(info->selector_name));
3020 char *method = info->method.get();
3021 if (method != nullptr) {
3022 strcpy(method, "+[");
3023 strcat(method, info->class_name);
3024 strcat(method, " ");
3025 strcat(method, info->selector_name);
3026 strcat(method, "]");
3027 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003028 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3029 }
3030 } else {
David Blaikie0e550682018-02-20 18:48:51 +00003031 info->method =
3032 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
3033 char *method = info->method.get();
3034 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003035 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003036 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003037 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003038 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003039 else
David Blaikie0e550682018-02-20 18:48:51 +00003040 strcpy(method, "-[r? ");
3041 strcat(method, info->selector_name);
3042 strcat(method, "]");
3043 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003044 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3045 }
3046 }
3047 info->class_name = nullptr;
3048 }
3049 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003050 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003051 info->method =
3052 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
3053 char *method = info->method.get();
3054 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003055 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003056 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003057 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003058 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003059 else
David Blaikie0e550682018-02-20 18:48:51 +00003060 strcpy(method, "-[[r? super] ");
3061 strcat(method, info->selector_name);
3062 strcat(method, "]");
3063 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003064 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3065 }
3066 info->class_name = nullptr;
3067 }
3068 }
3069 }
3070}
3071
3072// GuessPointerPointer() is passed the address of what might be a pointer to
3073// a reference to an Objective-C class, selector, message ref or cfstring.
3074// If so the value of the pointer is returned and one of the booleans are set
3075// to true. If not zero is returned and all the booleans are set to false.
3076static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3077 struct DisassembleInfo *info,
3078 bool &classref, bool &selref, bool &msgref,
3079 bool &cfstring) {
3080 classref = false;
3081 selref = false;
3082 msgref = false;
3083 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003084 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003085 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3086 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3087 for (unsigned J = 0; J < Seg.nsects; ++J) {
3088 MachO::section_64 Sec = info->O->getSection64(Load, J);
3089 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3090 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3091 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3092 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3093 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3094 ReferenceValue >= Sec.addr &&
3095 ReferenceValue < Sec.addr + Sec.size) {
3096 uint64_t sect_offset = ReferenceValue - Sec.addr;
3097 uint64_t object_offset = Sec.offset + sect_offset;
3098 StringRef MachOContents = info->O->getData();
3099 uint64_t object_size = MachOContents.size();
3100 const char *object_addr = (const char *)MachOContents.data();
3101 if (object_offset < object_size) {
3102 uint64_t pointer_value;
3103 memcpy(&pointer_value, object_addr + object_offset,
3104 sizeof(uint64_t));
3105 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3106 sys::swapByteOrder(pointer_value);
3107 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3108 selref = true;
3109 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3110 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3111 classref = true;
3112 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3113 ReferenceValue + 8 < Sec.addr + Sec.size) {
3114 msgref = true;
3115 memcpy(&pointer_value, object_addr + object_offset + 8,
3116 sizeof(uint64_t));
3117 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3118 sys::swapByteOrder(pointer_value);
3119 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3120 cfstring = true;
3121 return pointer_value;
3122 } else {
3123 return 0;
3124 }
3125 }
3126 }
3127 }
3128 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003129 }
3130 return 0;
3131}
3132
3133// get_pointer_64 returns a pointer to the bytes in the object file at the
3134// Address from a section in the Mach-O file. And indirectly returns the
3135// offset into the section, number of bytes left in the section past the offset
3136// and which section is was being referenced. If the Address is not in a
3137// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003138static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3139 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003140 DisassembleInfo *info,
3141 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003142 offset = 0;
3143 left = 0;
3144 S = SectionRef();
3145 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3146 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3147 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00003148 if (SectSize == 0)
3149 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00003150 if (objc_only) {
3151 StringRef SectName;
3152 ((*(info->Sections))[SectIdx]).getName(SectName);
3153 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3154 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3155 if (SegName != "__OBJC" && SectName != "__cstring")
3156 continue;
3157 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003158 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3159 S = (*(info->Sections))[SectIdx];
3160 offset = Address - SectAddress;
3161 left = SectSize - offset;
3162 StringRef SectContents;
3163 ((*(info->Sections))[SectIdx]).getContents(SectContents);
3164 return SectContents.data() + offset;
3165 }
3166 }
3167 return nullptr;
3168}
3169
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003170static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3171 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003172 DisassembleInfo *info,
3173 bool objc_only = false) {
3174 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003175}
3176
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003177// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3178// the symbol indirectly through n_value. Based on the relocation information
3179// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00003180// If no relocation information is found and a non-zero ReferenceValue for the
3181// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00003182static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3183 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003184 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003185 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00003186 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003187 return nullptr;
3188
3189 // See if there is an external relocation entry at the sect_offset.
3190 bool reloc_found = false;
3191 DataRefImpl Rel;
3192 MachO::any_relocation_info RE;
3193 bool isExtern = false;
3194 SymbolRef Symbol;
3195 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00003196 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003197 if (RelocOffset == sect_offset) {
3198 Rel = Reloc.getRawDataRefImpl();
3199 RE = info->O->getRelocation(Rel);
3200 if (info->O->isRelocationScattered(RE))
3201 continue;
3202 isExtern = info->O->getPlainRelocationExternal(RE);
3203 if (isExtern) {
3204 symbol_iterator RelocSym = Reloc.getSymbol();
3205 Symbol = *RelocSym;
3206 }
3207 reloc_found = true;
3208 break;
3209 }
3210 }
3211 // If there is an external relocation entry for a symbol in this section
3212 // at this section_offset then use that symbol's value for the n_value
3213 // and return its name.
3214 const char *SymbolName = nullptr;
3215 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003216 n_value = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00003217 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003218 if (!Name.empty()) {
3219 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003220 return SymbolName;
3221 }
3222 }
3223
3224 // TODO: For fully linked images, look through the external relocation
3225 // entries off the dynamic symtab command. For these the r_offset is from the
3226 // start of the first writeable segment in the Mach-O file. So the offset
3227 // to this section from that segment is passed to this routine by the caller,
3228 // as the database_offset. Which is the difference of the section's starting
3229 // address and the first writable segment.
3230 //
3231 // NOTE: need add passing the database_offset to this routine.
3232
Kevin Enderby0fc11822015-04-01 20:57:01 +00003233 // We did not find an external relocation entry so look up the ReferenceValue
3234 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003235 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003236
3237 return SymbolName;
3238}
3239
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003240static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3241 DisassembleInfo *info,
3242 uint32_t ReferenceValue) {
3243 uint64_t n_value64;
3244 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3245}
3246
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003247// These are structs in the Objective-C meta data and read to produce the
3248// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003249// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3250// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003251
3252// The cfstring object in a 64-bit Mach-O file.
3253struct cfstring64_t {
3254 uint64_t isa; // class64_t * (64-bit pointer)
3255 uint64_t flags; // flag bits
3256 uint64_t characters; // char * (64-bit pointer)
3257 uint64_t length; // number of non-NULL characters in above
3258};
3259
3260// The class object in a 64-bit Mach-O file.
3261struct class64_t {
3262 uint64_t isa; // class64_t * (64-bit pointer)
3263 uint64_t superclass; // class64_t * (64-bit pointer)
3264 uint64_t cache; // Cache (64-bit pointer)
3265 uint64_t vtable; // IMP * (64-bit pointer)
3266 uint64_t data; // class_ro64_t * (64-bit pointer)
3267};
3268
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003269struct class32_t {
3270 uint32_t isa; /* class32_t * (32-bit pointer) */
3271 uint32_t superclass; /* class32_t * (32-bit pointer) */
3272 uint32_t cache; /* Cache (32-bit pointer) */
3273 uint32_t vtable; /* IMP * (32-bit pointer) */
3274 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3275};
3276
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003277struct class_ro64_t {
3278 uint32_t flags;
3279 uint32_t instanceStart;
3280 uint32_t instanceSize;
3281 uint32_t reserved;
3282 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3283 uint64_t name; // const char * (64-bit pointer)
3284 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3285 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3286 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3287 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3288 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3289};
3290
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003291struct class_ro32_t {
3292 uint32_t flags;
3293 uint32_t instanceStart;
3294 uint32_t instanceSize;
3295 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3296 uint32_t name; /* const char * (32-bit pointer) */
3297 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3298 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3299 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3300 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3301 uint32_t baseProperties; /* const struct objc_property_list *
3302 (32-bit pointer) */
3303};
3304
3305/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003306#define RO_META (1 << 0)
3307#define RO_ROOT (1 << 1)
3308#define RO_HAS_CXX_STRUCTORS (1 << 2)
3309
3310struct method_list64_t {
3311 uint32_t entsize;
3312 uint32_t count;
3313 /* struct method64_t first; These structures follow inline */
3314};
3315
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003316struct method_list32_t {
3317 uint32_t entsize;
3318 uint32_t count;
3319 /* struct method32_t first; These structures follow inline */
3320};
3321
Kevin Enderby0fc11822015-04-01 20:57:01 +00003322struct method64_t {
3323 uint64_t name; /* SEL (64-bit pointer) */
3324 uint64_t types; /* const char * (64-bit pointer) */
3325 uint64_t imp; /* IMP (64-bit pointer) */
3326};
3327
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003328struct method32_t {
3329 uint32_t name; /* SEL (32-bit pointer) */
3330 uint32_t types; /* const char * (32-bit pointer) */
3331 uint32_t imp; /* IMP (32-bit pointer) */
3332};
3333
Kevin Enderby0fc11822015-04-01 20:57:01 +00003334struct protocol_list64_t {
3335 uint64_t count; /* uintptr_t (a 64-bit value) */
3336 /* struct protocol64_t * list[0]; These pointers follow inline */
3337};
3338
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003339struct protocol_list32_t {
3340 uint32_t count; /* uintptr_t (a 32-bit value) */
3341 /* struct protocol32_t * list[0]; These pointers follow inline */
3342};
3343
Kevin Enderby0fc11822015-04-01 20:57:01 +00003344struct protocol64_t {
3345 uint64_t isa; /* id * (64-bit pointer) */
3346 uint64_t name; /* const char * (64-bit pointer) */
3347 uint64_t protocols; /* struct protocol_list64_t *
3348 (64-bit pointer) */
3349 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3350 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3351 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3352 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3353 uint64_t instanceProperties; /* struct objc_property_list *
3354 (64-bit pointer) */
3355};
3356
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003357struct protocol32_t {
3358 uint32_t isa; /* id * (32-bit pointer) */
3359 uint32_t name; /* const char * (32-bit pointer) */
3360 uint32_t protocols; /* struct protocol_list_t *
3361 (32-bit pointer) */
3362 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3363 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3364 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3365 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3366 uint32_t instanceProperties; /* struct objc_property_list *
3367 (32-bit pointer) */
3368};
3369
Kevin Enderby0fc11822015-04-01 20:57:01 +00003370struct ivar_list64_t {
3371 uint32_t entsize;
3372 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003373 /* struct ivar64_t first; These structures follow inline */
3374};
3375
3376struct ivar_list32_t {
3377 uint32_t entsize;
3378 uint32_t count;
3379 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003380};
3381
3382struct ivar64_t {
3383 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3384 uint64_t name; /* const char * (64-bit pointer) */
3385 uint64_t type; /* const char * (64-bit pointer) */
3386 uint32_t alignment;
3387 uint32_t size;
3388};
3389
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003390struct ivar32_t {
3391 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3392 uint32_t name; /* const char * (32-bit pointer) */
3393 uint32_t type; /* const char * (32-bit pointer) */
3394 uint32_t alignment;
3395 uint32_t size;
3396};
3397
Kevin Enderby0fc11822015-04-01 20:57:01 +00003398struct objc_property_list64 {
3399 uint32_t entsize;
3400 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003401 /* struct objc_property64 first; These structures follow inline */
3402};
3403
3404struct objc_property_list32 {
3405 uint32_t entsize;
3406 uint32_t count;
3407 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003408};
3409
3410struct objc_property64 {
3411 uint64_t name; /* const char * (64-bit pointer) */
3412 uint64_t attributes; /* const char * (64-bit pointer) */
3413};
3414
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003415struct objc_property32 {
3416 uint32_t name; /* const char * (32-bit pointer) */
3417 uint32_t attributes; /* const char * (32-bit pointer) */
3418};
3419
Kevin Enderby0fc11822015-04-01 20:57:01 +00003420struct category64_t {
3421 uint64_t name; /* const char * (64-bit pointer) */
3422 uint64_t cls; /* struct class_t * (64-bit pointer) */
3423 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3424 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3425 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3426 uint64_t instanceProperties; /* struct objc_property_list *
3427 (64-bit pointer) */
3428};
3429
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003430struct category32_t {
3431 uint32_t name; /* const char * (32-bit pointer) */
3432 uint32_t cls; /* struct class_t * (32-bit pointer) */
3433 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3434 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3435 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3436 uint32_t instanceProperties; /* struct objc_property_list *
3437 (32-bit pointer) */
3438};
3439
Kevin Enderby0fc11822015-04-01 20:57:01 +00003440struct objc_image_info64 {
3441 uint32_t version;
3442 uint32_t flags;
3443};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003444struct objc_image_info32 {
3445 uint32_t version;
3446 uint32_t flags;
3447};
Kevin Enderby846c0002015-04-16 17:19:59 +00003448struct imageInfo_t {
3449 uint32_t version;
3450 uint32_t flags;
3451};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003452/* masks for objc_image_info.flags */
3453#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3454#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003455#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3456#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003457
3458struct message_ref64 {
3459 uint64_t imp; /* IMP (64-bit pointer) */
3460 uint64_t sel; /* SEL (64-bit pointer) */
3461};
3462
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003463struct message_ref32 {
3464 uint32_t imp; /* IMP (32-bit pointer) */
3465 uint32_t sel; /* SEL (32-bit pointer) */
3466};
3467
Kevin Enderby846c0002015-04-16 17:19:59 +00003468// Objective-C 1 (32-bit only) meta data structs.
3469
3470struct objc_module_t {
3471 uint32_t version;
3472 uint32_t size;
3473 uint32_t name; /* char * (32-bit pointer) */
3474 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3475};
3476
3477struct objc_symtab_t {
3478 uint32_t sel_ref_cnt;
3479 uint32_t refs; /* SEL * (32-bit pointer) */
3480 uint16_t cls_def_cnt;
3481 uint16_t cat_def_cnt;
3482 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3483};
3484
3485struct objc_class_t {
3486 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3487 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3488 uint32_t name; /* const char * (32-bit pointer) */
3489 int32_t version;
3490 int32_t info;
3491 int32_t instance_size;
3492 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3493 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3494 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3495 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3496};
3497
3498#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3499// class is not a metaclass
3500#define CLS_CLASS 0x1
3501// class is a metaclass
3502#define CLS_META 0x2
3503
3504struct objc_category_t {
3505 uint32_t category_name; /* char * (32-bit pointer) */
3506 uint32_t class_name; /* char * (32-bit pointer) */
3507 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3508 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3509 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3510};
3511
3512struct objc_ivar_t {
3513 uint32_t ivar_name; /* char * (32-bit pointer) */
3514 uint32_t ivar_type; /* char * (32-bit pointer) */
3515 int32_t ivar_offset;
3516};
3517
3518struct objc_ivar_list_t {
3519 int32_t ivar_count;
3520 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3521};
3522
3523struct objc_method_list_t {
3524 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3525 int32_t method_count;
3526 // struct objc_method_t method_list[1]; /* variable length structure */
3527};
3528
3529struct objc_method_t {
3530 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3531 uint32_t method_types; /* char * (32-bit pointer) */
3532 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3533 (32-bit pointer) */
3534};
3535
3536struct objc_protocol_list_t {
3537 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3538 int32_t count;
3539 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3540 // (32-bit pointer) */
3541};
3542
3543struct objc_protocol_t {
3544 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3545 uint32_t protocol_name; /* char * (32-bit pointer) */
3546 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3547 uint32_t instance_methods; /* struct objc_method_description_list *
3548 (32-bit pointer) */
3549 uint32_t class_methods; /* struct objc_method_description_list *
3550 (32-bit pointer) */
3551};
3552
3553struct objc_method_description_list_t {
3554 int32_t count;
3555 // struct objc_method_description_t list[1];
3556};
3557
3558struct objc_method_description_t {
3559 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3560 uint32_t types; /* char * (32-bit pointer) */
3561};
3562
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003563inline void swapStruct(struct cfstring64_t &cfs) {
3564 sys::swapByteOrder(cfs.isa);
3565 sys::swapByteOrder(cfs.flags);
3566 sys::swapByteOrder(cfs.characters);
3567 sys::swapByteOrder(cfs.length);
3568}
3569
3570inline void swapStruct(struct class64_t &c) {
3571 sys::swapByteOrder(c.isa);
3572 sys::swapByteOrder(c.superclass);
3573 sys::swapByteOrder(c.cache);
3574 sys::swapByteOrder(c.vtable);
3575 sys::swapByteOrder(c.data);
3576}
3577
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003578inline void swapStruct(struct class32_t &c) {
3579 sys::swapByteOrder(c.isa);
3580 sys::swapByteOrder(c.superclass);
3581 sys::swapByteOrder(c.cache);
3582 sys::swapByteOrder(c.vtable);
3583 sys::swapByteOrder(c.data);
3584}
3585
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003586inline void swapStruct(struct class_ro64_t &cro) {
3587 sys::swapByteOrder(cro.flags);
3588 sys::swapByteOrder(cro.instanceStart);
3589 sys::swapByteOrder(cro.instanceSize);
3590 sys::swapByteOrder(cro.reserved);
3591 sys::swapByteOrder(cro.ivarLayout);
3592 sys::swapByteOrder(cro.name);
3593 sys::swapByteOrder(cro.baseMethods);
3594 sys::swapByteOrder(cro.baseProtocols);
3595 sys::swapByteOrder(cro.ivars);
3596 sys::swapByteOrder(cro.weakIvarLayout);
3597 sys::swapByteOrder(cro.baseProperties);
3598}
3599
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003600inline void swapStruct(struct class_ro32_t &cro) {
3601 sys::swapByteOrder(cro.flags);
3602 sys::swapByteOrder(cro.instanceStart);
3603 sys::swapByteOrder(cro.instanceSize);
3604 sys::swapByteOrder(cro.ivarLayout);
3605 sys::swapByteOrder(cro.name);
3606 sys::swapByteOrder(cro.baseMethods);
3607 sys::swapByteOrder(cro.baseProtocols);
3608 sys::swapByteOrder(cro.ivars);
3609 sys::swapByteOrder(cro.weakIvarLayout);
3610 sys::swapByteOrder(cro.baseProperties);
3611}
3612
Kevin Enderby0fc11822015-04-01 20:57:01 +00003613inline void swapStruct(struct method_list64_t &ml) {
3614 sys::swapByteOrder(ml.entsize);
3615 sys::swapByteOrder(ml.count);
3616}
3617
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003618inline void swapStruct(struct method_list32_t &ml) {
3619 sys::swapByteOrder(ml.entsize);
3620 sys::swapByteOrder(ml.count);
3621}
3622
Kevin Enderby0fc11822015-04-01 20:57:01 +00003623inline void swapStruct(struct method64_t &m) {
3624 sys::swapByteOrder(m.name);
3625 sys::swapByteOrder(m.types);
3626 sys::swapByteOrder(m.imp);
3627}
3628
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003629inline void swapStruct(struct method32_t &m) {
3630 sys::swapByteOrder(m.name);
3631 sys::swapByteOrder(m.types);
3632 sys::swapByteOrder(m.imp);
3633}
3634
Kevin Enderby0fc11822015-04-01 20:57:01 +00003635inline void swapStruct(struct protocol_list64_t &pl) {
3636 sys::swapByteOrder(pl.count);
3637}
3638
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003639inline void swapStruct(struct protocol_list32_t &pl) {
3640 sys::swapByteOrder(pl.count);
3641}
3642
Kevin Enderby0fc11822015-04-01 20:57:01 +00003643inline void swapStruct(struct protocol64_t &p) {
3644 sys::swapByteOrder(p.isa);
3645 sys::swapByteOrder(p.name);
3646 sys::swapByteOrder(p.protocols);
3647 sys::swapByteOrder(p.instanceMethods);
3648 sys::swapByteOrder(p.classMethods);
3649 sys::swapByteOrder(p.optionalInstanceMethods);
3650 sys::swapByteOrder(p.optionalClassMethods);
3651 sys::swapByteOrder(p.instanceProperties);
3652}
3653
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003654inline void swapStruct(struct protocol32_t &p) {
3655 sys::swapByteOrder(p.isa);
3656 sys::swapByteOrder(p.name);
3657 sys::swapByteOrder(p.protocols);
3658 sys::swapByteOrder(p.instanceMethods);
3659 sys::swapByteOrder(p.classMethods);
3660 sys::swapByteOrder(p.optionalInstanceMethods);
3661 sys::swapByteOrder(p.optionalClassMethods);
3662 sys::swapByteOrder(p.instanceProperties);
3663}
3664
Kevin Enderby0fc11822015-04-01 20:57:01 +00003665inline void swapStruct(struct ivar_list64_t &il) {
3666 sys::swapByteOrder(il.entsize);
3667 sys::swapByteOrder(il.count);
3668}
3669
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003670inline void swapStruct(struct ivar_list32_t &il) {
3671 sys::swapByteOrder(il.entsize);
3672 sys::swapByteOrder(il.count);
3673}
3674
Kevin Enderby0fc11822015-04-01 20:57:01 +00003675inline void swapStruct(struct ivar64_t &i) {
3676 sys::swapByteOrder(i.offset);
3677 sys::swapByteOrder(i.name);
3678 sys::swapByteOrder(i.type);
3679 sys::swapByteOrder(i.alignment);
3680 sys::swapByteOrder(i.size);
3681}
3682
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003683inline void swapStruct(struct ivar32_t &i) {
3684 sys::swapByteOrder(i.offset);
3685 sys::swapByteOrder(i.name);
3686 sys::swapByteOrder(i.type);
3687 sys::swapByteOrder(i.alignment);
3688 sys::swapByteOrder(i.size);
3689}
3690
Kevin Enderby0fc11822015-04-01 20:57:01 +00003691inline void swapStruct(struct objc_property_list64 &pl) {
3692 sys::swapByteOrder(pl.entsize);
3693 sys::swapByteOrder(pl.count);
3694}
3695
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003696inline void swapStruct(struct objc_property_list32 &pl) {
3697 sys::swapByteOrder(pl.entsize);
3698 sys::swapByteOrder(pl.count);
3699}
3700
Kevin Enderby0fc11822015-04-01 20:57:01 +00003701inline void swapStruct(struct objc_property64 &op) {
3702 sys::swapByteOrder(op.name);
3703 sys::swapByteOrder(op.attributes);
3704}
3705
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003706inline void swapStruct(struct objc_property32 &op) {
3707 sys::swapByteOrder(op.name);
3708 sys::swapByteOrder(op.attributes);
3709}
3710
Kevin Enderby0fc11822015-04-01 20:57:01 +00003711inline void swapStruct(struct category64_t &c) {
3712 sys::swapByteOrder(c.name);
3713 sys::swapByteOrder(c.cls);
3714 sys::swapByteOrder(c.instanceMethods);
3715 sys::swapByteOrder(c.classMethods);
3716 sys::swapByteOrder(c.protocols);
3717 sys::swapByteOrder(c.instanceProperties);
3718}
3719
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003720inline void swapStruct(struct category32_t &c) {
3721 sys::swapByteOrder(c.name);
3722 sys::swapByteOrder(c.cls);
3723 sys::swapByteOrder(c.instanceMethods);
3724 sys::swapByteOrder(c.classMethods);
3725 sys::swapByteOrder(c.protocols);
3726 sys::swapByteOrder(c.instanceProperties);
3727}
3728
Kevin Enderby0fc11822015-04-01 20:57:01 +00003729inline void swapStruct(struct objc_image_info64 &o) {
3730 sys::swapByteOrder(o.version);
3731 sys::swapByteOrder(o.flags);
3732}
3733
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003734inline void swapStruct(struct objc_image_info32 &o) {
3735 sys::swapByteOrder(o.version);
3736 sys::swapByteOrder(o.flags);
3737}
3738
Kevin Enderby846c0002015-04-16 17:19:59 +00003739inline void swapStruct(struct imageInfo_t &o) {
3740 sys::swapByteOrder(o.version);
3741 sys::swapByteOrder(o.flags);
3742}
3743
Kevin Enderby0fc11822015-04-01 20:57:01 +00003744inline void swapStruct(struct message_ref64 &mr) {
3745 sys::swapByteOrder(mr.imp);
3746 sys::swapByteOrder(mr.sel);
3747}
3748
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003749inline void swapStruct(struct message_ref32 &mr) {
3750 sys::swapByteOrder(mr.imp);
3751 sys::swapByteOrder(mr.sel);
3752}
3753
Kevin Enderby846c0002015-04-16 17:19:59 +00003754inline void swapStruct(struct objc_module_t &module) {
3755 sys::swapByteOrder(module.version);
3756 sys::swapByteOrder(module.size);
3757 sys::swapByteOrder(module.name);
3758 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003759}
Kevin Enderby846c0002015-04-16 17:19:59 +00003760
3761inline void swapStruct(struct objc_symtab_t &symtab) {
3762 sys::swapByteOrder(symtab.sel_ref_cnt);
3763 sys::swapByteOrder(symtab.refs);
3764 sys::swapByteOrder(symtab.cls_def_cnt);
3765 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003766}
Kevin Enderby846c0002015-04-16 17:19:59 +00003767
3768inline void swapStruct(struct objc_class_t &objc_class) {
3769 sys::swapByteOrder(objc_class.isa);
3770 sys::swapByteOrder(objc_class.super_class);
3771 sys::swapByteOrder(objc_class.name);
3772 sys::swapByteOrder(objc_class.version);
3773 sys::swapByteOrder(objc_class.info);
3774 sys::swapByteOrder(objc_class.instance_size);
3775 sys::swapByteOrder(objc_class.ivars);
3776 sys::swapByteOrder(objc_class.methodLists);
3777 sys::swapByteOrder(objc_class.cache);
3778 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003779}
Kevin Enderby846c0002015-04-16 17:19:59 +00003780
3781inline void swapStruct(struct objc_category_t &objc_category) {
3782 sys::swapByteOrder(objc_category.category_name);
3783 sys::swapByteOrder(objc_category.class_name);
3784 sys::swapByteOrder(objc_category.instance_methods);
3785 sys::swapByteOrder(objc_category.class_methods);
3786 sys::swapByteOrder(objc_category.protocols);
3787}
3788
3789inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3790 sys::swapByteOrder(objc_ivar_list.ivar_count);
3791}
3792
3793inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3794 sys::swapByteOrder(objc_ivar.ivar_name);
3795 sys::swapByteOrder(objc_ivar.ivar_type);
3796 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003797}
Kevin Enderby846c0002015-04-16 17:19:59 +00003798
3799inline void swapStruct(struct objc_method_list_t &method_list) {
3800 sys::swapByteOrder(method_list.obsolete);
3801 sys::swapByteOrder(method_list.method_count);
3802}
3803
3804inline void swapStruct(struct objc_method_t &method) {
3805 sys::swapByteOrder(method.method_name);
3806 sys::swapByteOrder(method.method_types);
3807 sys::swapByteOrder(method.method_imp);
3808}
3809
3810inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3811 sys::swapByteOrder(protocol_list.next);
3812 sys::swapByteOrder(protocol_list.count);
3813}
3814
3815inline void swapStruct(struct objc_protocol_t &protocol) {
3816 sys::swapByteOrder(protocol.isa);
3817 sys::swapByteOrder(protocol.protocol_name);
3818 sys::swapByteOrder(protocol.protocol_list);
3819 sys::swapByteOrder(protocol.instance_methods);
3820 sys::swapByteOrder(protocol.class_methods);
3821}
3822
3823inline void swapStruct(struct objc_method_description_list_t &mdl) {
3824 sys::swapByteOrder(mdl.count);
3825}
3826
3827inline void swapStruct(struct objc_method_description_t &md) {
3828 sys::swapByteOrder(md.name);
3829 sys::swapByteOrder(md.types);
3830}
3831
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003832static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3833 struct DisassembleInfo *info);
3834
3835// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3836// to an Objective-C class and returns the class name. It is also passed the
3837// address of the pointer, so when the pointer is zero as it can be in an .o
3838// file, that is used to look for an external relocation entry with a symbol
3839// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003840static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3841 uint64_t ReferenceValue,
3842 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003843 const char *r;
3844 uint32_t offset, left;
3845 SectionRef S;
3846
3847 // The pointer_value can be 0 in an object file and have a relocation
3848 // entry for the class symbol at the ReferenceValue (the address of the
3849 // pointer).
3850 if (pointer_value == 0) {
3851 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3852 if (r == nullptr || left < sizeof(uint64_t))
3853 return nullptr;
3854 uint64_t n_value;
3855 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3856 if (symbol_name == nullptr)
3857 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003858 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003859 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3860 return class_name + 2;
3861 else
3862 return nullptr;
3863 }
3864
3865 // The case were the pointer_value is non-zero and points to a class defined
3866 // in this Mach-O file.
3867 r = get_pointer_64(pointer_value, offset, left, S, info);
3868 if (r == nullptr || left < sizeof(struct class64_t))
3869 return nullptr;
3870 struct class64_t c;
3871 memcpy(&c, r, sizeof(struct class64_t));
3872 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3873 swapStruct(c);
3874 if (c.data == 0)
3875 return nullptr;
3876 r = get_pointer_64(c.data, offset, left, S, info);
3877 if (r == nullptr || left < sizeof(struct class_ro64_t))
3878 return nullptr;
3879 struct class_ro64_t cro;
3880 memcpy(&cro, r, sizeof(struct class_ro64_t));
3881 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3882 swapStruct(cro);
3883 if (cro.name == 0)
3884 return nullptr;
3885 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3886 return name;
3887}
3888
3889// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3890// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003891static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3892 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003893 const char *r, *name;
3894 uint32_t offset, left;
3895 SectionRef S;
3896 struct cfstring64_t cfs;
3897 uint64_t cfs_characters;
3898
3899 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3900 if (r == nullptr || left < sizeof(struct cfstring64_t))
3901 return nullptr;
3902 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3903 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3904 swapStruct(cfs);
3905 if (cfs.characters == 0) {
3906 uint64_t n_value;
3907 const char *symbol_name = get_symbol_64(
3908 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3909 if (symbol_name == nullptr)
3910 return nullptr;
3911 cfs_characters = n_value;
3912 } else
3913 cfs_characters = cfs.characters;
3914 name = get_pointer_64(cfs_characters, offset, left, S, info);
3915
3916 return name;
3917}
3918
3919// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3920// of a pointer to an Objective-C selector reference when the pointer value is
3921// zero as in a .o file and is likely to have a external relocation entry with
3922// who's symbol's n_value is the real pointer to the selector name. If that is
3923// the case the real pointer to the selector name is returned else 0 is
3924// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003925static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3926 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003927 uint32_t offset, left;
3928 SectionRef S;
3929
3930 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3931 if (r == nullptr || left < sizeof(uint64_t))
3932 return 0;
3933 uint64_t n_value;
3934 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3935 if (symbol_name == nullptr)
3936 return 0;
3937 return n_value;
3938}
3939
Kevin Enderby0fc11822015-04-01 20:57:01 +00003940static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3941 const char *sectname) {
3942 for (const SectionRef &Section : O->sections()) {
3943 StringRef SectName;
3944 Section.getName(SectName);
3945 DataRefImpl Ref = Section.getRawDataRefImpl();
3946 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3947 if (SegName == segname && SectName == sectname)
3948 return Section;
3949 }
3950 return SectionRef();
3951}
3952
3953static void
3954walk_pointer_list_64(const char *listname, const SectionRef S,
3955 MachOObjectFile *O, struct DisassembleInfo *info,
3956 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3957 if (S == SectionRef())
3958 return;
3959
3960 StringRef SectName;
3961 S.getName(SectName);
3962 DataRefImpl Ref = S.getRawDataRefImpl();
3963 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3964 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3965
3966 StringRef BytesStr;
3967 S.getContents(BytesStr);
3968 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3969
3970 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3971 uint32_t left = S.getSize() - i;
3972 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3973 uint64_t p = 0;
3974 memcpy(&p, Contents + i, size);
3975 if (i + sizeof(uint64_t) > S.getSize())
3976 outs() << listname << " list pointer extends past end of (" << SegName
3977 << "," << SectName << ") section\n";
3978 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3979
3980 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3981 sys::swapByteOrder(p);
3982
3983 uint64_t n_value = 0;
3984 const char *name = get_symbol_64(i, S, info, n_value, p);
3985 if (name == nullptr)
3986 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3987
3988 if (n_value != 0) {
3989 outs() << format("0x%" PRIx64, n_value);
3990 if (p != 0)
3991 outs() << " + " << format("0x%" PRIx64, p);
3992 } else
3993 outs() << format("0x%" PRIx64, p);
3994 if (name != nullptr)
3995 outs() << " " << name;
3996 outs() << "\n";
3997
3998 p += n_value;
3999 if (func)
4000 func(p, info);
4001 }
4002}
4003
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004004static void
4005walk_pointer_list_32(const char *listname, const SectionRef S,
4006 MachOObjectFile *O, struct DisassembleInfo *info,
4007 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4008 if (S == SectionRef())
4009 return;
4010
4011 StringRef SectName;
4012 S.getName(SectName);
4013 DataRefImpl Ref = S.getRawDataRefImpl();
4014 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4015 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4016
4017 StringRef BytesStr;
4018 S.getContents(BytesStr);
4019 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4020
4021 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4022 uint32_t left = S.getSize() - i;
4023 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4024 uint32_t p = 0;
4025 memcpy(&p, Contents + i, size);
4026 if (i + sizeof(uint32_t) > S.getSize())
4027 outs() << listname << " list pointer extends past end of (" << SegName
4028 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00004029 uint32_t Address = S.getAddress() + i;
4030 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004031
4032 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4033 sys::swapByteOrder(p);
4034 outs() << format("0x%" PRIx32, p);
4035
4036 const char *name = get_symbol_32(i, S, info, p);
4037 if (name != nullptr)
4038 outs() << " " << name;
4039 outs() << "\n";
4040
4041 if (func)
4042 func(p, info);
4043 }
4044}
4045
4046static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004047 if (layout_map == nullptr)
4048 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004049 outs() << " layout map: ";
4050 do {
4051 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4052 left--;
4053 layout_map++;
4054 } while (*layout_map != '\0' && left != 0);
4055 outs() << "\n";
4056}
4057
Kevin Enderby0fc11822015-04-01 20:57:01 +00004058static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4059 uint32_t offset, left;
4060 SectionRef S;
4061 const char *layout_map;
4062
4063 if (p == 0)
4064 return;
4065 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004066 print_layout_map(layout_map, left);
4067}
4068
4069static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4070 uint32_t offset, left;
4071 SectionRef S;
4072 const char *layout_map;
4073
4074 if (p == 0)
4075 return;
4076 layout_map = get_pointer_32(p, offset, left, S, info);
4077 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004078}
4079
4080static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4081 const char *indent) {
4082 struct method_list64_t ml;
4083 struct method64_t m;
4084 const char *r;
4085 uint32_t offset, xoffset, left, i;
4086 SectionRef S, xS;
4087 const char *name, *sym_name;
4088 uint64_t n_value;
4089
4090 r = get_pointer_64(p, offset, left, S, info);
4091 if (r == nullptr)
4092 return;
4093 memset(&ml, '\0', sizeof(struct method_list64_t));
4094 if (left < sizeof(struct method_list64_t)) {
4095 memcpy(&ml, r, left);
4096 outs() << " (method_list_t entends past the end of the section)\n";
4097 } else
4098 memcpy(&ml, r, sizeof(struct method_list64_t));
4099 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4100 swapStruct(ml);
4101 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4102 outs() << indent << "\t\t count " << ml.count << "\n";
4103
4104 p += sizeof(struct method_list64_t);
4105 offset += sizeof(struct method_list64_t);
4106 for (i = 0; i < ml.count; i++) {
4107 r = get_pointer_64(p, offset, left, S, info);
4108 if (r == nullptr)
4109 return;
4110 memset(&m, '\0', sizeof(struct method64_t));
4111 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004112 memcpy(&m, r, left);
4113 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00004114 } else
4115 memcpy(&m, r, sizeof(struct method64_t));
4116 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4117 swapStruct(m);
4118
4119 outs() << indent << "\t\t name ";
4120 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4121 info, n_value, m.name);
4122 if (n_value != 0) {
4123 if (info->verbose && sym_name != nullptr)
4124 outs() << sym_name;
4125 else
4126 outs() << format("0x%" PRIx64, n_value);
4127 if (m.name != 0)
4128 outs() << " + " << format("0x%" PRIx64, m.name);
4129 } else
4130 outs() << format("0x%" PRIx64, m.name);
4131 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4132 if (name != nullptr)
4133 outs() << format(" %.*s", left, name);
4134 outs() << "\n";
4135
4136 outs() << indent << "\t\t types ";
4137 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4138 info, n_value, m.types);
4139 if (n_value != 0) {
4140 if (info->verbose && sym_name != nullptr)
4141 outs() << sym_name;
4142 else
4143 outs() << format("0x%" PRIx64, n_value);
4144 if (m.types != 0)
4145 outs() << " + " << format("0x%" PRIx64, m.types);
4146 } else
4147 outs() << format("0x%" PRIx64, m.types);
4148 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4149 if (name != nullptr)
4150 outs() << format(" %.*s", left, name);
4151 outs() << "\n";
4152
4153 outs() << indent << "\t\t imp ";
4154 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4155 n_value, m.imp);
4156 if (info->verbose && name == nullptr) {
4157 if (n_value != 0) {
4158 outs() << format("0x%" PRIx64, n_value) << " ";
4159 if (m.imp != 0)
4160 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4161 } else
4162 outs() << format("0x%" PRIx64, m.imp) << " ";
4163 }
4164 if (name != nullptr)
4165 outs() << name;
4166 outs() << "\n";
4167
4168 p += sizeof(struct method64_t);
4169 offset += sizeof(struct method64_t);
4170 }
4171}
4172
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004173static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4174 const char *indent) {
4175 struct method_list32_t ml;
4176 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00004177 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004178 uint32_t offset, xoffset, left, i;
4179 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004180
4181 r = get_pointer_32(p, offset, left, S, info);
4182 if (r == nullptr)
4183 return;
4184 memset(&ml, '\0', sizeof(struct method_list32_t));
4185 if (left < sizeof(struct method_list32_t)) {
4186 memcpy(&ml, r, left);
4187 outs() << " (method_list_t entends past the end of the section)\n";
4188 } else
4189 memcpy(&ml, r, sizeof(struct method_list32_t));
4190 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4191 swapStruct(ml);
4192 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4193 outs() << indent << "\t\t count " << ml.count << "\n";
4194
4195 p += sizeof(struct method_list32_t);
4196 offset += sizeof(struct method_list32_t);
4197 for (i = 0; i < ml.count; i++) {
4198 r = get_pointer_32(p, offset, left, S, info);
4199 if (r == nullptr)
4200 return;
4201 memset(&m, '\0', sizeof(struct method32_t));
4202 if (left < sizeof(struct method32_t)) {
4203 memcpy(&ml, r, left);
4204 outs() << indent << " (method_t entends past the end of the section)\n";
4205 } else
4206 memcpy(&m, r, sizeof(struct method32_t));
4207 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4208 swapStruct(m);
4209
4210 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4211 name = get_pointer_32(m.name, xoffset, left, xS, info);
4212 if (name != nullptr)
4213 outs() << format(" %.*s", left, name);
4214 outs() << "\n";
4215
4216 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4217 name = get_pointer_32(m.types, xoffset, left, xS, info);
4218 if (name != nullptr)
4219 outs() << format(" %.*s", left, name);
4220 outs() << "\n";
4221
4222 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4223 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4224 m.imp);
4225 if (name != nullptr)
4226 outs() << " " << name;
4227 outs() << "\n";
4228
4229 p += sizeof(struct method32_t);
4230 offset += sizeof(struct method32_t);
4231 }
4232}
4233
Kevin Enderby846c0002015-04-16 17:19:59 +00004234static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4235 uint32_t offset, left, xleft;
4236 SectionRef S;
4237 struct objc_method_list_t method_list;
4238 struct objc_method_t method;
4239 const char *r, *methods, *name, *SymbolName;
4240 int32_t i;
4241
4242 r = get_pointer_32(p, offset, left, S, info, true);
4243 if (r == nullptr)
4244 return true;
4245
4246 outs() << "\n";
4247 if (left > sizeof(struct objc_method_list_t)) {
4248 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4249 } else {
4250 outs() << "\t\t objc_method_list extends past end of the section\n";
4251 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4252 memcpy(&method_list, r, left);
4253 }
4254 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4255 swapStruct(method_list);
4256
4257 outs() << "\t\t obsolete "
4258 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4259 outs() << "\t\t method_count " << method_list.method_count << "\n";
4260
4261 methods = r + sizeof(struct objc_method_list_t);
4262 for (i = 0; i < method_list.method_count; i++) {
4263 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4264 outs() << "\t\t remaining method's extend past the of the section\n";
4265 break;
4266 }
4267 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4268 sizeof(struct objc_method_t));
4269 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4270 swapStruct(method);
4271
4272 outs() << "\t\t method_name "
4273 << format("0x%08" PRIx32, method.method_name);
4274 if (info->verbose) {
4275 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4276 if (name != nullptr)
4277 outs() << format(" %.*s", xleft, name);
4278 else
4279 outs() << " (not in an __OBJC section)";
4280 }
4281 outs() << "\n";
4282
4283 outs() << "\t\t method_types "
4284 << format("0x%08" PRIx32, method.method_types);
4285 if (info->verbose) {
4286 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4287 if (name != nullptr)
4288 outs() << format(" %.*s", xleft, name);
4289 else
4290 outs() << " (not in an __OBJC section)";
4291 }
4292 outs() << "\n";
4293
4294 outs() << "\t\t method_imp "
4295 << format("0x%08" PRIx32, method.method_imp) << " ";
4296 if (info->verbose) {
4297 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4298 if (SymbolName != nullptr)
4299 outs() << SymbolName;
4300 }
4301 outs() << "\n";
4302 }
4303 return false;
4304}
4305
Kevin Enderby0fc11822015-04-01 20:57:01 +00004306static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4307 struct protocol_list64_t pl;
4308 uint64_t q, n_value;
4309 struct protocol64_t pc;
4310 const char *r;
4311 uint32_t offset, xoffset, left, i;
4312 SectionRef S, xS;
4313 const char *name, *sym_name;
4314
4315 r = get_pointer_64(p, offset, left, S, info);
4316 if (r == nullptr)
4317 return;
4318 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4319 if (left < sizeof(struct protocol_list64_t)) {
4320 memcpy(&pl, r, left);
4321 outs() << " (protocol_list_t entends past the end of the section)\n";
4322 } else
4323 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4324 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4325 swapStruct(pl);
4326 outs() << " count " << pl.count << "\n";
4327
4328 p += sizeof(struct protocol_list64_t);
4329 offset += sizeof(struct protocol_list64_t);
4330 for (i = 0; i < pl.count; i++) {
4331 r = get_pointer_64(p, offset, left, S, info);
4332 if (r == nullptr)
4333 return;
4334 q = 0;
4335 if (left < sizeof(uint64_t)) {
4336 memcpy(&q, r, left);
4337 outs() << " (protocol_t * entends past the end of the section)\n";
4338 } else
4339 memcpy(&q, r, sizeof(uint64_t));
4340 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4341 sys::swapByteOrder(q);
4342
4343 outs() << "\t\t list[" << i << "] ";
4344 sym_name = get_symbol_64(offset, S, info, n_value, q);
4345 if (n_value != 0) {
4346 if (info->verbose && sym_name != nullptr)
4347 outs() << sym_name;
4348 else
4349 outs() << format("0x%" PRIx64, n_value);
4350 if (q != 0)
4351 outs() << " + " << format("0x%" PRIx64, q);
4352 } else
4353 outs() << format("0x%" PRIx64, q);
4354 outs() << " (struct protocol_t *)\n";
4355
4356 r = get_pointer_64(q + n_value, offset, left, S, info);
4357 if (r == nullptr)
4358 return;
4359 memset(&pc, '\0', sizeof(struct protocol64_t));
4360 if (left < sizeof(struct protocol64_t)) {
4361 memcpy(&pc, r, left);
4362 outs() << " (protocol_t entends past the end of the section)\n";
4363 } else
4364 memcpy(&pc, r, sizeof(struct protocol64_t));
4365 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4366 swapStruct(pc);
4367
4368 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4369
4370 outs() << "\t\t\t name ";
4371 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4372 info, n_value, pc.name);
4373 if (n_value != 0) {
4374 if (info->verbose && sym_name != nullptr)
4375 outs() << sym_name;
4376 else
4377 outs() << format("0x%" PRIx64, n_value);
4378 if (pc.name != 0)
4379 outs() << " + " << format("0x%" PRIx64, pc.name);
4380 } else
4381 outs() << format("0x%" PRIx64, pc.name);
4382 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4383 if (name != nullptr)
4384 outs() << format(" %.*s", left, name);
4385 outs() << "\n";
4386
4387 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4388
4389 outs() << "\t\t instanceMethods ";
4390 sym_name =
4391 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4392 S, info, n_value, pc.instanceMethods);
4393 if (n_value != 0) {
4394 if (info->verbose && sym_name != nullptr)
4395 outs() << sym_name;
4396 else
4397 outs() << format("0x%" PRIx64, n_value);
4398 if (pc.instanceMethods != 0)
4399 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4400 } else
4401 outs() << format("0x%" PRIx64, pc.instanceMethods);
4402 outs() << " (struct method_list_t *)\n";
4403 if (pc.instanceMethods + n_value != 0)
4404 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4405
4406 outs() << "\t\t classMethods ";
4407 sym_name =
4408 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4409 info, n_value, pc.classMethods);
4410 if (n_value != 0) {
4411 if (info->verbose && sym_name != nullptr)
4412 outs() << sym_name;
4413 else
4414 outs() << format("0x%" PRIx64, n_value);
4415 if (pc.classMethods != 0)
4416 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4417 } else
4418 outs() << format("0x%" PRIx64, pc.classMethods);
4419 outs() << " (struct method_list_t *)\n";
4420 if (pc.classMethods + n_value != 0)
4421 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4422
4423 outs() << "\t optionalInstanceMethods "
4424 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4425 outs() << "\t optionalClassMethods "
4426 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4427 outs() << "\t instanceProperties "
4428 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4429
4430 p += sizeof(uint64_t);
4431 offset += sizeof(uint64_t);
4432 }
4433}
4434
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004435static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4436 struct protocol_list32_t pl;
4437 uint32_t q;
4438 struct protocol32_t pc;
4439 const char *r;
4440 uint32_t offset, xoffset, left, i;
4441 SectionRef S, xS;
4442 const char *name;
4443
4444 r = get_pointer_32(p, offset, left, S, info);
4445 if (r == nullptr)
4446 return;
4447 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4448 if (left < sizeof(struct protocol_list32_t)) {
4449 memcpy(&pl, r, left);
4450 outs() << " (protocol_list_t entends past the end of the section)\n";
4451 } else
4452 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4453 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4454 swapStruct(pl);
4455 outs() << " count " << pl.count << "\n";
4456
4457 p += sizeof(struct protocol_list32_t);
4458 offset += sizeof(struct protocol_list32_t);
4459 for (i = 0; i < pl.count; i++) {
4460 r = get_pointer_32(p, offset, left, S, info);
4461 if (r == nullptr)
4462 return;
4463 q = 0;
4464 if (left < sizeof(uint32_t)) {
4465 memcpy(&q, r, left);
4466 outs() << " (protocol_t * entends past the end of the section)\n";
4467 } else
4468 memcpy(&q, r, sizeof(uint32_t));
4469 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4470 sys::swapByteOrder(q);
4471 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4472 << " (struct protocol_t *)\n";
4473 r = get_pointer_32(q, offset, left, S, info);
4474 if (r == nullptr)
4475 return;
4476 memset(&pc, '\0', sizeof(struct protocol32_t));
4477 if (left < sizeof(struct protocol32_t)) {
4478 memcpy(&pc, r, left);
4479 outs() << " (protocol_t entends past the end of the section)\n";
4480 } else
4481 memcpy(&pc, r, sizeof(struct protocol32_t));
4482 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4483 swapStruct(pc);
4484 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4485 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4486 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4487 if (name != nullptr)
4488 outs() << format(" %.*s", left, name);
4489 outs() << "\n";
4490 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4491 outs() << "\t\t instanceMethods "
4492 << format("0x%" PRIx32, pc.instanceMethods)
4493 << " (struct method_list_t *)\n";
4494 if (pc.instanceMethods != 0)
4495 print_method_list32_t(pc.instanceMethods, info, "\t");
4496 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4497 << " (struct method_list_t *)\n";
4498 if (pc.classMethods != 0)
4499 print_method_list32_t(pc.classMethods, info, "\t");
4500 outs() << "\t optionalInstanceMethods "
4501 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4502 outs() << "\t optionalClassMethods "
4503 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4504 outs() << "\t instanceProperties "
4505 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4506 p += sizeof(uint32_t);
4507 offset += sizeof(uint32_t);
4508 }
4509}
4510
Kevin Enderby846c0002015-04-16 17:19:59 +00004511static void print_indent(uint32_t indent) {
4512 for (uint32_t i = 0; i < indent;) {
4513 if (indent - i >= 8) {
4514 outs() << "\t";
4515 i += 8;
4516 } else {
4517 for (uint32_t j = i; j < indent; j++)
4518 outs() << " ";
4519 return;
4520 }
4521 }
4522}
4523
4524static bool print_method_description_list(uint32_t p, uint32_t indent,
4525 struct DisassembleInfo *info) {
4526 uint32_t offset, left, xleft;
4527 SectionRef S;
4528 struct objc_method_description_list_t mdl;
4529 struct objc_method_description_t md;
4530 const char *r, *list, *name;
4531 int32_t i;
4532
4533 r = get_pointer_32(p, offset, left, S, info, true);
4534 if (r == nullptr)
4535 return true;
4536
4537 outs() << "\n";
4538 if (left > sizeof(struct objc_method_description_list_t)) {
4539 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4540 } else {
4541 print_indent(indent);
4542 outs() << " objc_method_description_list extends past end of the section\n";
4543 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4544 memcpy(&mdl, r, left);
4545 }
4546 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4547 swapStruct(mdl);
4548
4549 print_indent(indent);
4550 outs() << " count " << mdl.count << "\n";
4551
4552 list = r + sizeof(struct objc_method_description_list_t);
4553 for (i = 0; i < mdl.count; i++) {
4554 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4555 print_indent(indent);
4556 outs() << " remaining list entries extend past the of the section\n";
4557 break;
4558 }
4559 print_indent(indent);
4560 outs() << " list[" << i << "]\n";
4561 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4562 sizeof(struct objc_method_description_t));
4563 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4564 swapStruct(md);
4565
4566 print_indent(indent);
4567 outs() << " name " << format("0x%08" PRIx32, md.name);
4568 if (info->verbose) {
4569 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4570 if (name != nullptr)
4571 outs() << format(" %.*s", xleft, name);
4572 else
4573 outs() << " (not in an __OBJC section)";
4574 }
4575 outs() << "\n";
4576
4577 print_indent(indent);
4578 outs() << " types " << format("0x%08" PRIx32, md.types);
4579 if (info->verbose) {
4580 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4581 if (name != nullptr)
4582 outs() << format(" %.*s", xleft, name);
4583 else
4584 outs() << " (not in an __OBJC section)";
4585 }
4586 outs() << "\n";
4587 }
4588 return false;
4589}
4590
4591static bool print_protocol_list(uint32_t p, uint32_t indent,
4592 struct DisassembleInfo *info);
4593
4594static bool print_protocol(uint32_t p, uint32_t indent,
4595 struct DisassembleInfo *info) {
4596 uint32_t offset, left;
4597 SectionRef S;
4598 struct objc_protocol_t protocol;
4599 const char *r, *name;
4600
4601 r = get_pointer_32(p, offset, left, S, info, true);
4602 if (r == nullptr)
4603 return true;
4604
4605 outs() << "\n";
4606 if (left >= sizeof(struct objc_protocol_t)) {
4607 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4608 } else {
4609 print_indent(indent);
4610 outs() << " Protocol extends past end of the section\n";
4611 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4612 memcpy(&protocol, r, left);
4613 }
4614 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4615 swapStruct(protocol);
4616
4617 print_indent(indent);
4618 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4619 << "\n";
4620
4621 print_indent(indent);
4622 outs() << " protocol_name "
4623 << format("0x%08" PRIx32, protocol.protocol_name);
4624 if (info->verbose) {
4625 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4626 if (name != nullptr)
4627 outs() << format(" %.*s", left, name);
4628 else
4629 outs() << " (not in an __OBJC section)";
4630 }
4631 outs() << "\n";
4632
4633 print_indent(indent);
4634 outs() << " protocol_list "
4635 << format("0x%08" PRIx32, protocol.protocol_list);
4636 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4637 outs() << " (not in an __OBJC section)\n";
4638
4639 print_indent(indent);
4640 outs() << " instance_methods "
4641 << format("0x%08" PRIx32, protocol.instance_methods);
4642 if (print_method_description_list(protocol.instance_methods, indent, info))
4643 outs() << " (not in an __OBJC section)\n";
4644
4645 print_indent(indent);
4646 outs() << " class_methods "
4647 << format("0x%08" PRIx32, protocol.class_methods);
4648 if (print_method_description_list(protocol.class_methods, indent, info))
4649 outs() << " (not in an __OBJC section)\n";
4650
4651 return false;
4652}
4653
4654static bool print_protocol_list(uint32_t p, uint32_t indent,
4655 struct DisassembleInfo *info) {
4656 uint32_t offset, left, l;
4657 SectionRef S;
4658 struct objc_protocol_list_t protocol_list;
4659 const char *r, *list;
4660 int32_t i;
4661
4662 r = get_pointer_32(p, offset, left, S, info, true);
4663 if (r == nullptr)
4664 return true;
4665
4666 outs() << "\n";
4667 if (left > sizeof(struct objc_protocol_list_t)) {
4668 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4669 } else {
4670 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4671 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4672 memcpy(&protocol_list, r, left);
4673 }
4674 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4675 swapStruct(protocol_list);
4676
4677 print_indent(indent);
4678 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4679 << "\n";
4680 print_indent(indent);
4681 outs() << " count " << protocol_list.count << "\n";
4682
4683 list = r + sizeof(struct objc_protocol_list_t);
4684 for (i = 0; i < protocol_list.count; i++) {
4685 if ((i + 1) * sizeof(uint32_t) > left) {
4686 outs() << "\t\t remaining list entries extend past the of the section\n";
4687 break;
4688 }
4689 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4690 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4691 sys::swapByteOrder(l);
4692
4693 print_indent(indent);
4694 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4695 if (print_protocol(l, indent, info))
4696 outs() << "(not in an __OBJC section)\n";
4697 }
4698 return false;
4699}
4700
Kevin Enderby0fc11822015-04-01 20:57:01 +00004701static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4702 struct ivar_list64_t il;
4703 struct ivar64_t i;
4704 const char *r;
4705 uint32_t offset, xoffset, left, j;
4706 SectionRef S, xS;
4707 const char *name, *sym_name, *ivar_offset_p;
4708 uint64_t ivar_offset, n_value;
4709
4710 r = get_pointer_64(p, offset, left, S, info);
4711 if (r == nullptr)
4712 return;
4713 memset(&il, '\0', sizeof(struct ivar_list64_t));
4714 if (left < sizeof(struct ivar_list64_t)) {
4715 memcpy(&il, r, left);
4716 outs() << " (ivar_list_t entends past the end of the section)\n";
4717 } else
4718 memcpy(&il, r, sizeof(struct ivar_list64_t));
4719 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4720 swapStruct(il);
4721 outs() << " entsize " << il.entsize << "\n";
4722 outs() << " count " << il.count << "\n";
4723
4724 p += sizeof(struct ivar_list64_t);
4725 offset += sizeof(struct ivar_list64_t);
4726 for (j = 0; j < il.count; j++) {
4727 r = get_pointer_64(p, offset, left, S, info);
4728 if (r == nullptr)
4729 return;
4730 memset(&i, '\0', sizeof(struct ivar64_t));
4731 if (left < sizeof(struct ivar64_t)) {
4732 memcpy(&i, r, left);
4733 outs() << " (ivar_t entends past the end of the section)\n";
4734 } else
4735 memcpy(&i, r, sizeof(struct ivar64_t));
4736 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4737 swapStruct(i);
4738
4739 outs() << "\t\t\t offset ";
4740 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4741 info, n_value, i.offset);
4742 if (n_value != 0) {
4743 if (info->verbose && sym_name != nullptr)
4744 outs() << sym_name;
4745 else
4746 outs() << format("0x%" PRIx64, n_value);
4747 if (i.offset != 0)
4748 outs() << " + " << format("0x%" PRIx64, i.offset);
4749 } else
4750 outs() << format("0x%" PRIx64, i.offset);
4751 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4752 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4753 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4754 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4755 sys::swapByteOrder(ivar_offset);
4756 outs() << " " << ivar_offset << "\n";
4757 } else
4758 outs() << "\n";
4759
4760 outs() << "\t\t\t name ";
4761 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4762 n_value, i.name);
4763 if (n_value != 0) {
4764 if (info->verbose && sym_name != nullptr)
4765 outs() << sym_name;
4766 else
4767 outs() << format("0x%" PRIx64, n_value);
4768 if (i.name != 0)
4769 outs() << " + " << format("0x%" PRIx64, i.name);
4770 } else
4771 outs() << format("0x%" PRIx64, i.name);
4772 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4773 if (name != nullptr)
4774 outs() << format(" %.*s", left, name);
4775 outs() << "\n";
4776
4777 outs() << "\t\t\t type ";
4778 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4779 n_value, i.name);
4780 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4781 if (n_value != 0) {
4782 if (info->verbose && sym_name != nullptr)
4783 outs() << sym_name;
4784 else
4785 outs() << format("0x%" PRIx64, n_value);
4786 if (i.type != 0)
4787 outs() << " + " << format("0x%" PRIx64, i.type);
4788 } else
4789 outs() << format("0x%" PRIx64, i.type);
4790 if (name != nullptr)
4791 outs() << format(" %.*s", left, name);
4792 outs() << "\n";
4793
4794 outs() << "\t\t\talignment " << i.alignment << "\n";
4795 outs() << "\t\t\t size " << i.size << "\n";
4796
4797 p += sizeof(struct ivar64_t);
4798 offset += sizeof(struct ivar64_t);
4799 }
4800}
4801
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004802static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4803 struct ivar_list32_t il;
4804 struct ivar32_t i;
4805 const char *r;
4806 uint32_t offset, xoffset, left, j;
4807 SectionRef S, xS;
4808 const char *name, *ivar_offset_p;
4809 uint32_t ivar_offset;
4810
4811 r = get_pointer_32(p, offset, left, S, info);
4812 if (r == nullptr)
4813 return;
4814 memset(&il, '\0', sizeof(struct ivar_list32_t));
4815 if (left < sizeof(struct ivar_list32_t)) {
4816 memcpy(&il, r, left);
4817 outs() << " (ivar_list_t entends past the end of the section)\n";
4818 } else
4819 memcpy(&il, r, sizeof(struct ivar_list32_t));
4820 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4821 swapStruct(il);
4822 outs() << " entsize " << il.entsize << "\n";
4823 outs() << " count " << il.count << "\n";
4824
4825 p += sizeof(struct ivar_list32_t);
4826 offset += sizeof(struct ivar_list32_t);
4827 for (j = 0; j < il.count; j++) {
4828 r = get_pointer_32(p, offset, left, S, info);
4829 if (r == nullptr)
4830 return;
4831 memset(&i, '\0', sizeof(struct ivar32_t));
4832 if (left < sizeof(struct ivar32_t)) {
4833 memcpy(&i, r, left);
4834 outs() << " (ivar_t entends past the end of the section)\n";
4835 } else
4836 memcpy(&i, r, sizeof(struct ivar32_t));
4837 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4838 swapStruct(i);
4839
4840 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4841 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4842 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4843 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4844 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4845 sys::swapByteOrder(ivar_offset);
4846 outs() << " " << ivar_offset << "\n";
4847 } else
4848 outs() << "\n";
4849
4850 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4851 name = get_pointer_32(i.name, xoffset, left, xS, info);
4852 if (name != nullptr)
4853 outs() << format(" %.*s", left, name);
4854 outs() << "\n";
4855
4856 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4857 name = get_pointer_32(i.type, xoffset, left, xS, info);
4858 if (name != nullptr)
4859 outs() << format(" %.*s", left, name);
4860 outs() << "\n";
4861
4862 outs() << "\t\t\talignment " << i.alignment << "\n";
4863 outs() << "\t\t\t size " << i.size << "\n";
4864
4865 p += sizeof(struct ivar32_t);
4866 offset += sizeof(struct ivar32_t);
4867 }
4868}
4869
Kevin Enderby0fc11822015-04-01 20:57:01 +00004870static void print_objc_property_list64(uint64_t p,
4871 struct DisassembleInfo *info) {
4872 struct objc_property_list64 opl;
4873 struct objc_property64 op;
4874 const char *r;
4875 uint32_t offset, xoffset, left, j;
4876 SectionRef S, xS;
4877 const char *name, *sym_name;
4878 uint64_t n_value;
4879
4880 r = get_pointer_64(p, offset, left, S, info);
4881 if (r == nullptr)
4882 return;
4883 memset(&opl, '\0', sizeof(struct objc_property_list64));
4884 if (left < sizeof(struct objc_property_list64)) {
4885 memcpy(&opl, r, left);
4886 outs() << " (objc_property_list entends past the end of the section)\n";
4887 } else
4888 memcpy(&opl, r, sizeof(struct objc_property_list64));
4889 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4890 swapStruct(opl);
4891 outs() << " entsize " << opl.entsize << "\n";
4892 outs() << " count " << opl.count << "\n";
4893
4894 p += sizeof(struct objc_property_list64);
4895 offset += sizeof(struct objc_property_list64);
4896 for (j = 0; j < opl.count; j++) {
4897 r = get_pointer_64(p, offset, left, S, info);
4898 if (r == nullptr)
4899 return;
4900 memset(&op, '\0', sizeof(struct objc_property64));
4901 if (left < sizeof(struct objc_property64)) {
4902 memcpy(&op, r, left);
4903 outs() << " (objc_property entends past the end of the section)\n";
4904 } else
4905 memcpy(&op, r, sizeof(struct objc_property64));
4906 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4907 swapStruct(op);
4908
4909 outs() << "\t\t\t name ";
4910 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4911 info, n_value, op.name);
4912 if (n_value != 0) {
4913 if (info->verbose && sym_name != nullptr)
4914 outs() << sym_name;
4915 else
4916 outs() << format("0x%" PRIx64, n_value);
4917 if (op.name != 0)
4918 outs() << " + " << format("0x%" PRIx64, op.name);
4919 } else
4920 outs() << format("0x%" PRIx64, op.name);
4921 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4922 if (name != nullptr)
4923 outs() << format(" %.*s", left, name);
4924 outs() << "\n";
4925
4926 outs() << "\t\t\tattributes ";
4927 sym_name =
4928 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4929 info, n_value, op.attributes);
4930 if (n_value != 0) {
4931 if (info->verbose && sym_name != nullptr)
4932 outs() << sym_name;
4933 else
4934 outs() << format("0x%" PRIx64, n_value);
4935 if (op.attributes != 0)
4936 outs() << " + " << format("0x%" PRIx64, op.attributes);
4937 } else
4938 outs() << format("0x%" PRIx64, op.attributes);
4939 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4940 if (name != nullptr)
4941 outs() << format(" %.*s", left, name);
4942 outs() << "\n";
4943
4944 p += sizeof(struct objc_property64);
4945 offset += sizeof(struct objc_property64);
4946 }
4947}
4948
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004949static void print_objc_property_list32(uint32_t p,
4950 struct DisassembleInfo *info) {
4951 struct objc_property_list32 opl;
4952 struct objc_property32 op;
4953 const char *r;
4954 uint32_t offset, xoffset, left, j;
4955 SectionRef S, xS;
4956 const char *name;
4957
4958 r = get_pointer_32(p, offset, left, S, info);
4959 if (r == nullptr)
4960 return;
4961 memset(&opl, '\0', sizeof(struct objc_property_list32));
4962 if (left < sizeof(struct objc_property_list32)) {
4963 memcpy(&opl, r, left);
4964 outs() << " (objc_property_list entends past the end of the section)\n";
4965 } else
4966 memcpy(&opl, r, sizeof(struct objc_property_list32));
4967 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4968 swapStruct(opl);
4969 outs() << " entsize " << opl.entsize << "\n";
4970 outs() << " count " << opl.count << "\n";
4971
4972 p += sizeof(struct objc_property_list32);
4973 offset += sizeof(struct objc_property_list32);
4974 for (j = 0; j < opl.count; j++) {
4975 r = get_pointer_32(p, offset, left, S, info);
4976 if (r == nullptr)
4977 return;
4978 memset(&op, '\0', sizeof(struct objc_property32));
4979 if (left < sizeof(struct objc_property32)) {
4980 memcpy(&op, r, left);
4981 outs() << " (objc_property entends past the end of the section)\n";
4982 } else
4983 memcpy(&op, r, sizeof(struct objc_property32));
4984 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4985 swapStruct(op);
4986
4987 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4988 name = get_pointer_32(op.name, xoffset, left, xS, info);
4989 if (name != nullptr)
4990 outs() << format(" %.*s", left, name);
4991 outs() << "\n";
4992
4993 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4994 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4995 if (name != nullptr)
4996 outs() << format(" %.*s", left, name);
4997 outs() << "\n";
4998
4999 p += sizeof(struct objc_property32);
5000 offset += sizeof(struct objc_property32);
5001 }
5002}
5003
Richard Smith81ff44d2015-10-09 22:09:56 +00005004static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00005005 bool &is_meta_class) {
5006 struct class_ro64_t cro;
5007 const char *r;
5008 uint32_t offset, xoffset, left;
5009 SectionRef S, xS;
5010 const char *name, *sym_name;
5011 uint64_t n_value;
5012
5013 r = get_pointer_64(p, offset, left, S, info);
5014 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00005015 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00005016 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005017 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5018 swapStruct(cro);
5019 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5020 if (cro.flags & RO_META)
5021 outs() << " RO_META";
5022 if (cro.flags & RO_ROOT)
5023 outs() << " RO_ROOT";
5024 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5025 outs() << " RO_HAS_CXX_STRUCTORS";
5026 outs() << "\n";
5027 outs() << " instanceStart " << cro.instanceStart << "\n";
5028 outs() << " instanceSize " << cro.instanceSize << "\n";
5029 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5030 << "\n";
5031 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5032 << "\n";
5033 print_layout_map64(cro.ivarLayout, info);
5034
5035 outs() << " name ";
5036 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5037 info, n_value, cro.name);
5038 if (n_value != 0) {
5039 if (info->verbose && sym_name != nullptr)
5040 outs() << sym_name;
5041 else
5042 outs() << format("0x%" PRIx64, n_value);
5043 if (cro.name != 0)
5044 outs() << " + " << format("0x%" PRIx64, cro.name);
5045 } else
5046 outs() << format("0x%" PRIx64, cro.name);
5047 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5048 if (name != nullptr)
5049 outs() << format(" %.*s", left, name);
5050 outs() << "\n";
5051
5052 outs() << " baseMethods ";
5053 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5054 S, info, n_value, cro.baseMethods);
5055 if (n_value != 0) {
5056 if (info->verbose && sym_name != nullptr)
5057 outs() << sym_name;
5058 else
5059 outs() << format("0x%" PRIx64, n_value);
5060 if (cro.baseMethods != 0)
5061 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5062 } else
5063 outs() << format("0x%" PRIx64, cro.baseMethods);
5064 outs() << " (struct method_list_t *)\n";
5065 if (cro.baseMethods + n_value != 0)
5066 print_method_list64_t(cro.baseMethods + n_value, info, "");
5067
5068 outs() << " baseProtocols ";
5069 sym_name =
5070 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5071 info, n_value, cro.baseProtocols);
5072 if (n_value != 0) {
5073 if (info->verbose && sym_name != nullptr)
5074 outs() << sym_name;
5075 else
5076 outs() << format("0x%" PRIx64, n_value);
5077 if (cro.baseProtocols != 0)
5078 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5079 } else
5080 outs() << format("0x%" PRIx64, cro.baseProtocols);
5081 outs() << "\n";
5082 if (cro.baseProtocols + n_value != 0)
5083 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5084
5085 outs() << " ivars ";
5086 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005087 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005088 if (n_value != 0) {
5089 if (info->verbose && sym_name != nullptr)
5090 outs() << sym_name;
5091 else
5092 outs() << format("0x%" PRIx64, n_value);
5093 if (cro.ivars != 0)
5094 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5095 } else
5096 outs() << format("0x%" PRIx64, cro.ivars);
5097 outs() << "\n";
5098 if (cro.ivars + n_value != 0)
5099 print_ivar_list64_t(cro.ivars + n_value, info);
5100
5101 outs() << " weakIvarLayout ";
5102 sym_name =
5103 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5104 info, n_value, cro.weakIvarLayout);
5105 if (n_value != 0) {
5106 if (info->verbose && sym_name != nullptr)
5107 outs() << sym_name;
5108 else
5109 outs() << format("0x%" PRIx64, n_value);
5110 if (cro.weakIvarLayout != 0)
5111 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5112 } else
5113 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5114 outs() << "\n";
5115 print_layout_map64(cro.weakIvarLayout + n_value, info);
5116
5117 outs() << " baseProperties ";
5118 sym_name =
5119 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5120 info, n_value, cro.baseProperties);
5121 if (n_value != 0) {
5122 if (info->verbose && sym_name != nullptr)
5123 outs() << sym_name;
5124 else
5125 outs() << format("0x%" PRIx64, n_value);
5126 if (cro.baseProperties != 0)
5127 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5128 } else
5129 outs() << format("0x%" PRIx64, cro.baseProperties);
5130 outs() << "\n";
5131 if (cro.baseProperties + n_value != 0)
5132 print_objc_property_list64(cro.baseProperties + n_value, info);
5133
Rafael Espindolab9091322015-10-24 23:19:10 +00005134 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005135 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005136}
5137
Richard Smith81ff44d2015-10-09 22:09:56 +00005138static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005139 bool &is_meta_class) {
5140 struct class_ro32_t cro;
5141 const char *r;
5142 uint32_t offset, xoffset, left;
5143 SectionRef S, xS;
5144 const char *name;
5145
5146 r = get_pointer_32(p, offset, left, S, info);
5147 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00005148 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005149 memset(&cro, '\0', sizeof(struct class_ro32_t));
5150 if (left < sizeof(struct class_ro32_t)) {
5151 memcpy(&cro, r, left);
5152 outs() << " (class_ro_t entends past the end of the section)\n";
5153 } else
5154 memcpy(&cro, r, sizeof(struct class_ro32_t));
5155 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5156 swapStruct(cro);
5157 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5158 if (cro.flags & RO_META)
5159 outs() << " RO_META";
5160 if (cro.flags & RO_ROOT)
5161 outs() << " RO_ROOT";
5162 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5163 outs() << " RO_HAS_CXX_STRUCTORS";
5164 outs() << "\n";
5165 outs() << " instanceStart " << cro.instanceStart << "\n";
5166 outs() << " instanceSize " << cro.instanceSize << "\n";
5167 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5168 << "\n";
5169 print_layout_map32(cro.ivarLayout, info);
5170
5171 outs() << " name " << format("0x%" PRIx32, cro.name);
5172 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5173 if (name != nullptr)
5174 outs() << format(" %.*s", left, name);
5175 outs() << "\n";
5176
5177 outs() << " baseMethods "
5178 << format("0x%" PRIx32, cro.baseMethods)
5179 << " (struct method_list_t *)\n";
5180 if (cro.baseMethods != 0)
5181 print_method_list32_t(cro.baseMethods, info, "");
5182
5183 outs() << " baseProtocols "
5184 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5185 if (cro.baseProtocols != 0)
5186 print_protocol_list32_t(cro.baseProtocols, info);
5187 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5188 << "\n";
5189 if (cro.ivars != 0)
5190 print_ivar_list32_t(cro.ivars, info);
5191 outs() << " weakIvarLayout "
5192 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5193 print_layout_map32(cro.weakIvarLayout, info);
5194 outs() << " baseProperties "
5195 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5196 if (cro.baseProperties != 0)
5197 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00005198 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005199 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005200}
5201
Kevin Enderby0fc11822015-04-01 20:57:01 +00005202static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5203 struct class64_t c;
5204 const char *r;
5205 uint32_t offset, left;
5206 SectionRef S;
5207 const char *name;
5208 uint64_t isa_n_value, n_value;
5209
5210 r = get_pointer_64(p, offset, left, S, info);
5211 if (r == nullptr || left < sizeof(struct class64_t))
5212 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005213 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005214 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5215 swapStruct(c);
5216
5217 outs() << " isa " << format("0x%" PRIx64, c.isa);
5218 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5219 isa_n_value, c.isa);
5220 if (name != nullptr)
5221 outs() << " " << name;
5222 outs() << "\n";
5223
5224 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5225 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5226 n_value, c.superclass);
5227 if (name != nullptr)
5228 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005229 else {
5230 name = get_dyld_bind_info_symbolname(S.getAddress() +
5231 offset + offsetof(struct class64_t, superclass), info);
5232 if (name != nullptr)
5233 outs() << " " << name;
5234 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005235 outs() << "\n";
5236
5237 outs() << " cache " << format("0x%" PRIx64, c.cache);
5238 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5239 n_value, c.cache);
5240 if (name != nullptr)
5241 outs() << " " << name;
5242 outs() << "\n";
5243
5244 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5245 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5246 n_value, c.vtable);
5247 if (name != nullptr)
5248 outs() << " " << name;
5249 outs() << "\n";
5250
5251 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5252 n_value, c.data);
5253 outs() << " data ";
5254 if (n_value != 0) {
5255 if (info->verbose && name != nullptr)
5256 outs() << name;
5257 else
5258 outs() << format("0x%" PRIx64, n_value);
5259 if (c.data != 0)
5260 outs() << " + " << format("0x%" PRIx64, c.data);
5261 } else
5262 outs() << format("0x%" PRIx64, c.data);
5263 outs() << " (struct class_ro_t *)";
5264
5265 // This is a Swift class if some of the low bits of the pointer are set.
5266 if ((c.data + n_value) & 0x7)
5267 outs() << " Swift class";
5268 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005269 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005270 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5271 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005272
Kevin Enderbyaac75382015-10-08 16:56:35 +00005273 if (!is_meta_class &&
5274 c.isa + isa_n_value != p &&
5275 c.isa + isa_n_value != 0 &&
5276 info->depth < 100) {
5277 info->depth++;
5278 outs() << "Meta Class\n";
5279 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005280 }
5281}
5282
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005283static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5284 struct class32_t c;
5285 const char *r;
5286 uint32_t offset, left;
5287 SectionRef S;
5288 const char *name;
5289
5290 r = get_pointer_32(p, offset, left, S, info);
5291 if (r == nullptr)
5292 return;
5293 memset(&c, '\0', sizeof(struct class32_t));
5294 if (left < sizeof(struct class32_t)) {
5295 memcpy(&c, r, left);
5296 outs() << " (class_t entends past the end of the section)\n";
5297 } else
5298 memcpy(&c, r, sizeof(struct class32_t));
5299 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5300 swapStruct(c);
5301
5302 outs() << " isa " << format("0x%" PRIx32, c.isa);
5303 name =
5304 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5305 if (name != nullptr)
5306 outs() << " " << name;
5307 outs() << "\n";
5308
5309 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5310 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5311 c.superclass);
5312 if (name != nullptr)
5313 outs() << " " << name;
5314 outs() << "\n";
5315
5316 outs() << " cache " << format("0x%" PRIx32, c.cache);
5317 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5318 c.cache);
5319 if (name != nullptr)
5320 outs() << " " << name;
5321 outs() << "\n";
5322
5323 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5324 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5325 c.vtable);
5326 if (name != nullptr)
5327 outs() << " " << name;
5328 outs() << "\n";
5329
5330 name =
5331 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5332 outs() << " data " << format("0x%" PRIx32, c.data)
5333 << " (struct class_ro_t *)";
5334
5335 // This is a Swift class if some of the low bits of the pointer are set.
5336 if (c.data & 0x3)
5337 outs() << " Swift class";
5338 outs() << "\n";
5339 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005340 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5341 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005342
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005343 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005344 outs() << "Meta Class\n";
5345 print_class32_t(c.isa, info);
5346 }
5347}
5348
Kevin Enderby846c0002015-04-16 17:19:59 +00005349static void print_objc_class_t(struct objc_class_t *objc_class,
5350 struct DisassembleInfo *info) {
5351 uint32_t offset, left, xleft;
5352 const char *name, *p, *ivar_list;
5353 SectionRef S;
5354 int32_t i;
5355 struct objc_ivar_list_t objc_ivar_list;
5356 struct objc_ivar_t ivar;
5357
5358 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5359 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5360 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5361 if (name != nullptr)
5362 outs() << format(" %.*s", left, name);
5363 else
5364 outs() << " (not in an __OBJC section)";
5365 }
5366 outs() << "\n";
5367
5368 outs() << "\t super_class "
5369 << format("0x%08" PRIx32, objc_class->super_class);
5370 if (info->verbose) {
5371 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5372 if (name != nullptr)
5373 outs() << format(" %.*s", left, name);
5374 else
5375 outs() << " (not in an __OBJC section)";
5376 }
5377 outs() << "\n";
5378
5379 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5380 if (info->verbose) {
5381 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5382 if (name != nullptr)
5383 outs() << format(" %.*s", left, name);
5384 else
5385 outs() << " (not in an __OBJC section)";
5386 }
5387 outs() << "\n";
5388
5389 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5390 << "\n";
5391
5392 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5393 if (info->verbose) {
5394 if (CLS_GETINFO(objc_class, CLS_CLASS))
5395 outs() << " CLS_CLASS";
5396 else if (CLS_GETINFO(objc_class, CLS_META))
5397 outs() << " CLS_META";
5398 }
5399 outs() << "\n";
5400
5401 outs() << "\t instance_size "
5402 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5403
5404 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5405 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5406 if (p != nullptr) {
5407 if (left > sizeof(struct objc_ivar_list_t)) {
5408 outs() << "\n";
5409 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5410 } else {
5411 outs() << " (entends past the end of the section)\n";
5412 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5413 memcpy(&objc_ivar_list, p, left);
5414 }
5415 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5416 swapStruct(objc_ivar_list);
5417 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5418 ivar_list = p + sizeof(struct objc_ivar_list_t);
5419 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5420 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5421 outs() << "\t\t remaining ivar's extend past the of the section\n";
5422 break;
5423 }
5424 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5425 sizeof(struct objc_ivar_t));
5426 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5427 swapStruct(ivar);
5428
5429 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5430 if (info->verbose) {
5431 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5432 if (name != nullptr)
5433 outs() << format(" %.*s", xleft, name);
5434 else
5435 outs() << " (not in an __OBJC section)";
5436 }
5437 outs() << "\n";
5438
5439 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5440 if (info->verbose) {
5441 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5442 if (name != nullptr)
5443 outs() << format(" %.*s", xleft, name);
5444 else
5445 outs() << " (not in an __OBJC section)";
5446 }
5447 outs() << "\n";
5448
5449 outs() << "\t\t ivar_offset "
5450 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5451 }
5452 } else {
5453 outs() << " (not in an __OBJC section)\n";
5454 }
5455
5456 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5457 if (print_method_list(objc_class->methodLists, info))
5458 outs() << " (not in an __OBJC section)\n";
5459
5460 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5461 << "\n";
5462
5463 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5464 if (print_protocol_list(objc_class->protocols, 16, info))
5465 outs() << " (not in an __OBJC section)\n";
5466}
5467
5468static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5469 struct DisassembleInfo *info) {
5470 uint32_t offset, left;
5471 const char *name;
5472 SectionRef S;
5473
5474 outs() << "\t category name "
5475 << format("0x%08" PRIx32, objc_category->category_name);
5476 if (info->verbose) {
5477 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5478 true);
5479 if (name != nullptr)
5480 outs() << format(" %.*s", left, name);
5481 else
5482 outs() << " (not in an __OBJC section)";
5483 }
5484 outs() << "\n";
5485
5486 outs() << "\t\t class name "
5487 << format("0x%08" PRIx32, objc_category->class_name);
5488 if (info->verbose) {
5489 name =
5490 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5491 if (name != nullptr)
5492 outs() << format(" %.*s", left, name);
5493 else
5494 outs() << " (not in an __OBJC section)";
5495 }
5496 outs() << "\n";
5497
5498 outs() << "\t instance methods "
5499 << format("0x%08" PRIx32, objc_category->instance_methods);
5500 if (print_method_list(objc_category->instance_methods, info))
5501 outs() << " (not in an __OBJC section)\n";
5502
5503 outs() << "\t class methods "
5504 << format("0x%08" PRIx32, objc_category->class_methods);
5505 if (print_method_list(objc_category->class_methods, info))
5506 outs() << " (not in an __OBJC section)\n";
5507}
5508
Kevin Enderby0fc11822015-04-01 20:57:01 +00005509static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5510 struct category64_t c;
5511 const char *r;
5512 uint32_t offset, xoffset, left;
5513 SectionRef S, xS;
5514 const char *name, *sym_name;
5515 uint64_t n_value;
5516
5517 r = get_pointer_64(p, offset, left, S, info);
5518 if (r == nullptr)
5519 return;
5520 memset(&c, '\0', sizeof(struct category64_t));
5521 if (left < sizeof(struct category64_t)) {
5522 memcpy(&c, r, left);
5523 outs() << " (category_t entends past the end of the section)\n";
5524 } else
5525 memcpy(&c, r, sizeof(struct category64_t));
5526 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5527 swapStruct(c);
5528
5529 outs() << " name ";
5530 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5531 info, n_value, c.name);
5532 if (n_value != 0) {
5533 if (info->verbose && sym_name != nullptr)
5534 outs() << sym_name;
5535 else
5536 outs() << format("0x%" PRIx64, n_value);
5537 if (c.name != 0)
5538 outs() << " + " << format("0x%" PRIx64, c.name);
5539 } else
5540 outs() << format("0x%" PRIx64, c.name);
5541 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5542 if (name != nullptr)
5543 outs() << format(" %.*s", left, name);
5544 outs() << "\n";
5545
5546 outs() << " cls ";
5547 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5548 n_value, c.cls);
5549 if (n_value != 0) {
5550 if (info->verbose && sym_name != nullptr)
5551 outs() << sym_name;
5552 else
5553 outs() << format("0x%" PRIx64, n_value);
5554 if (c.cls != 0)
5555 outs() << " + " << format("0x%" PRIx64, c.cls);
5556 } else
5557 outs() << format("0x%" PRIx64, c.cls);
5558 outs() << "\n";
5559 if (c.cls + n_value != 0)
5560 print_class64_t(c.cls + n_value, info);
5561
5562 outs() << " instanceMethods ";
5563 sym_name =
5564 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5565 info, n_value, c.instanceMethods);
5566 if (n_value != 0) {
5567 if (info->verbose && sym_name != nullptr)
5568 outs() << sym_name;
5569 else
5570 outs() << format("0x%" PRIx64, n_value);
5571 if (c.instanceMethods != 0)
5572 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5573 } else
5574 outs() << format("0x%" PRIx64, c.instanceMethods);
5575 outs() << "\n";
5576 if (c.instanceMethods + n_value != 0)
5577 print_method_list64_t(c.instanceMethods + n_value, info, "");
5578
5579 outs() << " classMethods ";
5580 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5581 S, info, n_value, c.classMethods);
5582 if (n_value != 0) {
5583 if (info->verbose && sym_name != nullptr)
5584 outs() << sym_name;
5585 else
5586 outs() << format("0x%" PRIx64, n_value);
5587 if (c.classMethods != 0)
5588 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5589 } else
5590 outs() << format("0x%" PRIx64, c.classMethods);
5591 outs() << "\n";
5592 if (c.classMethods + n_value != 0)
5593 print_method_list64_t(c.classMethods + n_value, info, "");
5594
5595 outs() << " protocols ";
5596 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5597 info, n_value, c.protocols);
5598 if (n_value != 0) {
5599 if (info->verbose && sym_name != nullptr)
5600 outs() << sym_name;
5601 else
5602 outs() << format("0x%" PRIx64, n_value);
5603 if (c.protocols != 0)
5604 outs() << " + " << format("0x%" PRIx64, c.protocols);
5605 } else
5606 outs() << format("0x%" PRIx64, c.protocols);
5607 outs() << "\n";
5608 if (c.protocols + n_value != 0)
5609 print_protocol_list64_t(c.protocols + n_value, info);
5610
5611 outs() << "instanceProperties ";
5612 sym_name =
5613 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5614 S, info, n_value, c.instanceProperties);
5615 if (n_value != 0) {
5616 if (info->verbose && sym_name != nullptr)
5617 outs() << sym_name;
5618 else
5619 outs() << format("0x%" PRIx64, n_value);
5620 if (c.instanceProperties != 0)
5621 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5622 } else
5623 outs() << format("0x%" PRIx64, c.instanceProperties);
5624 outs() << "\n";
5625 if (c.instanceProperties + n_value != 0)
5626 print_objc_property_list64(c.instanceProperties + n_value, info);
5627}
5628
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005629static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5630 struct category32_t c;
5631 const char *r;
5632 uint32_t offset, left;
5633 SectionRef S, xS;
5634 const char *name;
5635
5636 r = get_pointer_32(p, offset, left, S, info);
5637 if (r == nullptr)
5638 return;
5639 memset(&c, '\0', sizeof(struct category32_t));
5640 if (left < sizeof(struct category32_t)) {
5641 memcpy(&c, r, left);
5642 outs() << " (category_t entends past the end of the section)\n";
5643 } else
5644 memcpy(&c, r, sizeof(struct category32_t));
5645 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5646 swapStruct(c);
5647
5648 outs() << " name " << format("0x%" PRIx32, c.name);
5649 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5650 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005651 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005652 outs() << " " << name;
5653 outs() << "\n";
5654
5655 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5656 if (c.cls != 0)
5657 print_class32_t(c.cls, info);
5658 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5659 << "\n";
5660 if (c.instanceMethods != 0)
5661 print_method_list32_t(c.instanceMethods, info, "");
5662 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5663 << "\n";
5664 if (c.classMethods != 0)
5665 print_method_list32_t(c.classMethods, info, "");
5666 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5667 if (c.protocols != 0)
5668 print_protocol_list32_t(c.protocols, info);
5669 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5670 << "\n";
5671 if (c.instanceProperties != 0)
5672 print_objc_property_list32(c.instanceProperties, info);
5673}
5674
Kevin Enderby0fc11822015-04-01 20:57:01 +00005675static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5676 uint32_t i, left, offset, xoffset;
5677 uint64_t p, n_value;
5678 struct message_ref64 mr;
5679 const char *name, *sym_name;
5680 const char *r;
5681 SectionRef xS;
5682
5683 if (S == SectionRef())
5684 return;
5685
5686 StringRef SectName;
5687 S.getName(SectName);
5688 DataRefImpl Ref = S.getRawDataRefImpl();
5689 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5690 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5691 offset = 0;
5692 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5693 p = S.getAddress() + i;
5694 r = get_pointer_64(p, offset, left, S, info);
5695 if (r == nullptr)
5696 return;
5697 memset(&mr, '\0', sizeof(struct message_ref64));
5698 if (left < sizeof(struct message_ref64)) {
5699 memcpy(&mr, r, left);
5700 outs() << " (message_ref entends past the end of the section)\n";
5701 } else
5702 memcpy(&mr, r, sizeof(struct message_ref64));
5703 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5704 swapStruct(mr);
5705
5706 outs() << " imp ";
5707 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5708 n_value, mr.imp);
5709 if (n_value != 0) {
5710 outs() << format("0x%" PRIx64, n_value) << " ";
5711 if (mr.imp != 0)
5712 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5713 } else
5714 outs() << format("0x%" PRIx64, mr.imp) << " ";
5715 if (name != nullptr)
5716 outs() << " " << name;
5717 outs() << "\n";
5718
5719 outs() << " sel ";
5720 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5721 info, n_value, mr.sel);
5722 if (n_value != 0) {
5723 if (info->verbose && sym_name != nullptr)
5724 outs() << sym_name;
5725 else
5726 outs() << format("0x%" PRIx64, n_value);
5727 if (mr.sel != 0)
5728 outs() << " + " << format("0x%" PRIx64, mr.sel);
5729 } else
5730 outs() << format("0x%" PRIx64, mr.sel);
5731 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5732 if (name != nullptr)
5733 outs() << format(" %.*s", left, name);
5734 outs() << "\n";
5735
5736 offset += sizeof(struct message_ref64);
5737 }
5738}
5739
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005740static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5741 uint32_t i, left, offset, xoffset, p;
5742 struct message_ref32 mr;
5743 const char *name, *r;
5744 SectionRef xS;
5745
5746 if (S == SectionRef())
5747 return;
5748
5749 StringRef SectName;
5750 S.getName(SectName);
5751 DataRefImpl Ref = S.getRawDataRefImpl();
5752 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5753 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5754 offset = 0;
5755 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5756 p = S.getAddress() + i;
5757 r = get_pointer_32(p, offset, left, S, info);
5758 if (r == nullptr)
5759 return;
5760 memset(&mr, '\0', sizeof(struct message_ref32));
5761 if (left < sizeof(struct message_ref32)) {
5762 memcpy(&mr, r, left);
5763 outs() << " (message_ref entends past the end of the section)\n";
5764 } else
5765 memcpy(&mr, r, sizeof(struct message_ref32));
5766 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5767 swapStruct(mr);
5768
5769 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5770 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5771 mr.imp);
5772 if (name != nullptr)
5773 outs() << " " << name;
5774 outs() << "\n";
5775
5776 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5777 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5778 if (name != nullptr)
5779 outs() << " " << name;
5780 outs() << "\n";
5781
5782 offset += sizeof(struct message_ref32);
5783 }
5784}
5785
Kevin Enderby0fc11822015-04-01 20:57:01 +00005786static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5787 uint32_t left, offset, swift_version;
5788 uint64_t p;
5789 struct objc_image_info64 o;
5790 const char *r;
5791
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005792 if (S == SectionRef())
5793 return;
5794
Kevin Enderby0fc11822015-04-01 20:57:01 +00005795 StringRef SectName;
5796 S.getName(SectName);
5797 DataRefImpl Ref = S.getRawDataRefImpl();
5798 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5799 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5800 p = S.getAddress();
5801 r = get_pointer_64(p, offset, left, S, info);
5802 if (r == nullptr)
5803 return;
5804 memset(&o, '\0', sizeof(struct objc_image_info64));
5805 if (left < sizeof(struct objc_image_info64)) {
5806 memcpy(&o, r, left);
5807 outs() << " (objc_image_info entends past the end of the section)\n";
5808 } else
5809 memcpy(&o, r, sizeof(struct objc_image_info64));
5810 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5811 swapStruct(o);
5812 outs() << " version " << o.version << "\n";
5813 outs() << " flags " << format("0x%" PRIx32, o.flags);
5814 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5815 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5816 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5817 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005818 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5819 outs() << " OBJC_IMAGE_IS_SIMULATED";
5820 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5821 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005822 swift_version = (o.flags >> 8) & 0xff;
5823 if (swift_version != 0) {
5824 if (swift_version == 1)
5825 outs() << " Swift 1.0";
5826 else if (swift_version == 2)
5827 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005828 else if(swift_version == 3)
5829 outs() << " Swift 2.0";
5830 else if(swift_version == 4)
5831 outs() << " Swift 3.0";
5832 else if(swift_version == 5)
5833 outs() << " Swift 4.0";
5834 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005835 outs() << " Swift 4.1/Swift 4.2";
5836 else if(swift_version == 7)
5837 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005838 else
5839 outs() << " unknown future Swift version (" << swift_version << ")";
5840 }
5841 outs() << "\n";
5842}
5843
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005844static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5845 uint32_t left, offset, swift_version, p;
5846 struct objc_image_info32 o;
5847 const char *r;
5848
Kevin Enderby19be2512016-04-21 19:49:29 +00005849 if (S == SectionRef())
5850 return;
5851
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005852 StringRef SectName;
5853 S.getName(SectName);
5854 DataRefImpl Ref = S.getRawDataRefImpl();
5855 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5856 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5857 p = S.getAddress();
5858 r = get_pointer_32(p, offset, left, S, info);
5859 if (r == nullptr)
5860 return;
5861 memset(&o, '\0', sizeof(struct objc_image_info32));
5862 if (left < sizeof(struct objc_image_info32)) {
5863 memcpy(&o, r, left);
5864 outs() << " (objc_image_info entends past the end of the section)\n";
5865 } else
5866 memcpy(&o, r, sizeof(struct objc_image_info32));
5867 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5868 swapStruct(o);
5869 outs() << " version " << o.version << "\n";
5870 outs() << " flags " << format("0x%" PRIx32, o.flags);
5871 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5872 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5873 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5874 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5875 swift_version = (o.flags >> 8) & 0xff;
5876 if (swift_version != 0) {
5877 if (swift_version == 1)
5878 outs() << " Swift 1.0";
5879 else if (swift_version == 2)
5880 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005881 else if(swift_version == 3)
5882 outs() << " Swift 2.0";
5883 else if(swift_version == 4)
5884 outs() << " Swift 3.0";
5885 else if(swift_version == 5)
5886 outs() << " Swift 4.0";
5887 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005888 outs() << " Swift 4.1/Swift 4.2";
5889 else if(swift_version == 7)
5890 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005891 else
5892 outs() << " unknown future Swift version (" << swift_version << ")";
5893 }
5894 outs() << "\n";
5895}
5896
Kevin Enderby846c0002015-04-16 17:19:59 +00005897static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5898 uint32_t left, offset, p;
5899 struct imageInfo_t o;
5900 const char *r;
5901
5902 StringRef SectName;
5903 S.getName(SectName);
5904 DataRefImpl Ref = S.getRawDataRefImpl();
5905 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5906 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5907 p = S.getAddress();
5908 r = get_pointer_32(p, offset, left, S, info);
5909 if (r == nullptr)
5910 return;
5911 memset(&o, '\0', sizeof(struct imageInfo_t));
5912 if (left < sizeof(struct imageInfo_t)) {
5913 memcpy(&o, r, left);
5914 outs() << " (imageInfo entends past the end of the section)\n";
5915 } else
5916 memcpy(&o, r, sizeof(struct imageInfo_t));
5917 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5918 swapStruct(o);
5919 outs() << " version " << o.version << "\n";
5920 outs() << " flags " << format("0x%" PRIx32, o.flags);
5921 if (o.flags & 0x1)
5922 outs() << " F&C";
5923 if (o.flags & 0x2)
5924 outs() << " GC";
5925 if (o.flags & 0x4)
5926 outs() << " GC-only";
5927 else
5928 outs() << " RR";
5929 outs() << "\n";
5930}
5931
Kevin Enderby0fc11822015-04-01 20:57:01 +00005932static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5933 SymbolAddressMap AddrMap;
5934 if (verbose)
5935 CreateSymbolAddressMap(O, &AddrMap);
5936
5937 std::vector<SectionRef> Sections;
5938 for (const SectionRef &Section : O->sections()) {
5939 StringRef SectName;
5940 Section.getName(SectName);
5941 Sections.push_back(Section);
5942 }
5943
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005944 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005945
Davide Italiano62507042015-12-11 22:27:59 +00005946 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5947 if (CL == SectionRef())
5948 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005949 if (CL == SectionRef())
5950 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5951 if (CL == SectionRef())
5952 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005953 info.S = CL;
5954 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005955
Davide Italiano62507042015-12-11 22:27:59 +00005956 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5957 if (CR == SectionRef())
5958 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005959 if (CR == SectionRef())
5960 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5961 if (CR == SectionRef())
5962 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005963 info.S = CR;
5964 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005965
Davide Italiano62507042015-12-11 22:27:59 +00005966 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5967 if (SR == SectionRef())
5968 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005969 if (SR == SectionRef())
5970 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5971 if (SR == SectionRef())
5972 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005973 info.S = SR;
5974 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005975
Davide Italiano62507042015-12-11 22:27:59 +00005976 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5977 if (CA == SectionRef())
5978 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005979 if (CA == SectionRef())
5980 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5981 if (CA == SectionRef())
5982 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005983 info.S = CA;
5984 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005985
Davide Italiano62507042015-12-11 22:27:59 +00005986 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5987 if (PL == SectionRef())
5988 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005989 if (PL == SectionRef())
5990 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5991 if (PL == SectionRef())
5992 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005993 info.S = PL;
5994 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005995
Davide Italiano62507042015-12-11 22:27:59 +00005996 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5997 if (MR == SectionRef())
5998 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005999 if (MR == SectionRef())
6000 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6001 if (MR == SectionRef())
6002 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006003 info.S = MR;
6004 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006005
Davide Italiano62507042015-12-11 22:27:59 +00006006 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6007 if (II == SectionRef())
6008 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00006009 if (II == SectionRef())
6010 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6011 if (II == SectionRef())
6012 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00006013 info.S = II;
6014 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006015}
6016
6017static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006018 SymbolAddressMap AddrMap;
6019 if (verbose)
6020 CreateSymbolAddressMap(O, &AddrMap);
6021
6022 std::vector<SectionRef> Sections;
6023 for (const SectionRef &Section : O->sections()) {
6024 StringRef SectName;
6025 Section.getName(SectName);
6026 Sections.push_back(Section);
6027 }
6028
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006029 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006030
Kevin Enderby5879a482017-02-09 17:56:26 +00006031 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6032 if (CL == SectionRef())
6033 CL = get_section(O, "__DATA", "__objc_classlist");
6034 if (CL == SectionRef())
6035 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6036 if (CL == SectionRef())
6037 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6038 info.S = CL;
6039 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006040
Kevin Enderby5879a482017-02-09 17:56:26 +00006041 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6042 if (CR == SectionRef())
6043 CR = get_section(O, "__DATA", "__objc_classrefs");
6044 if (CR == SectionRef())
6045 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6046 if (CR == SectionRef())
6047 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6048 info.S = CR;
6049 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006050
Kevin Enderby5879a482017-02-09 17:56:26 +00006051 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6052 if (SR == SectionRef())
6053 SR = get_section(O, "__DATA", "__objc_superrefs");
6054 if (SR == SectionRef())
6055 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6056 if (SR == SectionRef())
6057 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6058 info.S = SR;
6059 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006060
Kevin Enderby5879a482017-02-09 17:56:26 +00006061 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6062 if (CA == SectionRef())
6063 CA = get_section(O, "__DATA", "__objc_catlist");
6064 if (CA == SectionRef())
6065 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6066 if (CA == SectionRef())
6067 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6068 info.S = CA;
6069 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006070
Kevin Enderby5879a482017-02-09 17:56:26 +00006071 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6072 if (PL == SectionRef())
6073 PL = get_section(O, "__DATA", "__objc_protolist");
6074 if (PL == SectionRef())
6075 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6076 if (PL == SectionRef())
6077 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6078 info.S = PL;
6079 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006080
Kevin Enderby5879a482017-02-09 17:56:26 +00006081 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6082 if (MR == SectionRef())
6083 MR = get_section(O, "__DATA", "__objc_msgrefs");
6084 if (MR == SectionRef())
6085 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6086 if (MR == SectionRef())
6087 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6088 info.S = MR;
6089 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006090
Kevin Enderby5879a482017-02-09 17:56:26 +00006091 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6092 if (II == SectionRef())
6093 II = get_section(O, "__DATA", "__objc_imageinfo");
6094 if (II == SectionRef())
6095 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6096 if (II == SectionRef())
6097 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6098 info.S = II;
6099 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006100}
6101
6102static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00006103 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6104 const char *r, *name, *defs;
6105 struct objc_module_t module;
6106 SectionRef S, xS;
6107 struct objc_symtab_t symtab;
6108 struct objc_class_t objc_class;
6109 struct objc_category_t objc_category;
6110
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006111 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00006112 S = get_section(O, "__OBJC", "__module_info");
6113 if (S == SectionRef())
6114 return false;
6115
6116 SymbolAddressMap AddrMap;
6117 if (verbose)
6118 CreateSymbolAddressMap(O, &AddrMap);
6119
6120 std::vector<SectionRef> Sections;
6121 for (const SectionRef &Section : O->sections()) {
6122 StringRef SectName;
6123 Section.getName(SectName);
6124 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006125 }
Kevin Enderby846c0002015-04-16 17:19:59 +00006126
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006127 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00006128
6129 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6130 p = S.getAddress() + i;
6131 r = get_pointer_32(p, offset, left, S, &info, true);
6132 if (r == nullptr)
6133 return true;
6134 memset(&module, '\0', sizeof(struct objc_module_t));
6135 if (left < sizeof(struct objc_module_t)) {
6136 memcpy(&module, r, left);
6137 outs() << " (module extends past end of __module_info section)\n";
6138 } else
6139 memcpy(&module, r, sizeof(struct objc_module_t));
6140 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6141 swapStruct(module);
6142
6143 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6144 outs() << " version " << module.version << "\n";
6145 outs() << " size " << module.size << "\n";
6146 outs() << " name ";
6147 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6148 if (name != nullptr)
6149 outs() << format("%.*s", left, name);
6150 else
6151 outs() << format("0x%08" PRIx32, module.name)
6152 << "(not in an __OBJC section)";
6153 outs() << "\n";
6154
6155 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6156 if (module.symtab == 0 || r == nullptr) {
6157 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6158 << " (not in an __OBJC section)\n";
6159 continue;
6160 }
6161 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6162 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6163 defs_left = 0;
6164 defs = nullptr;
6165 if (left < sizeof(struct objc_symtab_t)) {
6166 memcpy(&symtab, r, left);
6167 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6168 } else {
6169 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6170 if (left > sizeof(struct objc_symtab_t)) {
6171 defs_left = left - sizeof(struct objc_symtab_t);
6172 defs = r + sizeof(struct objc_symtab_t);
6173 }
6174 }
6175 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6176 swapStruct(symtab);
6177
6178 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6179 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6180 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6181 if (r == nullptr)
6182 outs() << " (not in an __OBJC section)";
6183 outs() << "\n";
6184 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6185 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6186 if (symtab.cls_def_cnt > 0)
6187 outs() << "\tClass Definitions\n";
6188 for (j = 0; j < symtab.cls_def_cnt; j++) {
6189 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6190 outs() << "\t(remaining class defs entries entends past the end of the "
6191 << "section)\n";
6192 break;
6193 }
6194 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6195 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6196 sys::swapByteOrder(def);
6197
6198 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6199 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6200 if (r != nullptr) {
6201 if (left > sizeof(struct objc_class_t)) {
6202 outs() << "\n";
6203 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6204 } else {
6205 outs() << " (entends past the end of the section)\n";
6206 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6207 memcpy(&objc_class, r, left);
6208 }
6209 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6210 swapStruct(objc_class);
6211 print_objc_class_t(&objc_class, &info);
6212 } else {
6213 outs() << "(not in an __OBJC section)\n";
6214 }
6215
6216 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6217 outs() << "\tMeta Class";
6218 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6219 if (r != nullptr) {
6220 if (left > sizeof(struct objc_class_t)) {
6221 outs() << "\n";
6222 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6223 } else {
6224 outs() << " (entends past the end of the section)\n";
6225 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6226 memcpy(&objc_class, r, left);
6227 }
6228 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6229 swapStruct(objc_class);
6230 print_objc_class_t(&objc_class, &info);
6231 } else {
6232 outs() << "(not in an __OBJC section)\n";
6233 }
6234 }
6235 }
6236 if (symtab.cat_def_cnt > 0)
6237 outs() << "\tCategory Definitions\n";
6238 for (j = 0; j < symtab.cat_def_cnt; j++) {
6239 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6240 outs() << "\t(remaining category defs entries entends past the end of "
6241 << "the section)\n";
6242 break;
6243 }
6244 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6245 sizeof(uint32_t));
6246 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6247 sys::swapByteOrder(def);
6248
6249 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6250 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6251 << format("0x%08" PRIx32, def);
6252 if (r != nullptr) {
6253 if (left > sizeof(struct objc_category_t)) {
6254 outs() << "\n";
6255 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6256 } else {
6257 outs() << " (entends past the end of the section)\n";
6258 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6259 memcpy(&objc_category, r, left);
6260 }
6261 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6262 swapStruct(objc_category);
6263 print_objc_objc_category_t(&objc_category, &info);
6264 } else {
6265 outs() << "(not in an __OBJC section)\n";
6266 }
6267 }
6268 }
6269 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6270 if (II != SectionRef())
6271 print_image_info(II, &info);
6272
6273 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006274}
6275
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006276static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6277 uint32_t size, uint32_t addr) {
6278 SymbolAddressMap AddrMap;
6279 CreateSymbolAddressMap(O, &AddrMap);
6280
6281 std::vector<SectionRef> Sections;
6282 for (const SectionRef &Section : O->sections()) {
6283 StringRef SectName;
6284 Section.getName(SectName);
6285 Sections.push_back(Section);
6286 }
6287
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006288 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006289
6290 const char *p;
6291 struct objc_protocol_t protocol;
6292 uint32_t left, paddr;
6293 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6294 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6295 left = size - (p - sect);
6296 if (left < sizeof(struct objc_protocol_t)) {
6297 outs() << "Protocol extends past end of __protocol section\n";
6298 memcpy(&protocol, p, left);
6299 } else
6300 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6301 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6302 swapStruct(protocol);
6303 paddr = addr + (p - sect);
6304 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6305 if (print_protocol(paddr, 0, &info))
6306 outs() << "(not in an __OBJC section)\n";
6307 }
6308}
6309
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006310#ifdef HAVE_LIBXAR
6311inline void swapStruct(struct xar_header &xar) {
6312 sys::swapByteOrder(xar.magic);
6313 sys::swapByteOrder(xar.size);
6314 sys::swapByteOrder(xar.version);
6315 sys::swapByteOrder(xar.toc_length_compressed);
6316 sys::swapByteOrder(xar.toc_length_uncompressed);
6317 sys::swapByteOrder(xar.cksum_alg);
6318}
6319
6320static void PrintModeVerbose(uint32_t mode) {
6321 switch(mode & S_IFMT){
6322 case S_IFDIR:
6323 outs() << "d";
6324 break;
6325 case S_IFCHR:
6326 outs() << "c";
6327 break;
6328 case S_IFBLK:
6329 outs() << "b";
6330 break;
6331 case S_IFREG:
6332 outs() << "-";
6333 break;
6334 case S_IFLNK:
6335 outs() << "l";
6336 break;
6337 case S_IFSOCK:
6338 outs() << "s";
6339 break;
6340 default:
6341 outs() << "?";
6342 break;
6343 }
6344
6345 /* owner permissions */
6346 if(mode & S_IREAD)
6347 outs() << "r";
6348 else
6349 outs() << "-";
6350 if(mode & S_IWRITE)
6351 outs() << "w";
6352 else
6353 outs() << "-";
6354 if(mode & S_ISUID)
6355 outs() << "s";
6356 else if(mode & S_IEXEC)
6357 outs() << "x";
6358 else
6359 outs() << "-";
6360
6361 /* group permissions */
6362 if(mode & (S_IREAD >> 3))
6363 outs() << "r";
6364 else
6365 outs() << "-";
6366 if(mode & (S_IWRITE >> 3))
6367 outs() << "w";
6368 else
6369 outs() << "-";
6370 if(mode & S_ISGID)
6371 outs() << "s";
6372 else if(mode & (S_IEXEC >> 3))
6373 outs() << "x";
6374 else
6375 outs() << "-";
6376
6377 /* other permissions */
6378 if(mode & (S_IREAD >> 6))
6379 outs() << "r";
6380 else
6381 outs() << "-";
6382 if(mode & (S_IWRITE >> 6))
6383 outs() << "w";
6384 else
6385 outs() << "-";
6386 if(mode & S_ISVTX)
6387 outs() << "t";
6388 else if(mode & (S_IEXEC >> 6))
6389 outs() << "x";
6390 else
6391 outs() << "-";
6392}
6393
6394static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006395 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006396 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6397 char *endp;
6398 uint32_t mode_value;
6399
Francis Ricci6f942972017-10-06 15:33:28 +00006400 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006401 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006402 WithColor::error(errs(), "llvm-objdump")
6403 << "can't obtain an xar iterator for xar archive " << XarFilename
6404 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006405 return;
6406 }
6407
6408 // Go through the xar's files.
6409 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006410 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006411 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006412 WithColor::error(errs(), "llvm-objdump")
6413 << "can't obtain an xar iterator for xar archive " << XarFilename
6414 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006415 return;
6416 }
6417 type = nullptr;
6418 mode = nullptr;
6419 user = nullptr;
6420 group = nullptr;
6421 size = nullptr;
6422 mtime = nullptr;
6423 name = nullptr;
6424 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006425 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006426 xar_prop_get(xf, key, &val);
6427#if 0 // Useful for debugging.
6428 outs() << "key: " << key << " value: " << val << "\n";
6429#endif
6430 if(strcmp(key, "type") == 0)
6431 type = val;
6432 if(strcmp(key, "mode") == 0)
6433 mode = val;
6434 if(strcmp(key, "user") == 0)
6435 user = val;
6436 if(strcmp(key, "group") == 0)
6437 group = val;
6438 if(strcmp(key, "data/size") == 0)
6439 size = val;
6440 if(strcmp(key, "mtime") == 0)
6441 mtime = val;
6442 if(strcmp(key, "name") == 0)
6443 name = val;
6444 }
6445 if(mode != nullptr){
6446 mode_value = strtoul(mode, &endp, 8);
6447 if(*endp != '\0')
6448 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6449 if(strcmp(type, "file") == 0)
6450 mode_value |= S_IFREG;
6451 PrintModeVerbose(mode_value);
6452 outs() << " ";
6453 }
6454 if(user != nullptr)
6455 outs() << format("%10s/", user);
6456 if(group != nullptr)
6457 outs() << format("%-10s ", group);
6458 if(size != nullptr)
6459 outs() << format("%7s ", size);
6460 if(mtime != nullptr){
6461 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6462 outs() << *m;
6463 if(*m == 'T')
6464 m++;
6465 outs() << " ";
6466 for( ; *m != 'Z' && *m != '\0'; m++)
6467 outs() << *m;
6468 outs() << " ";
6469 }
6470 if(name != nullptr)
6471 outs() << name;
6472 outs() << "\n";
6473 }
6474}
6475
6476static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6477 uint32_t size, bool verbose,
6478 bool PrintXarHeader, bool PrintXarFileHeaders,
6479 std::string XarMemberName) {
6480 if(size < sizeof(struct xar_header)) {
6481 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6482 "of struct xar_header)\n";
6483 return;
6484 }
6485 struct xar_header XarHeader;
6486 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6487 if (sys::IsLittleEndianHost)
6488 swapStruct(XarHeader);
6489 if (PrintXarHeader) {
6490 if (!XarMemberName.empty())
6491 outs() << "In xar member " << XarMemberName << ": ";
6492 else
6493 outs() << "For (__LLVM,__bundle) section: ";
6494 outs() << "xar header\n";
6495 if (XarHeader.magic == XAR_HEADER_MAGIC)
6496 outs() << " magic XAR_HEADER_MAGIC\n";
6497 else
6498 outs() << " magic "
6499 << format_hex(XarHeader.magic, 10, true)
6500 << " (not XAR_HEADER_MAGIC)\n";
6501 outs() << " size " << XarHeader.size << "\n";
6502 outs() << " version " << XarHeader.version << "\n";
6503 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6504 << "\n";
6505 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6506 << "\n";
6507 outs() << " cksum_alg ";
6508 switch (XarHeader.cksum_alg) {
6509 case XAR_CKSUM_NONE:
6510 outs() << "XAR_CKSUM_NONE\n";
6511 break;
6512 case XAR_CKSUM_SHA1:
6513 outs() << "XAR_CKSUM_SHA1\n";
6514 break;
6515 case XAR_CKSUM_MD5:
6516 outs() << "XAR_CKSUM_MD5\n";
6517 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006518#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006519 case XAR_CKSUM_SHA256:
6520 outs() << "XAR_CKSUM_SHA256\n";
6521 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006522#endif
6523#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006524 case XAR_CKSUM_SHA512:
6525 outs() << "XAR_CKSUM_SHA512\n";
6526 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006527#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006528 default:
6529 outs() << XarHeader.cksum_alg << "\n";
6530 }
6531 }
6532
6533 SmallString<128> XarFilename;
6534 int FD;
6535 std::error_code XarEC =
6536 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6537 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006538 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006539 return;
6540 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006541 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006542 raw_fd_ostream &XarOut = XarFile.os();
6543 StringRef XarContents(sect, size);
6544 XarOut << XarContents;
6545 XarOut.close();
6546 if (XarOut.has_error())
6547 return;
6548
Francis Ricci6f942972017-10-06 15:33:28 +00006549 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006550 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006551 WithColor::error(errs(), "llvm-objdump")
6552 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006553 return;
6554 }
6555
6556 SmallString<128> TocFilename;
6557 std::error_code TocEC =
6558 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6559 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006560 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006561 return;
6562 }
6563 xar_serialize(xar, TocFilename.c_str());
6564
6565 if (PrintXarFileHeaders) {
6566 if (!XarMemberName.empty())
6567 outs() << "In xar member " << XarMemberName << ": ";
6568 else
6569 outs() << "For (__LLVM,__bundle) section: ";
6570 outs() << "xar archive files:\n";
6571 PrintXarFilesSummary(XarFilename.c_str(), xar);
6572 }
6573
6574 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6575 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6576 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006577 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006578 return;
6579 }
6580 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6581
6582 if (!XarMemberName.empty())
6583 outs() << "In xar member " << XarMemberName << ": ";
6584 else
6585 outs() << "For (__LLVM,__bundle) section: ";
6586 outs() << "xar table of contents:\n";
6587 outs() << Buffer->getBuffer() << "\n";
6588
6589 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006590 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006591 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006592 WithColor::error(errs(), "llvm-objdump")
6593 << "can't obtain an xar iterator for xar archive "
6594 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006595 return;
6596 }
6597 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6598 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006599 const char *member_name, *member_type, *member_size_string;
6600 size_t member_size;
6601
Francis Ricci6f942972017-10-06 15:33:28 +00006602 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006603 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006604 WithColor::error(errs(), "llvm-objdump")
6605 << "can't obtain an xar iterator for xar archive "
6606 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006607 return;
6608 }
6609 member_name = NULL;
6610 member_type = NULL;
6611 member_size_string = NULL;
6612 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006613 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006614 xar_prop_get(xf, key, &val);
6615#if 0 // Useful for debugging.
6616 outs() << "key: " << key << " value: " << val << "\n";
6617#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006618 if (strcmp(key, "name") == 0)
6619 member_name = val;
6620 if (strcmp(key, "type") == 0)
6621 member_type = val;
6622 if (strcmp(key, "data/size") == 0)
6623 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006624 }
6625 /*
6626 * If we find a file with a name, date/size and type properties
6627 * and with the type being "file" see if that is a xar file.
6628 */
6629 if (member_name != NULL && member_type != NULL &&
6630 strcmp(member_type, "file") == 0 &&
6631 member_size_string != NULL){
6632 // Extract the file into a buffer.
6633 char *endptr;
6634 member_size = strtoul(member_size_string, &endptr, 10);
6635 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006636 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006637 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006638#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006639 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006640#endif
6641 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006642 std::string OldXarMemberName;
6643 // If XarMemberName is already set this is nested. So
6644 // save the old name and create the nested name.
6645 if (!XarMemberName.empty()) {
6646 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006647 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006648 (Twine("[") + XarMemberName + "]" + member_name).str();
6649 } else {
6650 OldXarMemberName = "";
6651 XarMemberName = member_name;
6652 }
6653 // See if this is could be a xar file (nested).
6654 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006655#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006656 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006657#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006658 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006659 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006660 swapStruct(XarHeader);
6661 if (XarHeader.magic == XAR_HEADER_MAGIC)
6662 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006663 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006664 XarMemberName);
6665 }
6666 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006667 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006668 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006669 }
6670 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006671 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006672}
6673#endif // defined(HAVE_LIBXAR)
6674
Kevin Enderby0fc11822015-04-01 20:57:01 +00006675static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6676 if (O->is64Bit())
6677 printObjc2_64bit_MetaData(O, verbose);
6678 else {
6679 MachO::mach_header H;
6680 H = O->getHeader();
6681 if (H.cputype == MachO::CPU_TYPE_ARM)
6682 printObjc2_32bit_MetaData(O, verbose);
6683 else {
6684 // This is the 32-bit non-arm cputype case. Which is normally
6685 // the first Objective-C ABI. But it may be the case of a
6686 // binary for the iOS simulator which is the second Objective-C
6687 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6688 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006689 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006690 printObjc2_32bit_MetaData(O, verbose);
6691 }
6692 }
6693}
6694
Kevin Enderbybf246f52014-09-24 23:08:22 +00006695// GuessLiteralPointer returns a string which for the item in the Mach-O file
6696// for the address passed in as ReferenceValue for printing as a comment with
6697// the instruction and also returns the corresponding type of that item
6698// indirectly through ReferenceType.
6699//
6700// If ReferenceValue is an address of literal cstring then a pointer to the
6701// cstring is returned and ReferenceType is set to
6702// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6703//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006704// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6705// Class ref that name is returned and the ReferenceType is set accordingly.
6706//
6707// Lastly, literals which are Symbol address in a literal pool are looked for
6708// and if found the symbol name is returned and ReferenceType is set to
6709// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6710//
6711// If there is no item in the Mach-O file for the address passed in as
6712// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006713static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6714 uint64_t ReferencePC,
6715 uint64_t *ReferenceType,
6716 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006717 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006718 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6719 uint64_t sect_addr = info->S.getAddress();
6720 uint64_t sect_offset = ReferencePC - sect_addr;
6721 bool reloc_found = false;
6722 DataRefImpl Rel;
6723 MachO::any_relocation_info RE;
6724 bool isExtern = false;
6725 SymbolRef Symbol;
6726 for (const RelocationRef &Reloc : info->S.relocations()) {
6727 uint64_t RelocOffset = Reloc.getOffset();
6728 if (RelocOffset == sect_offset) {
6729 Rel = Reloc.getRawDataRefImpl();
6730 RE = info->O->getRelocation(Rel);
6731 if (info->O->isRelocationScattered(RE))
6732 continue;
6733 isExtern = info->O->getPlainRelocationExternal(RE);
6734 if (isExtern) {
6735 symbol_iterator RelocSym = Reloc.getSymbol();
6736 Symbol = *RelocSym;
6737 }
6738 reloc_found = true;
6739 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006740 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006741 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006742 // If there is an external relocation entry for a symbol in a section
6743 // then used that symbol's value for the value of the reference.
6744 if (reloc_found && isExtern) {
6745 if (info->O->getAnyRelocationPCRel(RE)) {
6746 unsigned Type = info->O->getAnyRelocationType(RE);
6747 if (Type == MachO::X86_64_RELOC_SIGNED) {
6748 ReferenceValue = Symbol.getValue();
6749 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006750 }
6751 }
6752 }
6753
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006754 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6755 // Message refs and Class refs.
6756 bool classref, selref, msgref, cfstring;
6757 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6758 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006759 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006760 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6761 // And the pointer_value in that section is typically zero as it will be
6762 // set by dyld as part of the "bind information".
6763 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6764 if (name != nullptr) {
6765 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006766 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006767 if (class_name != nullptr && class_name[1] == '_' &&
6768 class_name[2] != '\0') {
6769 info->class_name = class_name + 2;
6770 return name;
6771 }
6772 }
6773 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006774
David Blaikie33dd45d02015-03-23 18:39:02 +00006775 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006776 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6777 const char *name =
6778 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6779 if (name != nullptr)
6780 info->class_name = name;
6781 else
6782 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006783 return name;
6784 }
6785
David Blaikie33dd45d02015-03-23 18:39:02 +00006786 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006787 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6788 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6789 return name;
6790 }
6791
David Blaikie33dd45d02015-03-23 18:39:02 +00006792 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006793 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6794
6795 if (pointer_value != 0)
6796 ReferenceValue = pointer_value;
6797
6798 const char *name = GuessCstringPointer(ReferenceValue, info);
6799 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006800 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006801 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6802 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006803 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006804 info->class_name = nullptr;
6805 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6806 info->selector_name = name;
6807 } else
6808 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6809 return name;
6810 }
6811
6812 // Lastly look for an indirect symbol with this ReferenceValue which is in
6813 // a literal pool. If found return that symbol name.
6814 name = GuessIndirectSymbol(ReferenceValue, info);
6815 if (name) {
6816 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6817 return name;
6818 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006819
6820 return nullptr;
6821}
6822
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006823// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006824// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006825// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6826// is created and returns the symbol name that matches the ReferenceValue or
6827// nullptr if none. The ReferenceType is passed in for the IN type of
6828// reference the instruction is making from the values in defined in the header
6829// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6830// Out type and the ReferenceName will also be set which is added as a comment
6831// to the disassembled instruction.
6832//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006833// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006834// returned through ReferenceName and ReferenceType is set to
6835// LLVMDisassembler_ReferenceType_DeMangled_Name .
6836//
6837// When this is called to get a symbol name for a branch target then the
6838// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6839// SymbolValue will be looked for in the indirect symbol table to determine if
6840// it is an address for a symbol stub. If so then the symbol name for that
6841// stub is returned indirectly through ReferenceName and then ReferenceType is
6842// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6843//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006844// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006845// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6846// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6847// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006848// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006849static const char *SymbolizerSymbolLookUp(void *DisInfo,
6850 uint64_t ReferenceValue,
6851 uint64_t *ReferenceType,
6852 uint64_t ReferencePC,
6853 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006854 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006855 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006856 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006857 *ReferenceName = nullptr;
6858 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006859 return nullptr;
6860 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006861
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006862 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006863
Kevin Enderby85974882014-09-26 22:20:44 +00006864 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6865 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006866 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006867 method_reference(info, ReferenceType, ReferenceName);
6868 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6869 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006870 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006871 if (info->demangled_name != nullptr)
6872 free(info->demangled_name);
6873 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006874 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006875 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006876 if (info->demangled_name != nullptr) {
6877 *ReferenceName = info->demangled_name;
6878 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6879 } else
6880 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6881 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006882 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6883 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6884 *ReferenceName =
6885 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006886 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006887 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006888 else
6889 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006890 // If this is arm64 and the reference is an adrp instruction save the
6891 // instruction, passed in ReferenceValue and the address of the instruction
6892 // for use later if we see and add immediate instruction.
6893 } else if (info->O->getArch() == Triple::aarch64 &&
6894 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6895 info->adrp_inst = ReferenceValue;
6896 info->adrp_addr = ReferencePC;
6897 SymbolName = nullptr;
6898 *ReferenceName = nullptr;
6899 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6900 // If this is arm64 and reference is an add immediate instruction and we
6901 // have
6902 // seen an adrp instruction just before it and the adrp's Xd register
6903 // matches
6904 // this add's Xn register reconstruct the value being referenced and look to
6905 // see if it is a literal pointer. Note the add immediate instruction is
6906 // passed in ReferenceValue.
6907 } else if (info->O->getArch() == Triple::aarch64 &&
6908 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6909 ReferencePC - 4 == info->adrp_addr &&
6910 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6911 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6912 uint32_t addxri_inst;
6913 uint64_t adrp_imm, addxri_imm;
6914
6915 adrp_imm =
6916 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6917 if (info->adrp_inst & 0x0200000)
6918 adrp_imm |= 0xfffffffffc000000LL;
6919
6920 addxri_inst = ReferenceValue;
6921 addxri_imm = (addxri_inst >> 10) & 0xfff;
6922 if (((addxri_inst >> 22) & 0x3) == 1)
6923 addxri_imm <<= 12;
6924
6925 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6926 (adrp_imm << 12) + addxri_imm;
6927
6928 *ReferenceName =
6929 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6930 if (*ReferenceName == nullptr)
6931 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6932 // If this is arm64 and the reference is a load register instruction and we
6933 // have seen an adrp instruction just before it and the adrp's Xd register
6934 // matches this add's Xn register reconstruct the value being referenced and
6935 // look to see if it is a literal pointer. Note the load register
6936 // instruction is passed in ReferenceValue.
6937 } else if (info->O->getArch() == Triple::aarch64 &&
6938 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6939 ReferencePC - 4 == info->adrp_addr &&
6940 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6941 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6942 uint32_t ldrxui_inst;
6943 uint64_t adrp_imm, ldrxui_imm;
6944
6945 adrp_imm =
6946 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6947 if (info->adrp_inst & 0x0200000)
6948 adrp_imm |= 0xfffffffffc000000LL;
6949
6950 ldrxui_inst = ReferenceValue;
6951 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6952
6953 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6954 (adrp_imm << 12) + (ldrxui_imm << 3);
6955
6956 *ReferenceName =
6957 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6958 if (*ReferenceName == nullptr)
6959 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6960 }
6961 // If this arm64 and is an load register (PC-relative) instruction the
6962 // ReferenceValue is the PC plus the immediate value.
6963 else if (info->O->getArch() == Triple::aarch64 &&
6964 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6965 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6966 *ReferenceName =
6967 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6968 if (*ReferenceName == nullptr)
6969 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006970 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006971 if (info->demangled_name != nullptr)
6972 free(info->demangled_name);
6973 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006974 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006975 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006976 if (info->demangled_name != nullptr) {
6977 *ReferenceName = info->demangled_name;
6978 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6979 }
6980 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006981 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006982 *ReferenceName = nullptr;
6983 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6984 }
6985
6986 return SymbolName;
6987}
6988
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006989/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006990/// Each comment in the CommentStream must end with a newline.
6991static void emitComments(raw_svector_ostream &CommentStream,
6992 SmallString<128> &CommentsToEmit,
6993 formatted_raw_ostream &FormattedOS,
6994 const MCAsmInfo &MAI) {
6995 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006996 StringRef Comments = CommentsToEmit.str();
6997 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006998 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006999 unsigned CommentColumn = MAI.getCommentColumn();
7000 bool IsFirst = true;
7001 while (!Comments.empty()) {
7002 if (!IsFirst)
7003 FormattedOS << '\n';
7004 // Emit a line of comments.
7005 FormattedOS.PadToColumn(CommentColumn);
7006 size_t Position = Comments.find('\n');
7007 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7008 // Move after the newline character.
7009 Comments = Comments.substr(Position + 1);
7010 IsFirst = false;
7011 }
7012 FormattedOS.flush();
7013
7014 // Tell the comment stream that the vector changed underneath it.
7015 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007016}
7017
Kevin Enderby95df54c2015-02-04 01:01:38 +00007018static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7019 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007020 const char *McpuDefault = nullptr;
7021 const Target *ThumbTarget = nullptr;
7022 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007023 if (!TheTarget) {
7024 // GetTarget prints out stuff.
7025 return;
7026 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00007027 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007028 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00007029 MachOMCPU = McpuDefault;
7030 else
7031 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007032
Ahmed Charles56440fd2014-03-06 05:51:42 +00007033 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007034 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007035 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007036 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007037
Kevin Enderbyc9595622014-08-06 23:24:41 +00007038 // Package up features to be passed to target/subtarget
7039 std::string FeaturesStr;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007040 if (!MAttrs.empty()) {
Kevin Enderbyc9595622014-08-06 23:24:41 +00007041 SubtargetFeatures Features;
7042 for (unsigned i = 0; i != MAttrs.size(); ++i)
7043 Features.AddFeature(MAttrs[i]);
7044 FeaturesStr = Features.getString();
7045 }
7046
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007047 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00007048 std::unique_ptr<const MCRegisterInfo> MRI(
7049 TheTarget->createMCRegInfo(TripleName));
7050 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00007051 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00007052 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007053 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00007054 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007055 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007056 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007057 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007058 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007059 std::unique_ptr<MCRelocationInfo> RelInfo(
7060 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7061 if (RelInfo) {
7062 Symbolizer.reset(TheTarget->createMCSymbolizer(
7063 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007064 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007065 DisAsm->setSymbolizer(std::move(Symbolizer));
7066 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007067 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00007068 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007069 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007070 // Set the display preference for hex vs. decimal immediates.
7071 IP->setPrintImmHex(PrintImmHex);
7072 // Comment stream and backing vector.
7073 SmallString<128> CommentsToEmit;
7074 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007075 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7076 // if it is done then arm64 comments for string literals don't get printed
7077 // and some constant get printed instead and not setting it causes intel
7078 // (32-bit and 64-bit) comments printed with different spacing before the
7079 // comment causing different diffs with the 'C' disassembler library API.
7080 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007081
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007082 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007083 WithColor::error(errs(), "llvm-objdump")
7084 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007085 return;
7086 }
7087
Tim Northover09ca33e2016-04-22 23:23:31 +00007088 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007089 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7090 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7091 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007092 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007093 std::unique_ptr<MCInstPrinter> ThumbIP;
7094 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007095 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007096 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007097 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007098 if (ThumbTarget) {
7099 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7100 ThumbAsmInfo.reset(
7101 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7102 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007103 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7104 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007105 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7106 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007107 MCContext *PtrThumbCtx = ThumbCtx.get();
7108 ThumbRelInfo.reset(
7109 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7110 if (ThumbRelInfo) {
7111 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7112 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007113 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007114 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7115 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007116 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7117 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007118 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7119 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007120 // Set the display preference for hex vs. decimal immediates.
7121 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007122 }
7123
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007124 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007125 WithColor::error(errs(), "llvm-objdump")
7126 << "couldn't initialize disassembler for target " << ThumbTripleName
7127 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007128 return;
7129 }
7130
Charles Davis8bdfafd2013-09-01 04:28:48 +00007131 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007132
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007133 // FIXME: Using the -cfg command line option, this code used to be able to
7134 // annotate relocations with the referenced symbol's name, and if this was
7135 // inside a __[cf]string section, the data it points to. This is now replaced
7136 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00007137 std::vector<SectionRef> Sections;
7138 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007139 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00007140 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007141
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00007142 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00007143 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007144
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007145 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00007146 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007147
Kevin Enderby273ae012013-06-06 17:20:50 +00007148 // Build a data in code table that is sorted on by the address of each entry.
7149 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00007150 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00007151 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00007152 else
7153 BaseAddress = BaseSegmentAddress;
7154 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00007155 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00007156 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007157 uint32_t Offset;
7158 DI->getOffset(Offset);
7159 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7160 }
7161 array_pod_sort(Dices.begin(), Dices.end());
7162
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007163#ifndef NDEBUG
7164 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7165#else
7166 raw_ostream &DebugOut = nulls();
7167#endif
7168
Ahmed Charles56440fd2014-03-06 05:51:42 +00007169 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00007170 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007171 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00007172 // Try to find debug info and set up the DIContext for it.
7173 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00007174 // A separate DSym file path was specified, parse it as a macho file,
7175 // get the sections and supply it to the section name parsing machinery.
7176 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00007177 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00007178 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00007179 if (std::error_code EC = BufOrErr.getError()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007180 report_error(errorCodeToError(EC), DSYMFile);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007181 return;
7182 }
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007183
Fangrui Songe7834bd2019-04-07 08:19:55 +00007184 std::unique_ptr<MachOObjectFile> DbgObjCheck = unwrapOrError(
7185 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef()),
7186 DSYMFile.getValue());
7187 DbgObj = DbgObjCheck.release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007188 // We need to keep the file alive, because we're replacing DbgObj with it.
7189 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00007190 }
7191
Eric Christopher7370b552012-11-12 21:40:38 +00007192 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00007193 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007194 }
7195
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007196 if (FilterSections.empty())
Kevin Enderby95df54c2015-02-04 01:01:38 +00007197 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007198
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007199 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00007200 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00007201 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7202 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007203
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007204 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007205
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007206 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007207 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007208 continue;
7209
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007210 StringRef BytesStr;
7211 Sections[SectIdx].getContents(BytesStr);
Fangrui Song6a0746a2019-04-07 03:58:42 +00007212 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
Rafael Espindola80291272014-10-08 15:28:58 +00007213 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007214
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007215 bool symbolTableWorked = false;
7216
Kevin Enderbybf246f52014-09-24 23:08:22 +00007217 // Create a map of symbol addresses to symbol names for use by
7218 // the SymbolizerSymbolLookUp() routine.
7219 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007220 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007221 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007222 SymbolRef::Type ST =
7223 unwrapOrError(Symbol.getType(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007224 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7225 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007226 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00007227 StringRef SymName =
7228 unwrapOrError(Symbol.getName(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007229 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007230 if (!DisSymName.empty() && DisSymName == SymName)
7231 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007232 }
7233 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007234 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007235 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7236 return;
7237 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007238 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007239 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007240 SymbolizerInfo.O = MachOOF;
7241 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007242 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007243 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007244 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007245 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007246 ThumbSymbolizerInfo.O = MachOOF;
7247 ThumbSymbolizerInfo.S = Sections[SectIdx];
7248 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7249 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007250
Kevin Enderby4b627be2016-04-28 20:14:13 +00007251 unsigned int Arch = MachOOF->getArch();
7252
Tim Northoverf203ab52016-07-14 22:13:32 +00007253 // Skip all symbols if this is a stubs file.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007254 if (Bytes.empty())
Tim Northoverf203ab52016-07-14 22:13:32 +00007255 return;
7256
Kevin Enderbyc138da32017-02-06 18:43:18 +00007257 // If the section has symbols but no symbol at the start of the section
7258 // these are used to make sure the bytes before the first symbol are
7259 // disassembled.
7260 bool FirstSymbol = true;
7261 bool FirstSymbolAtSectionStart = true;
7262
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007263 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007264 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007265 StringRef SymName =
7266 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7267 SymbolRef::Type ST =
7268 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
Kuba Breckade833222015-11-12 09:40:29 +00007269 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007270 continue;
7271
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007272 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007273 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007274 if (!containsSym) {
7275 if (!DisSymName.empty() && DisSymName == SymName) {
7276 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7277 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007278 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007279 continue;
7280 }
7281 // The __mh_execute_header is special and we need to deal with that fact
7282 // this symbol is before the start of the (__TEXT,__text) section and at the
7283 // address of the start of the __TEXT segment. This is because this symbol
7284 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7285 // start of the section in a standard MH_EXECUTE filetype.
7286 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7287 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7288 return;
7289 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007290 // When this code is trying to disassemble a symbol at a time and in the
7291 // case there is only the __mh_execute_header symbol left as in a stripped
7292 // executable, we need to deal with this by ignoring this symbol so the
7293 // whole section is disassembled and this symbol is then not displayed.
7294 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7295 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7296 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007297 continue;
7298
Kevin Enderby6a221752015-03-17 17:10:57 +00007299 // If we are only disassembling one symbol see if this is that symbol.
7300 if (!DisSymName.empty() && DisSymName != SymName)
7301 continue;
7302
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007303 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007304 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007305 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007306 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007307 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007308
Tim Northoverf203ab52016-07-14 22:13:32 +00007309 if (Start > SectSize) {
7310 outs() << "section data ends, " << SymName
7311 << " lies outside valid range\n";
7312 return;
7313 }
7314
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007315 // Stop disassembling either at the beginning of the next symbol or at
7316 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007317 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007318 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007319 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007320 while (Symbols.size() > NextSymIdx) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007321 SymbolRef::Type NextSymType = unwrapOrError(
7322 Symbols[NextSymIdx].getType(), MachOOF->getFileName());
Owen Andersond9243c42011-10-17 21:37:35 +00007323 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007324 containsNextSym =
7325 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007326 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007327 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007328 break;
7329 }
7330 ++NextSymIdx;
7331 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007332
Tim Northoverf203ab52016-07-14 22:13:32 +00007333 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007334 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007335
7336 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007337
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007338 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007339 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7340
7341 // We only need the dedicated Thumb target if there's a real choice
7342 // (i.e. we're not targeting M-class) and the function is Thumb.
7343 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007344
Kevin Enderbyc138da32017-02-06 18:43:18 +00007345 // If we are not specifying a symbol to start disassembly with and this
7346 // is the first symbol in the section but not at the start of the section
7347 // then move the disassembly index to the start of the section and
7348 // don't print the symbol name just yet. This is so the bytes before the
7349 // first symbol are disassembled.
7350 uint64_t SymbolStart = Start;
7351 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7352 FirstSymbolAtSectionStart = false;
7353 Start = 0;
7354 }
7355 else
7356 outs() << SymName << ":\n";
7357
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007358 DILineInfo lastLine;
7359 for (uint64_t Index = Start; Index < End; Index += Size) {
7360 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007361
Kevin Enderbyc138da32017-02-06 18:43:18 +00007362 // If this is the first symbol in the section and it was not at the
7363 // start of the section, see if we are at its Index now and if so print
7364 // the symbol name.
7365 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7366 outs() << SymName << ":\n";
7367
Kevin Enderbybf246f52014-09-24 23:08:22 +00007368 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007369 if (!NoLeadingAddr) {
7370 if (FullLeadingAddr) {
7371 if (MachOOF->is64Bit())
7372 outs() << format("%016" PRIx64, PC);
7373 else
7374 outs() << format("%08" PRIx64, PC);
7375 } else {
7376 outs() << format("%8" PRIx64 ":", PC);
7377 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007378 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007379 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007380 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007381
7382 // Check the data in code table here to see if this is data not an
7383 // instruction to be disassembled.
7384 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007385 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007386 dice_table_iterator DTI =
7387 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7388 compareDiceTableEntries);
7389 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007390 uint16_t Length;
7391 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007392 uint16_t Kind;
7393 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007394 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007395 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7396 (PC == (DTI->first + Length - 1)) && (Length & 1))
7397 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007398 continue;
7399 }
7400
Kevin Enderbybf246f52014-09-24 23:08:22 +00007401 SmallVector<char, 64> AnnotationsBytes;
7402 raw_svector_ostream Annotations(AnnotationsBytes);
7403
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007404 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007405 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007406 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007407 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007408 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007409 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007410 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007411 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007412 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007413 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007414 }
7415 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007416 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007417 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007418 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007419 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007420 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007421 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007422
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007423 // Print debug info.
7424 if (diContext) {
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00007425 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007426 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007427 if (dli != lastLine && dli.Line != 0)
7428 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7429 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007430 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007431 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007432 outs() << "\n";
7433 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007434 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007435 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007436 outs() << format("\t.byte 0x%02x #bad opcode\n",
7437 *(Bytes.data() + Index) & 0xff);
7438 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007439 } else if (Arch == Triple::aarch64 ||
7440 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007441 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7442 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7443 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7444 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7445 outs() << format("\t.long\t0x%08x\n", opcode);
7446 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007447 } else if (Arch == Triple::arm) {
7448 assert(IsThumb && "ARM mode should have been dealt with above");
7449 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7450 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7451 outs() << format("\t.short\t0x%04x\n", opcode);
7452 Size = 2;
7453 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007454 WithColor::warning(errs(), "llvm-objdump")
7455 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007456 if (Size == 0)
7457 Size = 1; // skip illegible bytes
7458 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007459 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007460 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007461 // Now that we are done disassembled the first symbol set the bool that
7462 // were doing this to false.
7463 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007464 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007465 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007466 // Reading the symbol table didn't work, disassemble the whole section.
7467 uint64_t SectAddress = Sections[SectIdx].getAddress();
7468 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007469 uint64_t InstSize;
7470 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007471 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007472
Kevin Enderbybf246f52014-09-24 23:08:22 +00007473 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007474 SmallVector<char, 64> AnnotationsBytes;
7475 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007476 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007477 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007478 if (!NoLeadingAddr) {
7479 if (FullLeadingAddr) {
7480 if (MachOOF->is64Bit())
7481 outs() << format("%016" PRIx64, PC);
7482 else
7483 outs() << format("%08" PRIx64, PC);
7484 } else {
7485 outs() << format("%8" PRIx64 ":", PC);
7486 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007487 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007488 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007489 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007490 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007491 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007492 StringRef AnnotationsStr = Annotations.str();
7493 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007494 outs() << "\n";
7495 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007496 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007497 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007498 outs() << format("\t.byte 0x%02x #bad opcode\n",
7499 *(Bytes.data() + Index) & 0xff);
7500 InstSize = 1; // skip exactly one illegible byte and move on.
7501 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007502 WithColor::warning(errs(), "llvm-objdump")
7503 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007504 if (InstSize == 0)
7505 InstSize = 1; // skip illegible bytes
7506 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007507 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007508 }
7509 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007510 // The TripleName's need to be reset if we are called again for a different
7511 // archtecture.
7512 TripleName = "";
7513 ThumbTripleName = "";
7514
Kevin Enderby04bf6932014-10-28 23:39:46 +00007515 if (SymbolizerInfo.demangled_name != nullptr)
7516 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007517 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7518 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007519 }
7520}
Tim Northover4bd286a2014-08-01 13:07:19 +00007521
Tim Northover39c70bb2014-08-12 11:52:59 +00007522//===----------------------------------------------------------------------===//
7523// __compact_unwind section dumping
7524//===----------------------------------------------------------------------===//
7525
Tim Northover4bd286a2014-08-01 13:07:19 +00007526namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007527
Tim Northover3a4e1c72018-01-23 13:51:57 +00007528template <typename T>
7529static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007530 using llvm::support::little;
7531 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007532
Tim Northover3a4e1c72018-01-23 13:51:57 +00007533 if (Offset + sizeof(T) > Contents.size()) {
7534 outs() << "warning: attempt to read past end of buffer\n";
7535 return T();
7536 }
7537
7538 uint64_t Val =
7539 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7540 return Val;
7541}
7542
7543template <typename T>
7544static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7545 T Val = read<T>(Contents, Offset);
7546 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007547 return Val;
7548}
Tim Northover39c70bb2014-08-12 11:52:59 +00007549
Tim Northover4bd286a2014-08-01 13:07:19 +00007550struct CompactUnwindEntry {
7551 uint32_t OffsetInSection;
7552
7553 uint64_t FunctionAddr;
7554 uint32_t Length;
7555 uint32_t CompactEncoding;
7556 uint64_t PersonalityAddr;
7557 uint64_t LSDAAddr;
7558
7559 RelocationRef FunctionReloc;
7560 RelocationRef PersonalityReloc;
7561 RelocationRef LSDAReloc;
7562
7563 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007564 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007565 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007566 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007567 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007568 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007569 }
7570
7571private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007572 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7573 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7574 Length = readNext<uint32_t>(Contents, Offset);
7575 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7576 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7577 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007578 }
7579};
7580}
7581
7582/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7583/// and data being relocated, determine the best base Name and Addend to use for
7584/// display purposes.
7585///
7586/// 1. An Extern relocation will directly reference a symbol (and the data is
7587/// then already an addend), so use that.
7588/// 2. Otherwise the data is an offset in the object file's layout; try to find
7589// a symbol before it in the same section, and use the offset from there.
7590/// 3. Finally, if all that fails, fall back to an offset from the start of the
7591/// referenced section.
7592static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7593 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007594 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007595 StringRef &Name, uint64_t &Addend) {
7596 if (Reloc.getSymbol() != Obj->symbol_end()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007597 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007598 Addend = Addr;
7599 return;
7600 }
7601
7602 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007603 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007604
Rafael Espindola80291272014-10-08 15:28:58 +00007605 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007606
7607 auto Sym = Symbols.upper_bound(Addr);
7608 if (Sym == Symbols.begin()) {
7609 // The first symbol in the object is after this reference, the best we can
7610 // do is section-relative notation.
7611 RelocSection.getName(Name);
7612 Addend = Addr - SectionAddr;
7613 return;
7614 }
7615
7616 // Go back one so that SymbolAddress <= Addr.
7617 --Sym;
7618
Fangrui Songe7834bd2019-04-07 08:19:55 +00007619 section_iterator SymSection =
7620 unwrapOrError(Sym->second.getSection(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007621 if (RelocSection == *SymSection) {
7622 // There's a valid symbol in the same section before this reference.
Fangrui Songe7834bd2019-04-07 08:19:55 +00007623 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007624 Addend = Addr - Sym->first;
7625 return;
7626 }
7627
7628 // There is a symbol before this reference, but it's in a different
7629 // section. Probably not helpful to mention it, so use the section name.
7630 RelocSection.getName(Name);
7631 Addend = Addr - SectionAddr;
7632}
7633
7634static void printUnwindRelocDest(const MachOObjectFile *Obj,
7635 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007636 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007637 StringRef Name;
7638 uint64_t Addend;
7639
Rafael Espindola854038e2015-06-26 14:51:16 +00007640 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007641 return;
7642
Tim Northover4bd286a2014-08-01 13:07:19 +00007643 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7644
7645 outs() << Name;
7646 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007647 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007648}
7649
7650static void
7651printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7652 std::map<uint64_t, SymbolRef> &Symbols,
7653 const SectionRef &CompactUnwind) {
7654
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007655 if (!Obj->isLittleEndian()) {
7656 outs() << "Skipping big-endian __compact_unwind section\n";
7657 return;
7658 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007659
7660 bool Is64 = Obj->is64Bit();
7661 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7662 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7663
7664 StringRef Contents;
7665 CompactUnwind.getContents(Contents);
7666
7667 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7668
7669 // First populate the initial raw offsets, encodings and so on from the entry.
7670 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007671 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007672 CompactUnwinds.push_back(Entry);
7673 }
7674
7675 // Next we need to look at the relocations to find out what objects are
7676 // actually being referred to.
7677 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007678 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007679
7680 uint32_t EntryIdx = RelocAddress / EntrySize;
7681 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7682 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7683
7684 if (OffsetInEntry == 0)
7685 Entry.FunctionReloc = Reloc;
7686 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7687 Entry.PersonalityReloc = Reloc;
7688 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7689 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007690 else {
7691 outs() << "Invalid relocation in __compact_unwind section\n";
7692 return;
7693 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007694 }
7695
7696 // Finally, we're ready to print the data we've gathered.
7697 outs() << "Contents of __compact_unwind section:\n";
7698 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007699 outs() << " Entry at offset "
7700 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007701
7702 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007703 outs() << " start: " << format("0x%" PRIx64,
7704 Entry.FunctionAddr) << ' ';
7705 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007706 outs() << '\n';
7707
7708 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007709 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7710 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007711 // 3. The 32-bit compact encoding.
7712 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007713 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007714
7715 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007716 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007717 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007718 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007719 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7720 Entry.PersonalityAddr);
7721 outs() << '\n';
7722 }
7723
7724 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007725 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007726 outs() << " LSDA: " << format("0x%" PRIx64,
7727 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007728 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7729 outs() << '\n';
7730 }
7731 }
7732}
7733
Tim Northover39c70bb2014-08-12 11:52:59 +00007734//===----------------------------------------------------------------------===//
7735// __unwind_info section dumping
7736//===----------------------------------------------------------------------===//
7737
Tim Northover3a4e1c72018-01-23 13:51:57 +00007738static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7739 ptrdiff_t Pos = 0;
7740 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007741 (void)Kind;
7742 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7743
Tim Northover3a4e1c72018-01-23 13:51:57 +00007744 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7745 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007746
Tim Northover3a4e1c72018-01-23 13:51:57 +00007747 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007748 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007749 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7750 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007751
7752 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007753 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7754 << ", "
7755 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007756 }
7757}
7758
7759static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007760 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007761 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007762 ptrdiff_t Pos = 0;
7763 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007764 (void)Kind;
7765 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7766
Tim Northover3a4e1c72018-01-23 13:51:57 +00007767 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7768 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007769
Tim Northover3a4e1c72018-01-23 13:51:57 +00007770 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7771 readNext<uint16_t>(PageData, Pos);
7772 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007773
Tim Northover3a4e1c72018-01-23 13:51:57 +00007774 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007775 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007776 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007777 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7778 uint32_t EncodingIdx = Entry >> 24;
7779
7780 uint32_t Encoding;
7781 if (EncodingIdx < CommonEncodings.size())
7782 Encoding = CommonEncodings[EncodingIdx];
7783 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007784 Encoding = read<uint32_t>(PageEncodings,
7785 sizeof(uint32_t) *
7786 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007787
7788 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007789 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7790 << ", "
7791 << "encoding[" << EncodingIdx
7792 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007793 }
7794}
7795
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007796static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7797 std::map<uint64_t, SymbolRef> &Symbols,
7798 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007799
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007800 if (!Obj->isLittleEndian()) {
7801 outs() << "Skipping big-endian __unwind_info section\n";
7802 return;
7803 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007804
7805 outs() << "Contents of __unwind_info section:\n";
7806
7807 StringRef Contents;
7808 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007809 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007810
7811 //===----------------------------------
7812 // Section header
7813 //===----------------------------------
7814
Tim Northover3a4e1c72018-01-23 13:51:57 +00007815 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007816 outs() << " Version: "
7817 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007818 if (Version != 1) {
7819 outs() << " Skipping section with unknown version\n";
7820 return;
7821 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007822
Tim Northover3a4e1c72018-01-23 13:51:57 +00007823 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007824 outs() << " Common encodings array section offset: "
7825 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007826 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007827 outs() << " Number of common encodings in array: "
7828 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7829
Tim Northover3a4e1c72018-01-23 13:51:57 +00007830 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007831 outs() << " Personality function array section offset: "
7832 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007833 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007834 outs() << " Number of personality functions in array: "
7835 << format("0x%" PRIx32, NumPersonalities) << '\n';
7836
Tim Northover3a4e1c72018-01-23 13:51:57 +00007837 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007838 outs() << " Index array section offset: "
7839 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007840 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007841 outs() << " Number of indices in array: "
7842 << format("0x%" PRIx32, NumIndices) << '\n';
7843
7844 //===----------------------------------
7845 // A shared list of common encodings
7846 //===----------------------------------
7847
7848 // These occupy indices in the range [0, N] whenever an encoding is referenced
7849 // from a compressed 2nd level index table. In practice the linker only
7850 // creates ~128 of these, so that indices are available to embed encodings in
7851 // the 2nd level index.
7852
7853 SmallVector<uint32_t, 64> CommonEncodings;
7854 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007855 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007856 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007857 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007858 CommonEncodings.push_back(Encoding);
7859
7860 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7861 << '\n';
7862 }
7863
Tim Northover39c70bb2014-08-12 11:52:59 +00007864 //===----------------------------------
7865 // Personality functions used in this executable
7866 //===----------------------------------
7867
7868 // There should be only a handful of these (one per source language,
7869 // roughly). Particularly since they only get 2 bits in the compact encoding.
7870
7871 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007872 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007873 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007874 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007875 outs() << " personality[" << i + 1
7876 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7877 }
7878
7879 //===----------------------------------
7880 // The level 1 index entries
7881 //===----------------------------------
7882
7883 // These specify an approximate place to start searching for the more detailed
7884 // information, sorted by PC.
7885
7886 struct IndexEntry {
7887 uint32_t FunctionOffset;
7888 uint32_t SecondLevelPageStart;
7889 uint32_t LSDAStart;
7890 };
7891
7892 SmallVector<IndexEntry, 4> IndexEntries;
7893
7894 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007895 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007896 for (unsigned i = 0; i < NumIndices; ++i) {
7897 IndexEntry Entry;
7898
Tim Northover3a4e1c72018-01-23 13:51:57 +00007899 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7900 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7901 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007902 IndexEntries.push_back(Entry);
7903
7904 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007905 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7906 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007907 << "2nd level page offset="
7908 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007909 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007910 }
7911
Tim Northover39c70bb2014-08-12 11:52:59 +00007912 //===----------------------------------
7913 // Next come the LSDA tables
7914 //===----------------------------------
7915
7916 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7917 // the first top-level index's LSDAOffset to the last (sentinel).
7918
7919 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007920 Pos = IndexEntries[0].LSDAStart;
7921 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7922 int NumLSDAs =
7923 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7924
Tim Northover39c70bb2014-08-12 11:52:59 +00007925 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007926 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7927 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007928 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007929 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7930 << ", "
7931 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007932 }
7933
7934 //===----------------------------------
7935 // Finally, the 2nd level indices
7936 //===----------------------------------
7937
7938 // Generally these are 4K in size, and have 2 possible forms:
7939 // + Regular stores up to 511 entries with disparate encodings
7940 // + Compressed stores up to 1021 entries if few enough compact encoding
7941 // values are used.
7942 outs() << " Second level indices:\n";
7943 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7944 // The final sentinel top-level index has no associated 2nd level page
7945 if (IndexEntries[i].SecondLevelPageStart == 0)
7946 break;
7947
7948 outs() << " Second level index[" << i << "]: "
7949 << "offset in section="
7950 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7951 << ", "
7952 << "base function offset="
7953 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7954
Tim Northover3a4e1c72018-01-23 13:51:57 +00007955 Pos = IndexEntries[i].SecondLevelPageStart;
7956 if (Pos + sizeof(uint32_t) > Contents.size()) {
7957 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7958 continue;
7959 }
7960
7961 uint32_t Kind =
7962 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007963 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007964 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007965 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007966 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7967 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007968 CommonEncodings);
7969 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007970 outs() << " Skipping 2nd level page with unknown kind " << Kind
7971 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007972 }
7973}
7974
Tim Northover4bd286a2014-08-01 13:07:19 +00007975void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7976 std::map<uint64_t, SymbolRef> Symbols;
7977 for (const SymbolRef &SymRef : Obj->symbols()) {
7978 // Discard any undefined or absolute symbols. They're not going to take part
7979 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007980 auto SectOrErr = SymRef.getSection();
7981 if (!SectOrErr) {
7982 // TODO: Actually report errors helpfully.
7983 consumeError(SectOrErr.takeError());
7984 continue;
7985 }
7986 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007987 if (Section == Obj->section_end())
7988 continue;
7989
Rafael Espindoladea00162015-07-03 17:44:18 +00007990 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007991 Symbols.insert(std::make_pair(Addr, SymRef));
7992 }
7993
7994 for (const SectionRef &Section : Obj->sections()) {
7995 StringRef SectName;
7996 Section.getName(SectName);
7997 if (SectName == "__compact_unwind")
7998 printMachOCompactUnwindSection(Obj, Symbols, Section);
7999 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00008000 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00008001 }
8002}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008003
8004static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8005 uint32_t cpusubtype, uint32_t filetype,
8006 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8007 bool verbose) {
8008 outs() << "Mach header\n";
8009 outs() << " magic cputype cpusubtype caps filetype ncmds "
8010 "sizeofcmds flags\n";
8011 if (verbose) {
8012 if (magic == MachO::MH_MAGIC)
8013 outs() << " MH_MAGIC";
8014 else if (magic == MachO::MH_MAGIC_64)
8015 outs() << "MH_MAGIC_64";
8016 else
8017 outs() << format(" 0x%08" PRIx32, magic);
8018 switch (cputype) {
8019 case MachO::CPU_TYPE_I386:
8020 outs() << " I386";
8021 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8022 case MachO::CPU_SUBTYPE_I386_ALL:
8023 outs() << " ALL";
8024 break;
8025 default:
8026 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8027 break;
8028 }
8029 break;
8030 case MachO::CPU_TYPE_X86_64:
8031 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00008032 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8033 case MachO::CPU_SUBTYPE_X86_64_ALL:
8034 outs() << " ALL";
8035 break;
8036 case MachO::CPU_SUBTYPE_X86_64_H:
8037 outs() << " Haswell";
8038 break;
8039 default:
8040 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8041 break;
8042 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008043 break;
8044 case MachO::CPU_TYPE_ARM:
8045 outs() << " ARM";
8046 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8047 case MachO::CPU_SUBTYPE_ARM_ALL:
8048 outs() << " ALL";
8049 break;
8050 case MachO::CPU_SUBTYPE_ARM_V4T:
8051 outs() << " V4T";
8052 break;
8053 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8054 outs() << " V5TEJ";
8055 break;
8056 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8057 outs() << " XSCALE";
8058 break;
8059 case MachO::CPU_SUBTYPE_ARM_V6:
8060 outs() << " V6";
8061 break;
8062 case MachO::CPU_SUBTYPE_ARM_V6M:
8063 outs() << " V6M";
8064 break;
8065 case MachO::CPU_SUBTYPE_ARM_V7:
8066 outs() << " V7";
8067 break;
8068 case MachO::CPU_SUBTYPE_ARM_V7EM:
8069 outs() << " V7EM";
8070 break;
8071 case MachO::CPU_SUBTYPE_ARM_V7K:
8072 outs() << " V7K";
8073 break;
8074 case MachO::CPU_SUBTYPE_ARM_V7M:
8075 outs() << " V7M";
8076 break;
8077 case MachO::CPU_SUBTYPE_ARM_V7S:
8078 outs() << " V7S";
8079 break;
8080 default:
8081 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8082 break;
8083 }
8084 break;
8085 case MachO::CPU_TYPE_ARM64:
8086 outs() << " ARM64";
8087 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8088 case MachO::CPU_SUBTYPE_ARM64_ALL:
8089 outs() << " ALL";
8090 break;
Shoaib Meenai867131a2019-04-08 21:37:08 +00008091 case MachO::CPU_SUBTYPE_ARM64E:
8092 outs() << " E";
8093 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008094 default:
8095 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8096 break;
8097 }
8098 break;
8099 case MachO::CPU_TYPE_POWERPC:
8100 outs() << " PPC";
8101 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8102 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8103 outs() << " ALL";
8104 break;
8105 default:
8106 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8107 break;
8108 }
8109 break;
8110 case MachO::CPU_TYPE_POWERPC64:
8111 outs() << " PPC64";
8112 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8113 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8114 outs() << " ALL";
8115 break;
8116 default:
8117 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8118 break;
8119 }
8120 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00008121 default:
8122 outs() << format(" %7d", cputype);
8123 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8124 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008125 }
8126 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008127 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008128 } else {
8129 outs() << format(" 0x%02" PRIx32,
8130 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8131 }
8132 switch (filetype) {
8133 case MachO::MH_OBJECT:
8134 outs() << " OBJECT";
8135 break;
8136 case MachO::MH_EXECUTE:
8137 outs() << " EXECUTE";
8138 break;
8139 case MachO::MH_FVMLIB:
8140 outs() << " FVMLIB";
8141 break;
8142 case MachO::MH_CORE:
8143 outs() << " CORE";
8144 break;
8145 case MachO::MH_PRELOAD:
8146 outs() << " PRELOAD";
8147 break;
8148 case MachO::MH_DYLIB:
8149 outs() << " DYLIB";
8150 break;
8151 case MachO::MH_DYLIB_STUB:
8152 outs() << " DYLIB_STUB";
8153 break;
8154 case MachO::MH_DYLINKER:
8155 outs() << " DYLINKER";
8156 break;
8157 case MachO::MH_BUNDLE:
8158 outs() << " BUNDLE";
8159 break;
8160 case MachO::MH_DSYM:
8161 outs() << " DSYM";
8162 break;
8163 case MachO::MH_KEXT_BUNDLE:
8164 outs() << " KEXTBUNDLE";
8165 break;
8166 default:
8167 outs() << format(" %10u", filetype);
8168 break;
8169 }
8170 outs() << format(" %5u", ncmds);
8171 outs() << format(" %10u", sizeofcmds);
8172 uint32_t f = flags;
8173 if (f & MachO::MH_NOUNDEFS) {
8174 outs() << " NOUNDEFS";
8175 f &= ~MachO::MH_NOUNDEFS;
8176 }
8177 if (f & MachO::MH_INCRLINK) {
8178 outs() << " INCRLINK";
8179 f &= ~MachO::MH_INCRLINK;
8180 }
8181 if (f & MachO::MH_DYLDLINK) {
8182 outs() << " DYLDLINK";
8183 f &= ~MachO::MH_DYLDLINK;
8184 }
8185 if (f & MachO::MH_BINDATLOAD) {
8186 outs() << " BINDATLOAD";
8187 f &= ~MachO::MH_BINDATLOAD;
8188 }
8189 if (f & MachO::MH_PREBOUND) {
8190 outs() << " PREBOUND";
8191 f &= ~MachO::MH_PREBOUND;
8192 }
8193 if (f & MachO::MH_SPLIT_SEGS) {
8194 outs() << " SPLIT_SEGS";
8195 f &= ~MachO::MH_SPLIT_SEGS;
8196 }
8197 if (f & MachO::MH_LAZY_INIT) {
8198 outs() << " LAZY_INIT";
8199 f &= ~MachO::MH_LAZY_INIT;
8200 }
8201 if (f & MachO::MH_TWOLEVEL) {
8202 outs() << " TWOLEVEL";
8203 f &= ~MachO::MH_TWOLEVEL;
8204 }
8205 if (f & MachO::MH_FORCE_FLAT) {
8206 outs() << " FORCE_FLAT";
8207 f &= ~MachO::MH_FORCE_FLAT;
8208 }
8209 if (f & MachO::MH_NOMULTIDEFS) {
8210 outs() << " NOMULTIDEFS";
8211 f &= ~MachO::MH_NOMULTIDEFS;
8212 }
8213 if (f & MachO::MH_NOFIXPREBINDING) {
8214 outs() << " NOFIXPREBINDING";
8215 f &= ~MachO::MH_NOFIXPREBINDING;
8216 }
8217 if (f & MachO::MH_PREBINDABLE) {
8218 outs() << " PREBINDABLE";
8219 f &= ~MachO::MH_PREBINDABLE;
8220 }
8221 if (f & MachO::MH_ALLMODSBOUND) {
8222 outs() << " ALLMODSBOUND";
8223 f &= ~MachO::MH_ALLMODSBOUND;
8224 }
8225 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8226 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8227 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8228 }
8229 if (f & MachO::MH_CANONICAL) {
8230 outs() << " CANONICAL";
8231 f &= ~MachO::MH_CANONICAL;
8232 }
8233 if (f & MachO::MH_WEAK_DEFINES) {
8234 outs() << " WEAK_DEFINES";
8235 f &= ~MachO::MH_WEAK_DEFINES;
8236 }
8237 if (f & MachO::MH_BINDS_TO_WEAK) {
8238 outs() << " BINDS_TO_WEAK";
8239 f &= ~MachO::MH_BINDS_TO_WEAK;
8240 }
8241 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8242 outs() << " ALLOW_STACK_EXECUTION";
8243 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8244 }
8245 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8246 outs() << " DEAD_STRIPPABLE_DYLIB";
8247 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8248 }
8249 if (f & MachO::MH_PIE) {
8250 outs() << " PIE";
8251 f &= ~MachO::MH_PIE;
8252 }
8253 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8254 outs() << " NO_REEXPORTED_DYLIBS";
8255 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8256 }
8257 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8258 outs() << " MH_HAS_TLV_DESCRIPTORS";
8259 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8260 }
8261 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8262 outs() << " MH_NO_HEAP_EXECUTION";
8263 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8264 }
8265 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8266 outs() << " APP_EXTENSION_SAFE";
8267 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8268 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008269 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8270 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8271 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8272 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008273 if (f != 0 || flags == 0)
8274 outs() << format(" 0x%08" PRIx32, f);
8275 } else {
8276 outs() << format(" 0x%08" PRIx32, magic);
8277 outs() << format(" %7d", cputype);
8278 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8279 outs() << format(" 0x%02" PRIx32,
8280 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8281 outs() << format(" %10u", filetype);
8282 outs() << format(" %5u", ncmds);
8283 outs() << format(" %10u", sizeofcmds);
8284 outs() << format(" 0x%08" PRIx32, flags);
8285 }
8286 outs() << "\n";
8287}
8288
Kevin Enderby956366c2014-08-29 22:30:52 +00008289static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8290 StringRef SegName, uint64_t vmaddr,
8291 uint64_t vmsize, uint64_t fileoff,
8292 uint64_t filesize, uint32_t maxprot,
8293 uint32_t initprot, uint32_t nsects,
8294 uint32_t flags, uint32_t object_size,
8295 bool verbose) {
8296 uint64_t expected_cmdsize;
8297 if (cmd == MachO::LC_SEGMENT) {
8298 outs() << " cmd LC_SEGMENT\n";
8299 expected_cmdsize = nsects;
8300 expected_cmdsize *= sizeof(struct MachO::section);
8301 expected_cmdsize += sizeof(struct MachO::segment_command);
8302 } else {
8303 outs() << " cmd LC_SEGMENT_64\n";
8304 expected_cmdsize = nsects;
8305 expected_cmdsize *= sizeof(struct MachO::section_64);
8306 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8307 }
8308 outs() << " cmdsize " << cmdsize;
8309 if (cmdsize != expected_cmdsize)
8310 outs() << " Inconsistent size\n";
8311 else
8312 outs() << "\n";
8313 outs() << " segname " << SegName << "\n";
8314 if (cmd == MachO::LC_SEGMENT_64) {
8315 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8316 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8317 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008318 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8319 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008320 }
8321 outs() << " fileoff " << fileoff;
8322 if (fileoff > object_size)
8323 outs() << " (past end of file)\n";
8324 else
8325 outs() << "\n";
8326 outs() << " filesize " << filesize;
8327 if (fileoff + filesize > object_size)
8328 outs() << " (past end of file)\n";
8329 else
8330 outs() << "\n";
8331 if (verbose) {
8332 if ((maxprot &
8333 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8334 MachO::VM_PROT_EXECUTE)) != 0)
8335 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8336 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008337 outs() << " maxprot ";
8338 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8339 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8340 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008341 }
8342 if ((initprot &
8343 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8344 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008345 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008346 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008347 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008348 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8349 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8350 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008351 }
8352 } else {
8353 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8354 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8355 }
8356 outs() << " nsects " << nsects << "\n";
8357 if (verbose) {
8358 outs() << " flags";
8359 if (flags == 0)
8360 outs() << " (none)\n";
8361 else {
8362 if (flags & MachO::SG_HIGHVM) {
8363 outs() << " HIGHVM";
8364 flags &= ~MachO::SG_HIGHVM;
8365 }
8366 if (flags & MachO::SG_FVMLIB) {
8367 outs() << " FVMLIB";
8368 flags &= ~MachO::SG_FVMLIB;
8369 }
8370 if (flags & MachO::SG_NORELOC) {
8371 outs() << " NORELOC";
8372 flags &= ~MachO::SG_NORELOC;
8373 }
8374 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8375 outs() << " PROTECTED_VERSION_1";
8376 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8377 }
8378 if (flags)
8379 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8380 else
8381 outs() << "\n";
8382 }
8383 } else {
8384 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8385 }
8386}
8387
8388static void PrintSection(const char *sectname, const char *segname,
8389 uint64_t addr, uint64_t size, uint32_t offset,
8390 uint32_t align, uint32_t reloff, uint32_t nreloc,
8391 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8392 uint32_t cmd, const char *sg_segname,
8393 uint32_t filetype, uint32_t object_size,
8394 bool verbose) {
8395 outs() << "Section\n";
8396 outs() << " sectname " << format("%.16s\n", sectname);
8397 outs() << " segname " << format("%.16s", segname);
8398 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8399 outs() << " (does not match segment)\n";
8400 else
8401 outs() << "\n";
8402 if (cmd == MachO::LC_SEGMENT_64) {
8403 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8404 outs() << " size " << format("0x%016" PRIx64, size);
8405 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008406 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8407 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008408 }
8409 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8410 outs() << " (past end of file)\n";
8411 else
8412 outs() << "\n";
8413 outs() << " offset " << offset;
8414 if (offset > object_size)
8415 outs() << " (past end of file)\n";
8416 else
8417 outs() << "\n";
8418 uint32_t align_shifted = 1 << align;
8419 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8420 outs() << " reloff " << reloff;
8421 if (reloff > object_size)
8422 outs() << " (past end of file)\n";
8423 else
8424 outs() << "\n";
8425 outs() << " nreloc " << nreloc;
8426 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8427 outs() << " (past end of file)\n";
8428 else
8429 outs() << "\n";
8430 uint32_t section_type = flags & MachO::SECTION_TYPE;
8431 if (verbose) {
8432 outs() << " type";
8433 if (section_type == MachO::S_REGULAR)
8434 outs() << " S_REGULAR\n";
8435 else if (section_type == MachO::S_ZEROFILL)
8436 outs() << " S_ZEROFILL\n";
8437 else if (section_type == MachO::S_CSTRING_LITERALS)
8438 outs() << " S_CSTRING_LITERALS\n";
8439 else if (section_type == MachO::S_4BYTE_LITERALS)
8440 outs() << " S_4BYTE_LITERALS\n";
8441 else if (section_type == MachO::S_8BYTE_LITERALS)
8442 outs() << " S_8BYTE_LITERALS\n";
8443 else if (section_type == MachO::S_16BYTE_LITERALS)
8444 outs() << " S_16BYTE_LITERALS\n";
8445 else if (section_type == MachO::S_LITERAL_POINTERS)
8446 outs() << " S_LITERAL_POINTERS\n";
8447 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8448 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8449 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8450 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8451 else if (section_type == MachO::S_SYMBOL_STUBS)
8452 outs() << " S_SYMBOL_STUBS\n";
8453 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8454 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8455 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8456 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8457 else if (section_type == MachO::S_COALESCED)
8458 outs() << " S_COALESCED\n";
8459 else if (section_type == MachO::S_INTERPOSING)
8460 outs() << " S_INTERPOSING\n";
8461 else if (section_type == MachO::S_DTRACE_DOF)
8462 outs() << " S_DTRACE_DOF\n";
8463 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8464 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8465 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8466 outs() << " S_THREAD_LOCAL_REGULAR\n";
8467 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8468 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8469 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8470 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8471 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8472 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8473 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8474 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8475 else
8476 outs() << format("0x%08" PRIx32, section_type) << "\n";
8477 outs() << "attributes";
8478 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8479 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8480 outs() << " PURE_INSTRUCTIONS";
8481 if (section_attributes & MachO::S_ATTR_NO_TOC)
8482 outs() << " NO_TOC";
8483 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8484 outs() << " STRIP_STATIC_SYMS";
8485 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8486 outs() << " NO_DEAD_STRIP";
8487 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8488 outs() << " LIVE_SUPPORT";
8489 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8490 outs() << " SELF_MODIFYING_CODE";
8491 if (section_attributes & MachO::S_ATTR_DEBUG)
8492 outs() << " DEBUG";
8493 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8494 outs() << " SOME_INSTRUCTIONS";
8495 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8496 outs() << " EXT_RELOC";
8497 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8498 outs() << " LOC_RELOC";
8499 if (section_attributes == 0)
8500 outs() << " (none)";
8501 outs() << "\n";
8502 } else
8503 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8504 outs() << " reserved1 " << reserved1;
8505 if (section_type == MachO::S_SYMBOL_STUBS ||
8506 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8507 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8508 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8509 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8510 outs() << " (index into indirect symbol table)\n";
8511 else
8512 outs() << "\n";
8513 outs() << " reserved2 " << reserved2;
8514 if (section_type == MachO::S_SYMBOL_STUBS)
8515 outs() << " (size of stubs)\n";
8516 else
8517 outs() << "\n";
8518}
8519
David Majnemer73cc6ff2014-11-13 19:48:56 +00008520static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008521 uint32_t object_size) {
8522 outs() << " cmd LC_SYMTAB\n";
8523 outs() << " cmdsize " << st.cmdsize;
8524 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8525 outs() << " Incorrect size\n";
8526 else
8527 outs() << "\n";
8528 outs() << " symoff " << st.symoff;
8529 if (st.symoff > object_size)
8530 outs() << " (past end of file)\n";
8531 else
8532 outs() << "\n";
8533 outs() << " nsyms " << st.nsyms;
8534 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008535 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008536 big_size = st.nsyms;
8537 big_size *= sizeof(struct MachO::nlist_64);
8538 big_size += st.symoff;
8539 if (big_size > object_size)
8540 outs() << " (past end of file)\n";
8541 else
8542 outs() << "\n";
8543 } else {
8544 big_size = st.nsyms;
8545 big_size *= sizeof(struct MachO::nlist);
8546 big_size += st.symoff;
8547 if (big_size > object_size)
8548 outs() << " (past end of file)\n";
8549 else
8550 outs() << "\n";
8551 }
8552 outs() << " stroff " << st.stroff;
8553 if (st.stroff > object_size)
8554 outs() << " (past end of file)\n";
8555 else
8556 outs() << "\n";
8557 outs() << " strsize " << st.strsize;
8558 big_size = st.stroff;
8559 big_size += st.strsize;
8560 if (big_size > object_size)
8561 outs() << " (past end of file)\n";
8562 else
8563 outs() << "\n";
8564}
8565
8566static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8567 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008568 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008569 outs() << " cmd LC_DYSYMTAB\n";
8570 outs() << " cmdsize " << dyst.cmdsize;
8571 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8572 outs() << " Incorrect size\n";
8573 else
8574 outs() << "\n";
8575 outs() << " ilocalsym " << dyst.ilocalsym;
8576 if (dyst.ilocalsym > nsyms)
8577 outs() << " (greater than the number of symbols)\n";
8578 else
8579 outs() << "\n";
8580 outs() << " nlocalsym " << dyst.nlocalsym;
8581 uint64_t big_size;
8582 big_size = dyst.ilocalsym;
8583 big_size += dyst.nlocalsym;
8584 if (big_size > nsyms)
8585 outs() << " (past the end of the symbol table)\n";
8586 else
8587 outs() << "\n";
8588 outs() << " iextdefsym " << dyst.iextdefsym;
8589 if (dyst.iextdefsym > nsyms)
8590 outs() << " (greater than the number of symbols)\n";
8591 else
8592 outs() << "\n";
8593 outs() << " nextdefsym " << dyst.nextdefsym;
8594 big_size = dyst.iextdefsym;
8595 big_size += dyst.nextdefsym;
8596 if (big_size > nsyms)
8597 outs() << " (past the end of the symbol table)\n";
8598 else
8599 outs() << "\n";
8600 outs() << " iundefsym " << dyst.iundefsym;
8601 if (dyst.iundefsym > nsyms)
8602 outs() << " (greater than the number of symbols)\n";
8603 else
8604 outs() << "\n";
8605 outs() << " nundefsym " << dyst.nundefsym;
8606 big_size = dyst.iundefsym;
8607 big_size += dyst.nundefsym;
8608 if (big_size > nsyms)
8609 outs() << " (past the end of the symbol table)\n";
8610 else
8611 outs() << "\n";
8612 outs() << " tocoff " << dyst.tocoff;
8613 if (dyst.tocoff > object_size)
8614 outs() << " (past end of file)\n";
8615 else
8616 outs() << "\n";
8617 outs() << " ntoc " << dyst.ntoc;
8618 big_size = dyst.ntoc;
8619 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8620 big_size += dyst.tocoff;
8621 if (big_size > object_size)
8622 outs() << " (past end of file)\n";
8623 else
8624 outs() << "\n";
8625 outs() << " modtaboff " << dyst.modtaboff;
8626 if (dyst.modtaboff > object_size)
8627 outs() << " (past end of file)\n";
8628 else
8629 outs() << "\n";
8630 outs() << " nmodtab " << dyst.nmodtab;
8631 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008632 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008633 modtabend = dyst.nmodtab;
8634 modtabend *= sizeof(struct MachO::dylib_module_64);
8635 modtabend += dyst.modtaboff;
8636 } else {
8637 modtabend = dyst.nmodtab;
8638 modtabend *= sizeof(struct MachO::dylib_module);
8639 modtabend += dyst.modtaboff;
8640 }
8641 if (modtabend > object_size)
8642 outs() << " (past end of file)\n";
8643 else
8644 outs() << "\n";
8645 outs() << " extrefsymoff " << dyst.extrefsymoff;
8646 if (dyst.extrefsymoff > object_size)
8647 outs() << " (past end of file)\n";
8648 else
8649 outs() << "\n";
8650 outs() << " nextrefsyms " << dyst.nextrefsyms;
8651 big_size = dyst.nextrefsyms;
8652 big_size *= sizeof(struct MachO::dylib_reference);
8653 big_size += dyst.extrefsymoff;
8654 if (big_size > object_size)
8655 outs() << " (past end of file)\n";
8656 else
8657 outs() << "\n";
8658 outs() << " indirectsymoff " << dyst.indirectsymoff;
8659 if (dyst.indirectsymoff > object_size)
8660 outs() << " (past end of file)\n";
8661 else
8662 outs() << "\n";
8663 outs() << " nindirectsyms " << dyst.nindirectsyms;
8664 big_size = dyst.nindirectsyms;
8665 big_size *= sizeof(uint32_t);
8666 big_size += dyst.indirectsymoff;
8667 if (big_size > object_size)
8668 outs() << " (past end of file)\n";
8669 else
8670 outs() << "\n";
8671 outs() << " extreloff " << dyst.extreloff;
8672 if (dyst.extreloff > object_size)
8673 outs() << " (past end of file)\n";
8674 else
8675 outs() << "\n";
8676 outs() << " nextrel " << dyst.nextrel;
8677 big_size = dyst.nextrel;
8678 big_size *= sizeof(struct MachO::relocation_info);
8679 big_size += dyst.extreloff;
8680 if (big_size > object_size)
8681 outs() << " (past end of file)\n";
8682 else
8683 outs() << "\n";
8684 outs() << " locreloff " << dyst.locreloff;
8685 if (dyst.locreloff > object_size)
8686 outs() << " (past end of file)\n";
8687 else
8688 outs() << "\n";
8689 outs() << " nlocrel " << dyst.nlocrel;
8690 big_size = dyst.nlocrel;
8691 big_size *= sizeof(struct MachO::relocation_info);
8692 big_size += dyst.locreloff;
8693 if (big_size > object_size)
8694 outs() << " (past end of file)\n";
8695 else
8696 outs() << "\n";
8697}
8698
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008699static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8700 uint32_t object_size) {
8701 if (dc.cmd == MachO::LC_DYLD_INFO)
8702 outs() << " cmd LC_DYLD_INFO\n";
8703 else
8704 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8705 outs() << " cmdsize " << dc.cmdsize;
8706 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8707 outs() << " Incorrect size\n";
8708 else
8709 outs() << "\n";
8710 outs() << " rebase_off " << dc.rebase_off;
8711 if (dc.rebase_off > object_size)
8712 outs() << " (past end of file)\n";
8713 else
8714 outs() << "\n";
8715 outs() << " rebase_size " << dc.rebase_size;
8716 uint64_t big_size;
8717 big_size = dc.rebase_off;
8718 big_size += dc.rebase_size;
8719 if (big_size > object_size)
8720 outs() << " (past end of file)\n";
8721 else
8722 outs() << "\n";
8723 outs() << " bind_off " << dc.bind_off;
8724 if (dc.bind_off > object_size)
8725 outs() << " (past end of file)\n";
8726 else
8727 outs() << "\n";
8728 outs() << " bind_size " << dc.bind_size;
8729 big_size = dc.bind_off;
8730 big_size += dc.bind_size;
8731 if (big_size > object_size)
8732 outs() << " (past end of file)\n";
8733 else
8734 outs() << "\n";
8735 outs() << " weak_bind_off " << dc.weak_bind_off;
8736 if (dc.weak_bind_off > object_size)
8737 outs() << " (past end of file)\n";
8738 else
8739 outs() << "\n";
8740 outs() << " weak_bind_size " << dc.weak_bind_size;
8741 big_size = dc.weak_bind_off;
8742 big_size += dc.weak_bind_size;
8743 if (big_size > object_size)
8744 outs() << " (past end of file)\n";
8745 else
8746 outs() << "\n";
8747 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8748 if (dc.lazy_bind_off > object_size)
8749 outs() << " (past end of file)\n";
8750 else
8751 outs() << "\n";
8752 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8753 big_size = dc.lazy_bind_off;
8754 big_size += dc.lazy_bind_size;
8755 if (big_size > object_size)
8756 outs() << " (past end of file)\n";
8757 else
8758 outs() << "\n";
8759 outs() << " export_off " << dc.export_off;
8760 if (dc.export_off > object_size)
8761 outs() << " (past end of file)\n";
8762 else
8763 outs() << "\n";
8764 outs() << " export_size " << dc.export_size;
8765 big_size = dc.export_off;
8766 big_size += dc.export_size;
8767 if (big_size > object_size)
8768 outs() << " (past end of file)\n";
8769 else
8770 outs() << "\n";
8771}
8772
8773static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8774 const char *Ptr) {
8775 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8776 outs() << " cmd LC_ID_DYLINKER\n";
8777 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8778 outs() << " cmd LC_LOAD_DYLINKER\n";
8779 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8780 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8781 else
8782 outs() << " cmd ?(" << dyld.cmd << ")\n";
8783 outs() << " cmdsize " << dyld.cmdsize;
8784 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8785 outs() << " Incorrect size\n";
8786 else
8787 outs() << "\n";
8788 if (dyld.name >= dyld.cmdsize)
8789 outs() << " name ?(bad offset " << dyld.name << ")\n";
8790 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008791 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008792 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8793 }
8794}
8795
8796static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8797 outs() << " cmd LC_UUID\n";
8798 outs() << " cmdsize " << uuid.cmdsize;
8799 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8800 outs() << " Incorrect size\n";
8801 else
8802 outs() << "\n";
8803 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008804 for (int i = 0; i < 16; ++i) {
8805 outs() << format("%02" PRIX32, uuid.uuid[i]);
8806 if (i == 3 || i == 5 || i == 7 || i == 9)
8807 outs() << "-";
8808 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008809 outs() << "\n";
8810}
8811
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008812static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008813 outs() << " cmd LC_RPATH\n";
8814 outs() << " cmdsize " << rpath.cmdsize;
8815 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8816 outs() << " Incorrect size\n";
8817 else
8818 outs() << "\n";
8819 if (rpath.path >= rpath.cmdsize)
8820 outs() << " path ?(bad offset " << rpath.path << ")\n";
8821 else {
8822 const char *P = (const char *)(Ptr) + rpath.path;
8823 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8824 }
8825}
8826
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008827static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008828 StringRef LoadCmdName;
8829 switch (vd.cmd) {
8830 case MachO::LC_VERSION_MIN_MACOSX:
8831 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8832 break;
8833 case MachO::LC_VERSION_MIN_IPHONEOS:
8834 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8835 break;
8836 case MachO::LC_VERSION_MIN_TVOS:
8837 LoadCmdName = "LC_VERSION_MIN_TVOS";
8838 break;
8839 case MachO::LC_VERSION_MIN_WATCHOS:
8840 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8841 break;
8842 default:
8843 llvm_unreachable("Unknown version min load command");
8844 }
8845
8846 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008847 outs() << " cmdsize " << vd.cmdsize;
8848 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8849 outs() << " Incorrect size\n";
8850 else
8851 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008852 outs() << " version "
8853 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8854 << MachOObjectFile::getVersionMinMinor(vd, false);
8855 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8856 if (Update != 0)
8857 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008858 outs() << "\n";
8859 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008860 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008861 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008862 outs() << " sdk "
8863 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8864 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008865 }
Davide Italiano56baef32015-08-26 12:26:11 +00008866 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8867 if (Update != 0)
8868 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008869 outs() << "\n";
8870}
8871
Kevin Enderbya4579c42017-01-19 17:36:31 +00008872static void PrintNoteLoadCommand(MachO::note_command Nt) {
8873 outs() << " cmd LC_NOTE\n";
8874 outs() << " cmdsize " << Nt.cmdsize;
8875 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8876 outs() << " Incorrect size\n";
8877 else
8878 outs() << "\n";
8879 const char *d = Nt.data_owner;
8880 outs() << "data_owner " << format("%.16s\n", d);
8881 outs() << " offset " << Nt.offset << "\n";
8882 outs() << " size " << Nt.size << "\n";
8883}
8884
Steven Wu5b54a422017-01-23 20:07:55 +00008885static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8886 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8887 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8888 << "\n";
8889}
8890
8891static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8892 MachO::build_version_command bd) {
8893 outs() << " cmd LC_BUILD_VERSION\n";
8894 outs() << " cmdsize " << bd.cmdsize;
8895 if (bd.cmdsize !=
8896 sizeof(struct MachO::build_version_command) +
8897 bd.ntools * sizeof(struct MachO::build_tool_version))
8898 outs() << " Incorrect size\n";
8899 else
8900 outs() << "\n";
8901 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8902 << "\n";
8903 if (bd.sdk)
8904 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8905 << "\n";
8906 else
8907 outs() << " sdk n/a\n";
8908 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8909 << "\n";
8910 outs() << " ntools " << bd.ntools << "\n";
8911 for (unsigned i = 0; i < bd.ntools; ++i) {
8912 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8913 PrintBuildToolVersion(bv);
8914 }
8915}
8916
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008917static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8918 outs() << " cmd LC_SOURCE_VERSION\n";
8919 outs() << " cmdsize " << sd.cmdsize;
8920 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8921 outs() << " Incorrect size\n";
8922 else
8923 outs() << "\n";
8924 uint64_t a = (sd.version >> 40) & 0xffffff;
8925 uint64_t b = (sd.version >> 30) & 0x3ff;
8926 uint64_t c = (sd.version >> 20) & 0x3ff;
8927 uint64_t d = (sd.version >> 10) & 0x3ff;
8928 uint64_t e = sd.version & 0x3ff;
8929 outs() << " version " << a << "." << b;
8930 if (e != 0)
8931 outs() << "." << c << "." << d << "." << e;
8932 else if (d != 0)
8933 outs() << "." << c << "." << d;
8934 else if (c != 0)
8935 outs() << "." << c;
8936 outs() << "\n";
8937}
8938
8939static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8940 outs() << " cmd LC_MAIN\n";
8941 outs() << " cmdsize " << ep.cmdsize;
8942 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8943 outs() << " Incorrect size\n";
8944 else
8945 outs() << "\n";
8946 outs() << " entryoff " << ep.entryoff << "\n";
8947 outs() << " stacksize " << ep.stacksize << "\n";
8948}
8949
Kevin Enderby0804f4672014-12-16 23:25:52 +00008950static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8951 uint32_t object_size) {
8952 outs() << " cmd LC_ENCRYPTION_INFO\n";
8953 outs() << " cmdsize " << ec.cmdsize;
8954 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8955 outs() << " Incorrect size\n";
8956 else
8957 outs() << "\n";
8958 outs() << " cryptoff " << ec.cryptoff;
8959 if (ec.cryptoff > object_size)
8960 outs() << " (past end of file)\n";
8961 else
8962 outs() << "\n";
8963 outs() << " cryptsize " << ec.cryptsize;
8964 if (ec.cryptsize > object_size)
8965 outs() << " (past end of file)\n";
8966 else
8967 outs() << "\n";
8968 outs() << " cryptid " << ec.cryptid << "\n";
8969}
8970
Kevin Enderby57538292014-12-17 01:01:30 +00008971static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008972 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008973 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8974 outs() << " cmdsize " << ec.cmdsize;
8975 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8976 outs() << " Incorrect size\n";
8977 else
8978 outs() << "\n";
8979 outs() << " cryptoff " << ec.cryptoff;
8980 if (ec.cryptoff > object_size)
8981 outs() << " (past end of file)\n";
8982 else
8983 outs() << "\n";
8984 outs() << " cryptsize " << ec.cryptsize;
8985 if (ec.cryptsize > object_size)
8986 outs() << " (past end of file)\n";
8987 else
8988 outs() << "\n";
8989 outs() << " cryptid " << ec.cryptid << "\n";
8990 outs() << " pad " << ec.pad << "\n";
8991}
8992
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008993static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8994 const char *Ptr) {
8995 outs() << " cmd LC_LINKER_OPTION\n";
8996 outs() << " cmdsize " << lo.cmdsize;
8997 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8998 outs() << " Incorrect size\n";
8999 else
9000 outs() << "\n";
9001 outs() << " count " << lo.count << "\n";
9002 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9003 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9004 uint32_t i = 0;
9005 while (left > 0) {
9006 while (*string == '\0' && left > 0) {
9007 string++;
9008 left--;
9009 }
9010 if (left > 0) {
9011 i++;
9012 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00009013 uint32_t NullPos = StringRef(string, left).find('\0');
9014 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009015 string += len;
9016 left -= len;
9017 }
9018 }
9019 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009020 outs() << " count " << lo.count << " does not match number of strings "
9021 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009022}
9023
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009024static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9025 const char *Ptr) {
9026 outs() << " cmd LC_SUB_FRAMEWORK\n";
9027 outs() << " cmdsize " << sub.cmdsize;
9028 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9029 outs() << " Incorrect size\n";
9030 else
9031 outs() << "\n";
9032 if (sub.umbrella < sub.cmdsize) {
9033 const char *P = Ptr + sub.umbrella;
9034 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9035 } else {
9036 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9037 }
9038}
9039
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009040static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9041 const char *Ptr) {
9042 outs() << " cmd LC_SUB_UMBRELLA\n";
9043 outs() << " cmdsize " << sub.cmdsize;
9044 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9045 outs() << " Incorrect size\n";
9046 else
9047 outs() << "\n";
9048 if (sub.sub_umbrella < sub.cmdsize) {
9049 const char *P = Ptr + sub.sub_umbrella;
9050 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9051 } else {
9052 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9053 }
9054}
9055
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009056static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009057 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009058 outs() << " cmd LC_SUB_LIBRARY\n";
9059 outs() << " cmdsize " << sub.cmdsize;
9060 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9061 outs() << " Incorrect size\n";
9062 else
9063 outs() << "\n";
9064 if (sub.sub_library < sub.cmdsize) {
9065 const char *P = Ptr + sub.sub_library;
9066 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9067 } else {
9068 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9069 }
9070}
9071
Kevin Enderby186eac32014-12-19 21:06:24 +00009072static void PrintSubClientCommand(MachO::sub_client_command sub,
9073 const char *Ptr) {
9074 outs() << " cmd LC_SUB_CLIENT\n";
9075 outs() << " cmdsize " << sub.cmdsize;
9076 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9077 outs() << " Incorrect size\n";
9078 else
9079 outs() << "\n";
9080 if (sub.client < sub.cmdsize) {
9081 const char *P = Ptr + sub.client;
9082 outs() << " client " << P << " (offset " << sub.client << ")\n";
9083 } else {
9084 outs() << " client ?(bad offset " << sub.client << ")\n";
9085 }
9086}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009087
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009088static void PrintRoutinesCommand(MachO::routines_command r) {
9089 outs() << " cmd LC_ROUTINES\n";
9090 outs() << " cmdsize " << r.cmdsize;
9091 if (r.cmdsize != sizeof(struct MachO::routines_command))
9092 outs() << " Incorrect size\n";
9093 else
9094 outs() << "\n";
9095 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9096 outs() << " init_module " << r.init_module << "\n";
9097 outs() << " reserved1 " << r.reserved1 << "\n";
9098 outs() << " reserved2 " << r.reserved2 << "\n";
9099 outs() << " reserved3 " << r.reserved3 << "\n";
9100 outs() << " reserved4 " << r.reserved4 << "\n";
9101 outs() << " reserved5 " << r.reserved5 << "\n";
9102 outs() << " reserved6 " << r.reserved6 << "\n";
9103}
9104
9105static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9106 outs() << " cmd LC_ROUTINES_64\n";
9107 outs() << " cmdsize " << r.cmdsize;
9108 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9109 outs() << " Incorrect size\n";
9110 else
9111 outs() << "\n";
9112 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9113 outs() << " init_module " << r.init_module << "\n";
9114 outs() << " reserved1 " << r.reserved1 << "\n";
9115 outs() << " reserved2 " << r.reserved2 << "\n";
9116 outs() << " reserved3 " << r.reserved3 << "\n";
9117 outs() << " reserved4 " << r.reserved4 << "\n";
9118 outs() << " reserved5 " << r.reserved5 << "\n";
9119 outs() << " reserved6 " << r.reserved6 << "\n";
9120}
9121
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009122static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9123 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9124 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9125 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9126 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9127 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9128 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9129 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9130 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9131 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9132 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9133 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9134 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9135 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9136 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9137 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9138 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9139}
9140
Kevin Enderby48ef5342014-12-23 22:56:39 +00009141static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9142 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9143 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9144 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9145 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9146 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9147 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9148 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9149 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9150 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9151 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9152 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9153 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9154 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9155 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9156 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9157 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9158 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9159 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9160 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9161 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9162 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9163}
9164
Kevin Enderby227df342014-12-23 23:43:59 +00009165static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009166 uint32_t f;
9167 outs() << "\t mmst_reg ";
9168 for (f = 0; f < 10; f++)
9169 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9170 outs() << "\n";
9171 outs() << "\t mmst_rsrv ";
9172 for (f = 0; f < 6; f++)
9173 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9174 outs() << "\n";
9175}
9176
Kevin Enderbyaefb0032014-12-24 00:16:51 +00009177static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009178 uint32_t f;
9179 outs() << "\t xmm_reg ";
9180 for (f = 0; f < 16; f++)
9181 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9182 outs() << "\n";
9183}
9184
9185static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9186 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9187 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9188 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9189 outs() << " denorm " << fpu.fpu_fcw.denorm;
9190 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9191 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9192 outs() << " undfl " << fpu.fpu_fcw.undfl;
9193 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9194 outs() << "\t\t pc ";
9195 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9196 outs() << "FP_PREC_24B ";
9197 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9198 outs() << "FP_PREC_53B ";
9199 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9200 outs() << "FP_PREC_64B ";
9201 else
9202 outs() << fpu.fpu_fcw.pc << " ";
9203 outs() << "rc ";
9204 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9205 outs() << "FP_RND_NEAR ";
9206 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9207 outs() << "FP_RND_DOWN ";
9208 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9209 outs() << "FP_RND_UP ";
9210 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009211 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009212 outs() << "\n";
9213 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9214 outs() << " denorm " << fpu.fpu_fsw.denorm;
9215 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9216 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9217 outs() << " undfl " << fpu.fpu_fsw.undfl;
9218 outs() << " precis " << fpu.fpu_fsw.precis;
9219 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9220 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9221 outs() << " c0 " << fpu.fpu_fsw.c0;
9222 outs() << " c1 " << fpu.fpu_fsw.c1;
9223 outs() << " c2 " << fpu.fpu_fsw.c2;
9224 outs() << " tos " << fpu.fpu_fsw.tos;
9225 outs() << " c3 " << fpu.fpu_fsw.c3;
9226 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9227 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9228 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9229 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9230 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9231 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9232 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9233 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9234 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9235 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9236 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9237 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9238 outs() << "\n";
9239 outs() << "\t fpu_stmm0:\n";
9240 Print_mmst_reg(fpu.fpu_stmm0);
9241 outs() << "\t fpu_stmm1:\n";
9242 Print_mmst_reg(fpu.fpu_stmm1);
9243 outs() << "\t fpu_stmm2:\n";
9244 Print_mmst_reg(fpu.fpu_stmm2);
9245 outs() << "\t fpu_stmm3:\n";
9246 Print_mmst_reg(fpu.fpu_stmm3);
9247 outs() << "\t fpu_stmm4:\n";
9248 Print_mmst_reg(fpu.fpu_stmm4);
9249 outs() << "\t fpu_stmm5:\n";
9250 Print_mmst_reg(fpu.fpu_stmm5);
9251 outs() << "\t fpu_stmm6:\n";
9252 Print_mmst_reg(fpu.fpu_stmm6);
9253 outs() << "\t fpu_stmm7:\n";
9254 Print_mmst_reg(fpu.fpu_stmm7);
9255 outs() << "\t fpu_xmm0:\n";
9256 Print_xmm_reg(fpu.fpu_xmm0);
9257 outs() << "\t fpu_xmm1:\n";
9258 Print_xmm_reg(fpu.fpu_xmm1);
9259 outs() << "\t fpu_xmm2:\n";
9260 Print_xmm_reg(fpu.fpu_xmm2);
9261 outs() << "\t fpu_xmm3:\n";
9262 Print_xmm_reg(fpu.fpu_xmm3);
9263 outs() << "\t fpu_xmm4:\n";
9264 Print_xmm_reg(fpu.fpu_xmm4);
9265 outs() << "\t fpu_xmm5:\n";
9266 Print_xmm_reg(fpu.fpu_xmm5);
9267 outs() << "\t fpu_xmm6:\n";
9268 Print_xmm_reg(fpu.fpu_xmm6);
9269 outs() << "\t fpu_xmm7:\n";
9270 Print_xmm_reg(fpu.fpu_xmm7);
9271 outs() << "\t fpu_xmm8:\n";
9272 Print_xmm_reg(fpu.fpu_xmm8);
9273 outs() << "\t fpu_xmm9:\n";
9274 Print_xmm_reg(fpu.fpu_xmm9);
9275 outs() << "\t fpu_xmm10:\n";
9276 Print_xmm_reg(fpu.fpu_xmm10);
9277 outs() << "\t fpu_xmm11:\n";
9278 Print_xmm_reg(fpu.fpu_xmm11);
9279 outs() << "\t fpu_xmm12:\n";
9280 Print_xmm_reg(fpu.fpu_xmm12);
9281 outs() << "\t fpu_xmm13:\n";
9282 Print_xmm_reg(fpu.fpu_xmm13);
9283 outs() << "\t fpu_xmm14:\n";
9284 Print_xmm_reg(fpu.fpu_xmm14);
9285 outs() << "\t fpu_xmm15:\n";
9286 Print_xmm_reg(fpu.fpu_xmm15);
9287 outs() << "\t fpu_rsrv4:\n";
9288 for (uint32_t f = 0; f < 6; f++) {
9289 outs() << "\t ";
9290 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009291 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009292 outs() << "\n";
9293 }
9294 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9295 outs() << "\n";
9296}
9297
9298static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9299 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9300 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9301 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9302}
9303
Kevin Enderby41c9c002016-10-21 18:22:35 +00009304static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9305 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9306 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9307 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9308 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9309 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9310 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9311 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9312 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9313 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9314 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9315 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9316 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9317 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9318 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9319 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9320 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9321 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9322}
9323
Kevin Enderby7747cb52016-11-03 20:51:28 +00009324static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9325 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9326 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9327 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9328 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9329 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9330 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9331 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9332 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9333 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9334 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9335 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9336 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9337 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9338 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9339 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9340 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9341 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9342 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9343 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9344 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9345 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9346 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9347 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9348 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9349 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9350 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9351 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9352 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9353 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9354 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9355 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9356 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9357 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9358 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9359}
9360
Kevin Enderby48ef5342014-12-23 22:56:39 +00009361static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9362 bool isLittleEndian, uint32_t cputype) {
9363 if (t.cmd == MachO::LC_THREAD)
9364 outs() << " cmd LC_THREAD\n";
9365 else if (t.cmd == MachO::LC_UNIXTHREAD)
9366 outs() << " cmd LC_UNIXTHREAD\n";
9367 else
9368 outs() << " cmd " << t.cmd << " (unknown)\n";
9369 outs() << " cmdsize " << t.cmdsize;
9370 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9371 outs() << " Incorrect size\n";
9372 else
9373 outs() << "\n";
9374
9375 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9376 const char *end = Ptr + t.cmdsize;
9377 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009378 if (cputype == MachO::CPU_TYPE_I386) {
9379 while (begin < end) {
9380 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9381 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9382 begin += sizeof(uint32_t);
9383 } else {
9384 flavor = 0;
9385 begin = end;
9386 }
9387 if (isLittleEndian != sys::IsLittleEndianHost)
9388 sys::swapByteOrder(flavor);
9389 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9390 memcpy((char *)&count, begin, sizeof(uint32_t));
9391 begin += sizeof(uint32_t);
9392 } else {
9393 count = 0;
9394 begin = end;
9395 }
9396 if (isLittleEndian != sys::IsLittleEndianHost)
9397 sys::swapByteOrder(count);
9398 if (flavor == MachO::x86_THREAD_STATE32) {
9399 outs() << " flavor i386_THREAD_STATE\n";
9400 if (count == MachO::x86_THREAD_STATE32_COUNT)
9401 outs() << " count i386_THREAD_STATE_COUNT\n";
9402 else
9403 outs() << " count " << count
9404 << " (not x86_THREAD_STATE32_COUNT)\n";
9405 MachO::x86_thread_state32_t cpu32;
9406 left = end - begin;
9407 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9408 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9409 begin += sizeof(MachO::x86_thread_state32_t);
9410 } else {
9411 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9412 memcpy(&cpu32, begin, left);
9413 begin += left;
9414 }
9415 if (isLittleEndian != sys::IsLittleEndianHost)
9416 swapStruct(cpu32);
9417 Print_x86_thread_state32_t(cpu32);
9418 } else if (flavor == MachO::x86_THREAD_STATE) {
9419 outs() << " flavor x86_THREAD_STATE\n";
9420 if (count == MachO::x86_THREAD_STATE_COUNT)
9421 outs() << " count x86_THREAD_STATE_COUNT\n";
9422 else
9423 outs() << " count " << count
9424 << " (not x86_THREAD_STATE_COUNT)\n";
9425 struct MachO::x86_thread_state_t ts;
9426 left = end - begin;
9427 if (left >= sizeof(MachO::x86_thread_state_t)) {
9428 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9429 begin += sizeof(MachO::x86_thread_state_t);
9430 } else {
9431 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9432 memcpy(&ts, begin, left);
9433 begin += left;
9434 }
9435 if (isLittleEndian != sys::IsLittleEndianHost)
9436 swapStruct(ts);
9437 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9438 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9439 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9440 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9441 else
9442 outs() << "tsh.count " << ts.tsh.count
9443 << " (not x86_THREAD_STATE32_COUNT\n";
9444 Print_x86_thread_state32_t(ts.uts.ts32);
9445 } else {
9446 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9447 << ts.tsh.count << "\n";
9448 }
9449 } else {
9450 outs() << " flavor " << flavor << " (unknown)\n";
9451 outs() << " count " << count << "\n";
9452 outs() << " state (unknown)\n";
9453 begin += count * sizeof(uint32_t);
9454 }
9455 }
9456 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009457 while (begin < end) {
9458 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9459 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9460 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009461 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009462 flavor = 0;
9463 begin = end;
9464 }
9465 if (isLittleEndian != sys::IsLittleEndianHost)
9466 sys::swapByteOrder(flavor);
9467 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9468 memcpy((char *)&count, begin, sizeof(uint32_t));
9469 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009470 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009471 count = 0;
9472 begin = end;
9473 }
9474 if (isLittleEndian != sys::IsLittleEndianHost)
9475 sys::swapByteOrder(count);
9476 if (flavor == MachO::x86_THREAD_STATE64) {
9477 outs() << " flavor x86_THREAD_STATE64\n";
9478 if (count == MachO::x86_THREAD_STATE64_COUNT)
9479 outs() << " count x86_THREAD_STATE64_COUNT\n";
9480 else
9481 outs() << " count " << count
9482 << " (not x86_THREAD_STATE64_COUNT)\n";
9483 MachO::x86_thread_state64_t cpu64;
9484 left = end - begin;
9485 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9486 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9487 begin += sizeof(MachO::x86_thread_state64_t);
9488 } else {
9489 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9490 memcpy(&cpu64, begin, left);
9491 begin += left;
9492 }
9493 if (isLittleEndian != sys::IsLittleEndianHost)
9494 swapStruct(cpu64);
9495 Print_x86_thread_state64_t(cpu64);
9496 } else if (flavor == MachO::x86_THREAD_STATE) {
9497 outs() << " flavor x86_THREAD_STATE\n";
9498 if (count == MachO::x86_THREAD_STATE_COUNT)
9499 outs() << " count x86_THREAD_STATE_COUNT\n";
9500 else
9501 outs() << " count " << count
9502 << " (not x86_THREAD_STATE_COUNT)\n";
9503 struct MachO::x86_thread_state_t ts;
9504 left = end - begin;
9505 if (left >= sizeof(MachO::x86_thread_state_t)) {
9506 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9507 begin += sizeof(MachO::x86_thread_state_t);
9508 } else {
9509 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9510 memcpy(&ts, begin, left);
9511 begin += left;
9512 }
9513 if (isLittleEndian != sys::IsLittleEndianHost)
9514 swapStruct(ts);
9515 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9516 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9517 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9518 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9519 else
9520 outs() << "tsh.count " << ts.tsh.count
9521 << " (not x86_THREAD_STATE64_COUNT\n";
9522 Print_x86_thread_state64_t(ts.uts.ts64);
9523 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009524 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9525 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009526 }
9527 } else if (flavor == MachO::x86_FLOAT_STATE) {
9528 outs() << " flavor x86_FLOAT_STATE\n";
9529 if (count == MachO::x86_FLOAT_STATE_COUNT)
9530 outs() << " count x86_FLOAT_STATE_COUNT\n";
9531 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009532 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009533 struct MachO::x86_float_state_t fs;
9534 left = end - begin;
9535 if (left >= sizeof(MachO::x86_float_state_t)) {
9536 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9537 begin += sizeof(MachO::x86_float_state_t);
9538 } else {
9539 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9540 memcpy(&fs, begin, left);
9541 begin += left;
9542 }
9543 if (isLittleEndian != sys::IsLittleEndianHost)
9544 swapStruct(fs);
9545 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9546 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009547 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009548 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9549 else
9550 outs() << "fsh.count " << fs.fsh.count
9551 << " (not x86_FLOAT_STATE64_COUNT\n";
9552 Print_x86_float_state_t(fs.ufs.fs64);
9553 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009554 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9555 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009556 }
9557 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9558 outs() << " flavor x86_EXCEPTION_STATE\n";
9559 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9560 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9561 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009562 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009563 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9564 struct MachO::x86_exception_state_t es;
9565 left = end - begin;
9566 if (left >= sizeof(MachO::x86_exception_state_t)) {
9567 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9568 begin += sizeof(MachO::x86_exception_state_t);
9569 } else {
9570 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9571 memcpy(&es, begin, left);
9572 begin += left;
9573 }
9574 if (isLittleEndian != sys::IsLittleEndianHost)
9575 swapStruct(es);
9576 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9577 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009578 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009579 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9580 else
9581 outs() << "\t esh.count " << es.esh.count
9582 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9583 Print_x86_exception_state_t(es.ues.es64);
9584 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009585 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9586 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009587 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009588 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9589 outs() << " flavor x86_EXCEPTION_STATE64\n";
9590 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9591 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9592 else
9593 outs() << " count " << count
9594 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9595 struct MachO::x86_exception_state64_t es64;
9596 left = end - begin;
9597 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9598 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9599 begin += sizeof(MachO::x86_exception_state64_t);
9600 } else {
9601 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9602 memcpy(&es64, begin, left);
9603 begin += left;
9604 }
9605 if (isLittleEndian != sys::IsLittleEndianHost)
9606 swapStruct(es64);
9607 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009608 } else {
9609 outs() << " flavor " << flavor << " (unknown)\n";
9610 outs() << " count " << count << "\n";
9611 outs() << " state (unknown)\n";
9612 begin += count * sizeof(uint32_t);
9613 }
9614 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009615 } else if (cputype == MachO::CPU_TYPE_ARM) {
9616 while (begin < end) {
9617 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9618 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9619 begin += sizeof(uint32_t);
9620 } else {
9621 flavor = 0;
9622 begin = end;
9623 }
9624 if (isLittleEndian != sys::IsLittleEndianHost)
9625 sys::swapByteOrder(flavor);
9626 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9627 memcpy((char *)&count, begin, sizeof(uint32_t));
9628 begin += sizeof(uint32_t);
9629 } else {
9630 count = 0;
9631 begin = end;
9632 }
9633 if (isLittleEndian != sys::IsLittleEndianHost)
9634 sys::swapByteOrder(count);
9635 if (flavor == MachO::ARM_THREAD_STATE) {
9636 outs() << " flavor ARM_THREAD_STATE\n";
9637 if (count == MachO::ARM_THREAD_STATE_COUNT)
9638 outs() << " count ARM_THREAD_STATE_COUNT\n";
9639 else
9640 outs() << " count " << count
9641 << " (not ARM_THREAD_STATE_COUNT)\n";
9642 MachO::arm_thread_state32_t cpu32;
9643 left = end - begin;
9644 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9645 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9646 begin += sizeof(MachO::arm_thread_state32_t);
9647 } else {
9648 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9649 memcpy(&cpu32, begin, left);
9650 begin += left;
9651 }
9652 if (isLittleEndian != sys::IsLittleEndianHost)
9653 swapStruct(cpu32);
9654 Print_arm_thread_state32_t(cpu32);
9655 } else {
9656 outs() << " flavor " << flavor << " (unknown)\n";
9657 outs() << " count " << count << "\n";
9658 outs() << " state (unknown)\n";
9659 begin += count * sizeof(uint32_t);
9660 }
9661 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009662 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9663 while (begin < end) {
9664 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9665 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9666 begin += sizeof(uint32_t);
9667 } else {
9668 flavor = 0;
9669 begin = end;
9670 }
9671 if (isLittleEndian != sys::IsLittleEndianHost)
9672 sys::swapByteOrder(flavor);
9673 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9674 memcpy((char *)&count, begin, sizeof(uint32_t));
9675 begin += sizeof(uint32_t);
9676 } else {
9677 count = 0;
9678 begin = end;
9679 }
9680 if (isLittleEndian != sys::IsLittleEndianHost)
9681 sys::swapByteOrder(count);
9682 if (flavor == MachO::ARM_THREAD_STATE64) {
9683 outs() << " flavor ARM_THREAD_STATE64\n";
9684 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9685 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9686 else
9687 outs() << " count " << count
9688 << " (not ARM_THREAD_STATE64_COUNT)\n";
9689 MachO::arm_thread_state64_t cpu64;
9690 left = end - begin;
9691 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9692 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9693 begin += sizeof(MachO::arm_thread_state64_t);
9694 } else {
9695 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9696 memcpy(&cpu64, begin, left);
9697 begin += left;
9698 }
9699 if (isLittleEndian != sys::IsLittleEndianHost)
9700 swapStruct(cpu64);
9701 Print_arm_thread_state64_t(cpu64);
9702 } else {
9703 outs() << " flavor " << flavor << " (unknown)\n";
9704 outs() << " count " << count << "\n";
9705 outs() << " state (unknown)\n";
9706 begin += count * sizeof(uint32_t);
9707 }
9708 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009709 } else {
9710 while (begin < end) {
9711 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9712 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9713 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009714 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009715 flavor = 0;
9716 begin = end;
9717 }
9718 if (isLittleEndian != sys::IsLittleEndianHost)
9719 sys::swapByteOrder(flavor);
9720 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9721 memcpy((char *)&count, begin, sizeof(uint32_t));
9722 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009723 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009724 count = 0;
9725 begin = end;
9726 }
9727 if (isLittleEndian != sys::IsLittleEndianHost)
9728 sys::swapByteOrder(count);
9729 outs() << " flavor " << flavor << "\n";
9730 outs() << " count " << count << "\n";
9731 outs() << " state (Unknown cputype/cpusubtype)\n";
9732 begin += count * sizeof(uint32_t);
9733 }
9734 }
9735}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009736
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009737static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9738 if (dl.cmd == MachO::LC_ID_DYLIB)
9739 outs() << " cmd LC_ID_DYLIB\n";
9740 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9741 outs() << " cmd LC_LOAD_DYLIB\n";
9742 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9743 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9744 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9745 outs() << " cmd LC_REEXPORT_DYLIB\n";
9746 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9747 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9748 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9749 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9750 else
9751 outs() << " cmd " << dl.cmd << " (unknown)\n";
9752 outs() << " cmdsize " << dl.cmdsize;
9753 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9754 outs() << " Incorrect size\n";
9755 else
9756 outs() << "\n";
9757 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009758 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009759 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9760 } else {
9761 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9762 }
9763 outs() << " time stamp " << dl.dylib.timestamp << " ";
9764 time_t t = dl.dylib.timestamp;
9765 outs() << ctime(&t);
9766 outs() << " current version ";
9767 if (dl.dylib.current_version == 0xffffffff)
9768 outs() << "n/a\n";
9769 else
9770 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9771 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9772 << (dl.dylib.current_version & 0xff) << "\n";
9773 outs() << "compatibility version ";
9774 if (dl.dylib.compatibility_version == 0xffffffff)
9775 outs() << "n/a\n";
9776 else
9777 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9778 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9779 << (dl.dylib.compatibility_version & 0xff) << "\n";
9780}
9781
9782static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9783 uint32_t object_size) {
9784 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009785 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009786 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9787 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9788 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9789 outs() << " cmd LC_FUNCTION_STARTS\n";
9790 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9791 outs() << " cmd LC_DATA_IN_CODE\n";
9792 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9793 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9794 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9795 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9796 else
9797 outs() << " cmd " << ld.cmd << " (?)\n";
9798 outs() << " cmdsize " << ld.cmdsize;
9799 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9800 outs() << " Incorrect size\n";
9801 else
9802 outs() << "\n";
9803 outs() << " dataoff " << ld.dataoff;
9804 if (ld.dataoff > object_size)
9805 outs() << " (past end of file)\n";
9806 else
9807 outs() << "\n";
9808 outs() << " datasize " << ld.datasize;
9809 uint64_t big_size = ld.dataoff;
9810 big_size += ld.datasize;
9811 if (big_size > object_size)
9812 outs() << " (past end of file)\n";
9813 else
9814 outs() << "\n";
9815}
9816
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009817static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9818 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009819 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009820 unsigned Index = 0;
9821 for (const auto &Command : Obj->load_commands()) {
9822 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009823 if (Command.C.cmd == MachO::LC_SEGMENT) {
9824 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9825 const char *sg_segname = SLC.segname;
9826 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9827 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9828 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9829 verbose);
9830 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009831 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009832 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9833 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9834 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9835 }
9836 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9837 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9838 const char *sg_segname = SLC_64.segname;
9839 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9840 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9841 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9842 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9843 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9844 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9845 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9846 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9847 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9848 sg_segname, filetype, Buf.size(), verbose);
9849 }
9850 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9851 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009852 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009853 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9854 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9855 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009856 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9857 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009858 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9859 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9860 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9861 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9862 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9863 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9864 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9865 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9866 PrintDyldLoadCommand(Dyld, Command.Ptr);
9867 } else if (Command.C.cmd == MachO::LC_UUID) {
9868 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9869 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009870 } else if (Command.C.cmd == MachO::LC_RPATH) {
9871 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9872 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009873 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009874 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9875 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9876 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009877 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9878 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009879 } else if (Command.C.cmd == MachO::LC_NOTE) {
9880 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9881 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009882 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9883 MachO::build_version_command Bv =
9884 Obj->getBuildVersionLoadCommand(Command);
9885 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009886 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9887 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9888 PrintSourceVersionCommand(Sd);
9889 } else if (Command.C.cmd == MachO::LC_MAIN) {
9890 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9891 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009892 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009893 MachO::encryption_info_command Ei =
9894 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009895 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009896 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009897 MachO::encryption_info_command_64 Ei =
9898 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009899 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009900 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009901 MachO::linker_option_command Lo =
9902 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009903 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009904 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9905 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9906 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009907 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9908 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9909 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009910 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9911 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9912 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009913 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9914 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9915 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009916 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9917 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9918 PrintRoutinesCommand(Rc);
9919 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9920 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9921 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009922 } else if (Command.C.cmd == MachO::LC_THREAD ||
9923 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9924 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9925 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009926 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9927 Command.C.cmd == MachO::LC_ID_DYLIB ||
9928 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9929 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9930 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9931 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009932 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9933 PrintDylibCommand(Dl, Command.Ptr);
9934 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9935 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9936 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9937 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9938 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9939 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9940 MachO::linkedit_data_command Ld =
9941 Obj->getLinkeditDataLoadCommand(Command);
9942 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009943 } else {
9944 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9945 << ")\n";
9946 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9947 // TODO: get and print the raw bytes of the load command.
9948 }
9949 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009950 }
9951}
9952
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009953static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009954 if (Obj->is64Bit()) {
9955 MachO::mach_header_64 H_64;
9956 H_64 = Obj->getHeader64();
9957 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9958 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9959 } else {
9960 MachO::mach_header H;
9961 H = Obj->getHeader();
9962 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9963 H.sizeofcmds, H.flags, verbose);
9964 }
9965}
9966
9967void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9968 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009969 PrintMachHeader(file, !NonVerbose);
9970}
9971
9972void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9973 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009974 uint32_t filetype = 0;
9975 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009976 if (file->is64Bit()) {
9977 MachO::mach_header_64 H_64;
9978 H_64 = file->getHeader64();
9979 filetype = H_64.filetype;
9980 cputype = H_64.cputype;
9981 } else {
9982 MachO::mach_header H;
9983 H = file->getHeader();
9984 filetype = H.filetype;
9985 cputype = H.cputype;
9986 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009987 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009988}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009989
9990//===----------------------------------------------------------------------===//
9991// export trie dumping
9992//===----------------------------------------------------------------------===//
9993
9994void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009995 uint64_t BaseSegmentAddress = 0;
9996 for (const auto &Command : Obj->load_commands()) {
9997 if (Command.C.cmd == MachO::LC_SEGMENT) {
9998 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9999 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10000 BaseSegmentAddress = Seg.vmaddr;
10001 break;
10002 }
10003 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10004 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10005 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10006 BaseSegmentAddress = Seg.vmaddr;
10007 break;
10008 }
10009 }
10010 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010011 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +000010012 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010013 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010014 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10015 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10016 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10017 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10018 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10019 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10020 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10021 if (ReExport)
10022 outs() << "[re-export] ";
10023 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010024 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010025 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010026 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010027 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010028 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +000010029 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010030 if (WeakDef) {
10031 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010032 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010033 }
10034 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010035 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010036 outs() << ", ";
10037 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010038 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010039 }
10040 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010041 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010042 outs() << ", ";
10043 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010044 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010045 }
10046 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010047 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010048 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010049 outs() << format("resolver=0x%08llX", Entry.other());
10050 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010051 }
10052 outs() << "]";
10053 }
10054 if (ReExport) {
10055 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010056 int Ordinal = Entry.other() - 1;
10057 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10058 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +000010059 outs() << " (from " << DylibName << ")";
10060 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010061 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010062 }
10063 outs() << "\n";
10064 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010065 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010066 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikd04bc352014-08-30 00:20:14 +000010067}
Nick Kledzikac431442014-09-12 21:34:15 +000010068
Nick Kledzikac431442014-09-12 21:34:15 +000010069//===----------------------------------------------------------------------===//
10070// rebase table dumping
10071//===----------------------------------------------------------------------===//
10072
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010073void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +000010074 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010075 Error Err = Error::success();
10076 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10077 StringRef SegmentName = Entry.segmentName();
10078 StringRef SectionName = Entry.sectionName();
10079 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +000010080
10081 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010082 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10083 SegmentName.str().c_str(), SectionName.str().c_str(),
10084 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +000010085 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010086 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010087 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikac431442014-09-12 21:34:15 +000010088}
Nick Kledzik56ebef42014-09-16 01:41:51 +000010089
10090static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10091 StringRef DylibName;
10092 switch (Ordinal) {
10093 case MachO::BIND_SPECIAL_DYLIB_SELF:
10094 return "this-image";
10095 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10096 return "main-executable";
10097 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10098 return "flat-namespace";
10099 default:
Nick Kledzikabd29872014-09-16 22:03:13 +000010100 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010101 std::error_code EC =
10102 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +000010103 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +000010104 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +000010105 return DylibName;
10106 }
Nick Kledzik56ebef42014-09-16 01:41:51 +000010107 }
Nick Kledzikabd29872014-09-16 22:03:13 +000010108 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010109}
10110
10111//===----------------------------------------------------------------------===//
10112// bind table dumping
10113//===----------------------------------------------------------------------===//
10114
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010115void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010116 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010117 outs() << "segment section address type "
10118 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010119 Error Err = Error::success();
10120 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010121 StringRef SegmentName = Entry.segmentName();
10122 StringRef SectionName = Entry.sectionName();
10123 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010124
10125 // Table lines look like:
10126 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010127 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +000010128 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010129 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010130 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010131 << left_justify(SectionName, 18) << " "
10132 << format_hex(Address, 10, true) << " "
10133 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010134 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010135 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010136 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010137 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010138 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010139 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010140}
10141
10142//===----------------------------------------------------------------------===//
10143// lazy bind table dumping
10144//===----------------------------------------------------------------------===//
10145
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010146void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010147 outs() << "segment section address "
10148 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010149 Error Err = Error::success();
10150 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010151 StringRef SegmentName = Entry.segmentName();
10152 StringRef SectionName = Entry.sectionName();
10153 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010154
10155 // Table lines look like:
10156 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010157 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010158 << left_justify(SectionName, 18) << " "
10159 << format_hex(Address, 10, true) << " "
10160 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010161 << Entry.symbolName() << "\n";
10162 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010163 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010164 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010165}
10166
Nick Kledzik56ebef42014-09-16 01:41:51 +000010167//===----------------------------------------------------------------------===//
10168// weak bind table dumping
10169//===----------------------------------------------------------------------===//
10170
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010171void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010172 outs() << "segment section address "
10173 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010174 Error Err = Error::success();
10175 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010176 // Strong symbols don't have a location to update.
10177 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010178 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010179 << Entry.symbolName() << "\n";
10180 continue;
10181 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010182 StringRef SegmentName = Entry.segmentName();
10183 StringRef SectionName = Entry.sectionName();
10184 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010185
10186 // Table lines look like:
10187 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010188 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010189 << left_justify(SectionName, 18) << " "
10190 << format_hex(Address, 10, true) << " "
10191 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010192 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10193 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010194 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010195 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010196 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010197}
10198
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010199// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10200// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10201// information for that address. If the address is found its binding symbol
10202// name is returned. If not nullptr is returned.
10203static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10204 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010205 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010206 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010207 Error Err = Error::success();
10208 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010209 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010210 StringRef name = Entry.symbolName();
10211 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010212 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010213 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010214 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010215 report_error(std::move(Err), info->O->getFileName());
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010216 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010217 auto name = info->bindtable->lookup(ReferenceValue);
10218 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010219}
Michael Trent1854ecc2017-12-05 07:50:00 +000010220