blob: e6845400a92326589616cabf68eb26cd2a128e20 [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
Fangrui Song523758e2019-04-15 15:31:42 +000058using namespace llvm::object;
Benjamin Kramer43a772e2011-09-19 17:56:04 +000059
Fangrui Song9d812f42019-04-15 15:00:10 +000060namespace llvm {
61
Serge Guelton94c36fa2019-05-22 06:30:46 +000062cl::OptionCategory MachOCat("llvm-objdump MachO Specific Options");
63
Fangrui Song9d812f42019-04-15 15:00:10 +000064extern cl::opt<bool> ArchiveHeaders;
65extern cl::opt<bool> Disassemble;
66extern cl::opt<bool> DisassembleAll;
67extern cl::opt<DIDumpType> DwarfDumpType;
68extern cl::list<std::string> FilterSections;
69extern cl::list<std::string> MAttrs;
70extern cl::opt<std::string> MCPU;
71extern cl::opt<bool> NoShowRawInsn;
72extern cl::opt<bool> NoLeadingAddr;
73extern cl::opt<bool> PrintImmHex;
74extern cl::opt<bool> PrivateHeaders;
75extern cl::opt<bool> Relocations;
76extern cl::opt<bool> SectionHeaders;
77extern cl::opt<bool> SectionContents;
78extern cl::opt<bool> SymbolTable;
79extern cl::opt<std::string> TripleName;
80extern cl::opt<bool> UnwindInfo;
81
82cl::opt<bool>
83 FirstPrivateHeader("private-header",
84 cl::desc("Display only the first format specific file "
Serge Guelton94c36fa2019-05-22 06:30:46 +000085 "header"),
86 cl::cat(MachOCat));
Fangrui Song9d812f42019-04-15 15:00:10 +000087
88cl::opt<bool> ExportsTrie("exports-trie",
Serge Guelton94c36fa2019-05-22 06:30:46 +000089 cl::desc("Display mach-o exported symbols"),
90 cl::cat(MachOCat));
Fangrui Song9d812f42019-04-15 15:00:10 +000091
Serge Guelton94c36fa2019-05-22 06:30:46 +000092cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"),
93 cl::cat(MachOCat));
Fangrui Song9d812f42019-04-15 15:00:10 +000094
Serge Guelton94c36fa2019-05-22 06:30:46 +000095cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"),
96 cl::cat(MachOCat));
Fangrui Song9d812f42019-04-15 15:00:10 +000097
98cl::opt<bool> LazyBind("lazy-bind",
Serge Guelton94c36fa2019-05-22 06:30:46 +000099 cl::desc("Display mach-o lazy binding info"),
100 cl::cat(MachOCat));
Fangrui Song9d812f42019-04-15 15:00:10 +0000101
102cl::opt<bool> WeakBind("weak-bind",
Serge Guelton94c36fa2019-05-22 06:30:46 +0000103 cl::desc("Display mach-o weak binding info"),
104 cl::cat(MachOCat));
Fangrui Song9d812f42019-04-15 15:00:10 +0000105
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000106static cl::opt<bool>
Matthew Voss0f436772019-02-19 19:46:08 +0000107 UseDbg("g", cl::Grouping,
Serge Guelton94c36fa2019-05-22 06:30:46 +0000108 cl::desc("Print line information from debug info if available"),
109 cl::cat(MachOCat));
Benjamin Kramer699128e2011-09-21 01:13:19 +0000110
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000111static cl::opt<std::string> DSYMFile("dsym",
Serge Guelton94c36fa2019-05-22 06:30:46 +0000112 cl::desc("Use .dSYM file for debug info"),
113 cl::cat(MachOCat));
Benjamin Kramer699128e2011-09-21 01:13:19 +0000114
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000115static cl::opt<bool> FullLeadingAddr("full-leading-addr",
Serge Guelton94c36fa2019-05-22 06:30:46 +0000116 cl::desc("Print full leading address"),
117 cl::cat(MachOCat));
Kevin Enderbybf246f52014-09-24 23:08:22 +0000118
Kevin Enderbyf9d60f02016-11-29 21:43:40 +0000119static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
Serge Guelton94c36fa2019-05-22 06:30:46 +0000120 cl::desc("Print no leading headers"),
121 cl::cat(MachOCat));
Kevin Enderbyf9d60f02016-11-29 21:43:40 +0000122
Fangrui Song9d812f42019-04-15 15:00:10 +0000123cl::opt<bool> UniversalHeaders("universal-headers",
124 cl::desc("Print Mach-O universal headers "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000125 "(requires -macho)"),
126 cl::cat(MachOCat));
Kevin Enderby13023a12015-01-15 23:19:11 +0000127
Kevin Enderby131d1772015-01-09 19:22:37 +0000128cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +0000129 ArchiveMemberOffsets("archive-member-offsets",
130 cl::desc("Print the offset to each archive member for "
131 "Mach-O archives (requires -macho and "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000132 "-archive-headers)"),
133 cl::cat(MachOCat));
Kevin Enderby8972e482015-04-30 20:30:42 +0000134
Fangrui Song9d812f42019-04-15 15:00:10 +0000135cl::opt<bool> IndirectSymbols("indirect-symbols",
136 cl::desc("Print indirect symbol table for Mach-O "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000137 "objects (requires -macho)"),
138 cl::cat(MachOCat));
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000139
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000140cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000141 DataInCode("data-in-code",
142 cl::desc("Print the data in code table for Mach-O objects "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000143 "(requires -macho)"),
144 cl::cat(MachOCat));
Fangrui Song9d812f42019-04-15 15:00:10 +0000145
146cl::opt<bool> LinkOptHints("link-opt-hints",
147 cl::desc("Print the linker optimization hints for "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000148 "Mach-O objects (requires -macho)"),
149 cl::cat(MachOCat));
Fangrui Song9d812f42019-04-15 15:00:10 +0000150
151cl::opt<bool> InfoPlist("info-plist",
152 cl::desc("Print the info plist section as strings for "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000153 "Mach-O objects (requires -macho)"),
154 cl::cat(MachOCat));
Fangrui Song9d812f42019-04-15 15:00:10 +0000155
156cl::opt<bool> DylibsUsed("dylibs-used",
157 cl::desc("Print the shared libraries used for linked "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000158 "Mach-O files (requires -macho)"),
159 cl::cat(MachOCat));
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000160
Kevin Enderby9a509442015-01-27 21:28:24 +0000161cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000162 DylibId("dylib-id",
163 cl::desc("Print the shared library's id for the dylib Mach-O "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000164 "file (requires -macho)"),
165 cl::cat(MachOCat));
Kevin Enderby9a509442015-01-27 21:28:24 +0000166
Kevin Enderbycd66be52015-03-11 22:06:32 +0000167cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000168 NonVerbose("non-verbose",
169 cl::desc("Print the info for Mach-O objects in "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000170 "non-verbose or numeric form (requires -macho)"),
171 cl::cat(MachOCat));
Kevin Enderbycd66be52015-03-11 22:06:32 +0000172
Kevin Enderbyf0640752015-03-13 17:56:32 +0000173cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000174 ObjcMetaData("objc-meta-data",
175 cl::desc("Print the Objective-C runtime meta data for "
Serge Guelton94c36fa2019-05-22 06:30:46 +0000176 "Mach-O files (requires -macho)"),
177 cl::cat(MachOCat));
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000178
Fangrui Song9d812f42019-04-15 15:00:10 +0000179cl::opt<std::string> DisSymName(
Kevin Enderby6a221752015-03-17 17:10:57 +0000180 "dis-symname",
Serge Guelton94c36fa2019-05-22 06:30:46 +0000181 cl::desc("disassemble just this symbol's instructions (requires -macho)"),
182 cl::cat(MachOCat));
Kevin Enderby6a221752015-03-17 17:10:57 +0000183
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000184static cl::opt<bool> NoSymbolicOperands(
185 "no-symbolic-operands",
Serge Guelton94c36fa2019-05-22 06:30:46 +0000186 cl::desc("do not symbolic operands when disassembling (requires -macho)"),
187 cl::cat(MachOCat));
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000188
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000189static cl::list<std::string>
190 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
Serge Guelton94c36fa2019-05-22 06:30:46 +0000191 cl::ZeroOrMore, cl::cat(MachOCat));
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000192
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000193bool ArchAll = false;
194
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000195static std::string ThumbTripleName;
196
197static const Target *GetTarget(const MachOObjectFile *MachOObj,
198 const char **McpuDefault,
199 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000200 // Figure out the target triple.
Fangrui Song523758e2019-04-15 15:31:42 +0000201 Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000202 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000203 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000204 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000205 }
206
207 if (TT.getArch() == Triple::arm) {
208 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
209 // that support ARM are also capable of Thumb mode.
Fangrui Song523758e2019-04-15 15:31:42 +0000210 Triple ThumbTriple = TT;
Tim Northover9e8eb412016-04-22 23:21:13 +0000211 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
212 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000213 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000214 }
215
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000216 // Get the target specific parser.
217 std::string Error;
218 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000219 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000220 return TheTarget;
221
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000222 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
223 if (*ThumbTarget)
224 return TheTarget;
225
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000226 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000227 if (!TheTarget)
228 errs() << TripleName;
229 else
230 errs() << ThumbTripleName;
231 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000232 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000233}
234
Owen Andersond9243c42011-10-17 21:37:35 +0000235struct SymbolSorter {
236 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000237 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000238 if (!ATypeOrErr)
George Rimarf0f38d92019-08-21 11:07:31 +0000239 reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000240 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000241 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000242 if (!BTypeOrErr)
George Rimarf0f38d92019-08-21 11:07:31 +0000243 reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000244 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000245 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
246 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000247 return AAddr < BAddr;
248 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000249};
250
Kevin Enderby273ae012013-06-06 17:20:50 +0000251// Types for the storted data in code table that is built before disassembly
252// and the predicate function to sort them.
253typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
254typedef std::vector<DiceTableEntry> DiceTable;
255typedef DiceTable::iterator dice_table_iterator;
256
Francis Ricci195a66f2017-10-06 15:54:20 +0000257#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000258namespace {
259struct ScopedXarFile {
260 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000261 ScopedXarFile(const char *filename, int32_t flags)
262 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000263 ~ScopedXarFile() {
264 if (xar)
265 xar_close(xar);
266 }
267 ScopedXarFile(const ScopedXarFile &) = delete;
268 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
269 operator xar_t() { return xar; }
270};
271
272struct ScopedXarIter {
273 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000274 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000275 ~ScopedXarIter() {
276 if (iter)
277 xar_iter_free(iter);
278 }
279 ScopedXarIter(const ScopedXarIter &) = delete;
280 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
281 operator xar_iter_t() { return iter; }
282};
283} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000284#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000285
Kevin Enderby930fdc72014-11-06 19:00:13 +0000286// This is used to search for a data in code table entry for the PC being
287// disassembled. The j parameter has the PC in j.first. A single data in code
288// table entry can cover many bytes for each of its Kind's. So if the offset,
289// aka the i.first value, of the data in code table entry plus its Length
290// covers the PC being searched for this will return true. If not it will
291// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000292static bool compareDiceTableEntries(const DiceTableEntry &i,
293 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000294 uint16_t Length;
295 i.second.getLength(Length);
296
297 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000298}
299
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000300static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000301 unsigned short Kind) {
302 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000303
304 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000305 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000306 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000307 if (Length >= 4) {
308 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000309 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000310 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000311 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000312 Size = 4;
313 } else if (Length >= 2) {
314 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000315 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000316 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000317 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000318 Size = 2;
319 } else {
320 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000321 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000322 Value = bytes[0];
323 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000324 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000325 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000326 if (Kind == MachO::DICE_KIND_DATA)
327 outs() << "\t@ KIND_DATA\n";
328 else
329 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000330 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000331 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000332 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000333 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000334 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000335 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
336 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000337 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000338 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000339 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000340 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000341 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000342 outs() << "\t.short " << format("%5u", Value & 0xffff)
343 << "\t@ KIND_JUMP_TABLE16\n";
344 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000345 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000346 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000347 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
348 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000349 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000350 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000351 outs() << "\t.long " << Value;
352 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
353 outs() << "\t@ KIND_JUMP_TABLE32\n";
354 else
355 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
356 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000357 break;
358 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000359 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000360}
361
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000362static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000363 std::vector<SectionRef> &Sections,
364 std::vector<SymbolRef> &Symbols,
365 SmallVectorImpl<uint64_t> &FoundFns,
366 uint64_t &BaseSegmentAddress) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000367 const StringRef FileName = MachOObj->getFileName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000368 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000369 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
370 if (!SymName.startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000371 Symbols.push_back(Symbol);
372 }
Owen Andersond9243c42011-10-17 21:37:35 +0000373
George Rimarbcc00e12019-08-14 11:10:11 +0000374 for (const SectionRef &Section : MachOObj->sections())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000375 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000376
Kevin Enderby273ae012013-06-06 17:20:50 +0000377 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000378 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000379 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000380 // We found a function starts segment, parse the addresses for later
381 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000382 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000383 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000384
Charles Davis8bdfafd2013-09-01 04:28:48 +0000385 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000386 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
387 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000388 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000389 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000390 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000391 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000392 }
Kuba Mraceka7c48b72019-08-01 15:51:14 +0000393 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
394 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
395 StringRef SegName = SLC.segname;
396 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
397 BaseSegmentAddressSet = true;
398 BaseSegmentAddress = SLC.vmaddr;
399 }
Kevin Enderby273ae012013-06-06 17:20:50 +0000400 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000401 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000402}
403
Kuba Mraceka7c48b72019-08-01 15:51:14 +0000404static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
405 DiceTable &Dices, uint64_t &InstSize) {
406 // Check the data in code table here to see if this is data not an
407 // instruction to be disassembled.
408 DiceTable Dice;
409 Dice.push_back(std::make_pair(PC, DiceRef()));
410 dice_table_iterator DTI =
411 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
412 compareDiceTableEntries);
413 if (DTI != Dices.end()) {
414 uint16_t Length;
415 DTI->second.getLength(Length);
416 uint16_t Kind;
417 DTI->second.getKind(Kind);
418 InstSize = DumpDataInCode(bytes, Length, Kind);
419 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
420 (PC == (DTI->first + Length - 1)) && (Length & 1))
421 InstSize++;
422 return true;
423 }
424 return false;
425}
426
George Rimarc1964882019-01-18 11:33:26 +0000427static void printRelocationTargetName(const MachOObjectFile *O,
428 const MachO::any_relocation_info &RE,
429 raw_string_ostream &Fmt) {
430 // Target of a scattered relocation is an address. In the interest of
431 // generating pretty output, scan through the symbol table looking for a
432 // symbol that aligns with that address. If we find one, print it.
433 // Otherwise, we just print the hex address of the target.
Fangrui Songe7834bd2019-04-07 08:19:55 +0000434 const StringRef FileName = O->getFileName();
George Rimarc1964882019-01-18 11:33:26 +0000435 if (O->isRelocationScattered(RE)) {
436 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
437
438 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000439 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
440 if (Addr != Val)
George Rimarc1964882019-01-18 11:33:26 +0000441 continue;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000442 Fmt << unwrapOrError(Symbol.getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000443 return;
444 }
445
446 // If we couldn't find a symbol that this relocation refers to, try
447 // to find a section beginning instead.
448 for (const SectionRef &Section : ToolSectionFilter(*O)) {
George Rimarc1964882019-01-18 11:33:26 +0000449 uint64_t Addr = Section.getAddress();
450 if (Addr != Val)
451 continue;
George Rimarbcc00e12019-08-14 11:10:11 +0000452 StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
453 Fmt << NameOrErr;
George Rimarc1964882019-01-18 11:33:26 +0000454 return;
455 }
456
457 Fmt << format("0x%x", Val);
458 return;
459 }
460
461 StringRef S;
462 bool isExtern = O->getPlainRelocationExternal(RE);
463 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
464
465 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
466 Fmt << format("0x%0" PRIx64, Val);
467 return;
468 }
469
470 if (isExtern) {
471 symbol_iterator SI = O->symbol_begin();
472 advance(SI, Val);
Fangrui Songe7834bd2019-04-07 08:19:55 +0000473 S = unwrapOrError(SI->getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000474 } else {
475 section_iterator SI = O->section_begin();
476 // Adjust for the fact that sections are 1-indexed.
477 if (Val == 0) {
478 Fmt << "0 (?,?)";
479 return;
480 }
481 uint32_t I = Val - 1;
482 while (I != 0 && SI != O->section_end()) {
483 --I;
484 advance(SI, 1);
485 }
George Rimarbcc00e12019-08-14 11:10:11 +0000486 if (SI == O->section_end()) {
George Rimarc1964882019-01-18 11:33:26 +0000487 Fmt << Val << " (?,?)";
George Rimarbcc00e12019-08-14 11:10:11 +0000488 } else {
489 if (Expected<StringRef> NameOrErr = SI->getName())
490 S = *NameOrErr;
491 else
492 consumeError(NameOrErr.takeError());
493 }
George Rimarc1964882019-01-18 11:33:26 +0000494 }
495
496 Fmt << S;
497}
498
Fangrui Song523758e2019-04-15 15:31:42 +0000499Error getMachORelocationValueString(const MachOObjectFile *Obj,
500 const RelocationRef &RelRef,
501 SmallVectorImpl<char> &Result) {
George Rimarc1964882019-01-18 11:33:26 +0000502 DataRefImpl Rel = RelRef.getRawDataRefImpl();
503 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
504
505 unsigned Arch = Obj->getArch();
506
507 std::string FmtBuf;
508 raw_string_ostream Fmt(FmtBuf);
509 unsigned Type = Obj->getAnyRelocationType(RE);
510 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
511
512 // Determine any addends that should be displayed with the relocation.
513 // These require decoding the relocation type, which is triple-specific.
514
515 // X86_64 has entirely custom relocation types.
516 if (Arch == Triple::x86_64) {
517 switch (Type) {
518 case MachO::X86_64_RELOC_GOT_LOAD:
519 case MachO::X86_64_RELOC_GOT: {
520 printRelocationTargetName(Obj, RE, Fmt);
521 Fmt << "@GOT";
522 if (IsPCRel)
523 Fmt << "PCREL";
524 break;
525 }
526 case MachO::X86_64_RELOC_SUBTRACTOR: {
527 DataRefImpl RelNext = Rel;
528 Obj->moveRelocationNext(RelNext);
529 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
530
531 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
532 // X86_64_RELOC_UNSIGNED.
533 // NOTE: Scattered relocations don't exist on x86_64.
534 unsigned RType = Obj->getAnyRelocationType(RENext);
535 if (RType != MachO::X86_64_RELOC_UNSIGNED)
George Rimarf0f38d92019-08-21 11:07:31 +0000536 reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
537 "X86_64_RELOC_SUBTRACTOR.");
George Rimarc1964882019-01-18 11:33:26 +0000538
539 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
540 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
541 printRelocationTargetName(Obj, RENext, Fmt);
542 Fmt << "-";
543 printRelocationTargetName(Obj, RE, Fmt);
544 break;
545 }
546 case MachO::X86_64_RELOC_TLV:
547 printRelocationTargetName(Obj, RE, Fmt);
548 Fmt << "@TLV";
549 if (IsPCRel)
550 Fmt << "P";
551 break;
552 case MachO::X86_64_RELOC_SIGNED_1:
553 printRelocationTargetName(Obj, RE, Fmt);
554 Fmt << "-1";
555 break;
556 case MachO::X86_64_RELOC_SIGNED_2:
557 printRelocationTargetName(Obj, RE, Fmt);
558 Fmt << "-2";
559 break;
560 case MachO::X86_64_RELOC_SIGNED_4:
561 printRelocationTargetName(Obj, RE, Fmt);
562 Fmt << "-4";
563 break;
564 default:
565 printRelocationTargetName(Obj, RE, Fmt);
566 break;
567 }
568 // X86 and ARM share some relocation types in common.
569 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
570 Arch == Triple::ppc) {
571 // Generic relocation types...
572 switch (Type) {
573 case MachO::GENERIC_RELOC_PAIR: // prints no info
Fangrui Songf67de6c2019-04-08 16:24:08 +0000574 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000575 case MachO::GENERIC_RELOC_SECTDIFF: {
576 DataRefImpl RelNext = Rel;
577 Obj->moveRelocationNext(RelNext);
578 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
579
580 // X86 sect diff's must be followed by a relocation of type
581 // GENERIC_RELOC_PAIR.
582 unsigned RType = Obj->getAnyRelocationType(RENext);
583
584 if (RType != MachO::GENERIC_RELOC_PAIR)
George Rimarf0f38d92019-08-21 11:07:31 +0000585 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
586 "GENERIC_RELOC_SECTDIFF.");
George Rimarc1964882019-01-18 11:33:26 +0000587
588 printRelocationTargetName(Obj, RE, Fmt);
589 Fmt << "-";
590 printRelocationTargetName(Obj, RENext, Fmt);
591 break;
592 }
593 }
594
595 if (Arch == Triple::x86 || Arch == Triple::ppc) {
596 switch (Type) {
597 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
598 DataRefImpl RelNext = Rel;
599 Obj->moveRelocationNext(RelNext);
600 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
601
602 // X86 sect diff's must be followed by a relocation of type
603 // GENERIC_RELOC_PAIR.
604 unsigned RType = Obj->getAnyRelocationType(RENext);
605 if (RType != MachO::GENERIC_RELOC_PAIR)
George Rimarf0f38d92019-08-21 11:07:31 +0000606 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
607 "GENERIC_RELOC_LOCAL_SECTDIFF.");
George Rimarc1964882019-01-18 11:33:26 +0000608
609 printRelocationTargetName(Obj, RE, Fmt);
610 Fmt << "-";
611 printRelocationTargetName(Obj, RENext, Fmt);
612 break;
613 }
614 case MachO::GENERIC_RELOC_TLV: {
615 printRelocationTargetName(Obj, RE, Fmt);
616 Fmt << "@TLV";
617 if (IsPCRel)
618 Fmt << "P";
619 break;
620 }
621 default:
622 printRelocationTargetName(Obj, RE, Fmt);
623 }
624 } else { // ARM-specific relocations
625 switch (Type) {
626 case MachO::ARM_RELOC_HALF:
627 case MachO::ARM_RELOC_HALF_SECTDIFF: {
628 // Half relocations steal a bit from the length field to encode
629 // whether this is an upper16 or a lower16 relocation.
630 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
631
632 if (isUpper)
633 Fmt << ":upper16:(";
634 else
635 Fmt << ":lower16:(";
636 printRelocationTargetName(Obj, RE, Fmt);
637
638 DataRefImpl RelNext = Rel;
639 Obj->moveRelocationNext(RelNext);
640 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
641
642 // ARM half relocs must be followed by a relocation of type
643 // ARM_RELOC_PAIR.
644 unsigned RType = Obj->getAnyRelocationType(RENext);
645 if (RType != MachO::ARM_RELOC_PAIR)
George Rimarf0f38d92019-08-21 11:07:31 +0000646 reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
647 "ARM_RELOC_HALF");
George Rimarc1964882019-01-18 11:33:26 +0000648
649 // NOTE: The half of the target virtual address is stashed in the
650 // address field of the secondary relocation, but we can't reverse
651 // engineer the constant offset from it without decoding the movw/movt
652 // instruction to find the other half in its immediate field.
653
654 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
655 // symbol/section pointer of the follow-on relocation.
656 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
657 Fmt << "-";
658 printRelocationTargetName(Obj, RENext, Fmt);
659 }
660
661 Fmt << ")";
662 break;
663 }
664 default: {
665 printRelocationTargetName(Obj, RE, Fmt);
666 }
667 }
668 }
669 } else
670 printRelocationTargetName(Obj, RE, Fmt);
671
672 Fmt.flush();
673 Result.append(FmtBuf.begin(), FmtBuf.end());
Fangrui Songf67de6c2019-04-08 16:24:08 +0000674 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000675}
676
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000677static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
678 uint32_t n, uint32_t count,
679 uint32_t stride, uint64_t addr) {
680 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
681 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
682 if (n > nindirectsyms)
683 outs() << " (entries start past the end of the indirect symbol "
684 "table) (reserved1 field greater than the table size)";
685 else if (n + count > nindirectsyms)
686 outs() << " (entries extends past the end of the indirect symbol "
687 "table)";
688 outs() << "\n";
689 uint32_t cputype = O->getHeader().cputype;
690 if (cputype & MachO::CPU_ARCH_ABI64)
691 outs() << "address index";
692 else
693 outs() << "address index";
694 if (verbose)
695 outs() << " name\n";
696 else
697 outs() << "\n";
698 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
699 if (cputype & MachO::CPU_ARCH_ABI64)
700 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
701 else
Tim Northover43978372016-04-26 18:29:16 +0000702 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000703 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
704 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
705 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
706 outs() << "LOCAL\n";
707 continue;
708 }
709 if (indirect_symbol ==
710 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
711 outs() << "LOCAL ABSOLUTE\n";
712 continue;
713 }
714 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
715 outs() << "ABSOLUTE\n";
716 continue;
717 }
718 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000719 if (verbose) {
720 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
721 if (indirect_symbol < Symtab.nsyms) {
722 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
723 SymbolRef Symbol = *Sym;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000724 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
Kevin Enderbyf0640752015-03-13 17:56:32 +0000725 } else {
726 outs() << "?";
727 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000728 }
729 outs() << "\n";
730 }
731}
732
733static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000734 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000735 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
736 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
737 for (unsigned J = 0; J < Seg.nsects; ++J) {
738 MachO::section_64 Sec = O->getSection64(Load, J);
739 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
740 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
741 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
742 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
743 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
744 section_type == MachO::S_SYMBOL_STUBS) {
745 uint32_t stride;
746 if (section_type == MachO::S_SYMBOL_STUBS)
747 stride = Sec.reserved2;
748 else
749 stride = 8;
750 if (stride == 0) {
751 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
752 << Sec.sectname << ") "
753 << "(size of stubs in reserved2 field is zero)\n";
754 continue;
755 }
756 uint32_t count = Sec.size / stride;
757 outs() << "Indirect symbols for (" << Sec.segname << ","
758 << Sec.sectname << ") " << count << " entries";
759 uint32_t n = Sec.reserved1;
760 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
761 }
762 }
763 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
764 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
765 for (unsigned J = 0; J < Seg.nsects; ++J) {
766 MachO::section Sec = O->getSection(Load, J);
767 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
768 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
769 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
770 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
771 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
772 section_type == MachO::S_SYMBOL_STUBS) {
773 uint32_t stride;
774 if (section_type == MachO::S_SYMBOL_STUBS)
775 stride = Sec.reserved2;
776 else
777 stride = 4;
778 if (stride == 0) {
779 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
780 << Sec.sectname << ") "
781 << "(size of stubs in reserved2 field is zero)\n";
782 continue;
783 }
784 uint32_t count = Sec.size / stride;
785 outs() << "Indirect symbols for (" << Sec.segname << ","
786 << Sec.sectname << ") " << count << " entries";
787 uint32_t n = Sec.reserved1;
788 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
789 }
790 }
791 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000792 }
793}
794
Michael Trenta1703b12017-12-15 17:57:40 +0000795static void PrintRType(const uint64_t cputype, const unsigned r_type) {
796 static char const *generic_r_types[] = {
797 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
798 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
799 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
800 };
801 static char const *x86_64_r_types[] = {
802 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
803 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
804 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
805 };
806 static char const *arm_r_types[] = {
807 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
808 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
809 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
810 };
811 static char const *arm64_r_types[] = {
812 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
813 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
814 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
815 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000816
Michael Trenta1703b12017-12-15 17:57:40 +0000817 if (r_type > 0xf){
818 outs() << format("%-7u", r_type) << " ";
819 return;
820 }
821 switch (cputype) {
822 case MachO::CPU_TYPE_I386:
823 outs() << generic_r_types[r_type];
824 break;
825 case MachO::CPU_TYPE_X86_64:
826 outs() << x86_64_r_types[r_type];
827 break;
828 case MachO::CPU_TYPE_ARM:
829 outs() << arm_r_types[r_type];
830 break;
831 case MachO::CPU_TYPE_ARM64:
Tim Northoverff6875a2019-05-14 11:25:44 +0000832 case MachO::CPU_TYPE_ARM64_32:
Michael Trenta1703b12017-12-15 17:57:40 +0000833 outs() << arm64_r_types[r_type];
834 break;
835 default:
836 outs() << format("%-7u ", r_type);
837 }
838}
839
840static void PrintRLength(const uint64_t cputype, const unsigned r_type,
841 const unsigned r_length, const bool previous_arm_half){
842 if (cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +0000843 (r_type == MachO::ARM_RELOC_HALF ||
844 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
Michael Trenta1703b12017-12-15 17:57:40 +0000845 if ((r_length & 0x1) == 0)
846 outs() << "lo/";
847 else
848 outs() << "hi/";
849 if ((r_length & 0x1) == 0)
850 outs() << "arm ";
851 else
852 outs() << "thm ";
853 } else {
854 switch (r_length) {
855 case 0:
856 outs() << "byte ";
857 break;
858 case 1:
859 outs() << "word ";
860 break;
861 case 2:
862 outs() << "long ";
863 break;
864 case 3:
865 if (cputype == MachO::CPU_TYPE_X86_64)
866 outs() << "quad ";
867 else
868 outs() << format("?(%2d) ", r_length);
869 break;
870 default:
871 outs() << format("?(%2d) ", r_length);
872 }
873 }
874}
875
876static void PrintRelocationEntries(const MachOObjectFile *O,
877 const relocation_iterator Begin,
878 const relocation_iterator End,
879 const uint64_t cputype,
880 const bool verbose) {
881 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
882 bool previous_arm_half = false;
883 bool previous_sectdiff = false;
884 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000885
Michael Trenta1703b12017-12-15 17:57:40 +0000886 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
887 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
888 const MachO::any_relocation_info RE = O->getRelocation(Rel);
889 const unsigned r_type = O->getAnyRelocationType(RE);
890 const bool r_scattered = O->isRelocationScattered(RE);
891 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
892 const unsigned r_length = O->getAnyRelocationLength(RE);
893 const unsigned r_address = O->getAnyRelocationAddress(RE);
894 const bool r_extern = (r_scattered ? false :
895 O->getPlainRelocationExternal(RE));
896 const uint32_t r_value = (r_scattered ?
897 O->getScatteredRelocationValue(RE) : 0);
898 const unsigned r_symbolnum = (r_scattered ? 0 :
899 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000900
Michael Trenta1703b12017-12-15 17:57:40 +0000901 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
902 if (verbose) {
903 // scattered: address
904 if ((cputype == MachO::CPU_TYPE_I386 &&
Fangrui Song523758e2019-04-15 15:31:42 +0000905 r_type == MachO::GENERIC_RELOC_PAIR) ||
906 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
Michael Trenta1703b12017-12-15 17:57:40 +0000907 outs() << " ";
908 else
909 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000910
Michael Trenta1703b12017-12-15 17:57:40 +0000911 // scattered: pcrel
912 if (r_pcrel)
913 outs() << "True ";
914 else
915 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000916
Michael Trenta1703b12017-12-15 17:57:40 +0000917 // scattered: length
918 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000919
Michael Trenta1703b12017-12-15 17:57:40 +0000920 // scattered: extern & type
921 outs() << "n/a ";
922 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000923
Michael Trenta1703b12017-12-15 17:57:40 +0000924 // scattered: scattered & value
925 outs() << format("True 0x%08x", (unsigned int)r_value);
926 if (previous_sectdiff == false) {
927 if ((cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +0000928 r_type == MachO::ARM_RELOC_PAIR))
Michael Trenta1703b12017-12-15 17:57:40 +0000929 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
Fangrui Song523758e2019-04-15 15:31:42 +0000930 } else if (cputype == MachO::CPU_TYPE_ARM &&
931 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
Michael Trenta1703b12017-12-15 17:57:40 +0000932 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
933 if ((cputype == MachO::CPU_TYPE_I386 &&
Fangrui Song523758e2019-04-15 15:31:42 +0000934 (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
935 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
Michael Trenta1703b12017-12-15 17:57:40 +0000936 (cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +0000937 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
938 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
939 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
940 previous_sectdiff = true;
941 sectdiff_r_type = r_type;
942 } else {
Michael Trenta1703b12017-12-15 17:57:40 +0000943 previous_sectdiff = false;
944 sectdiff_r_type = 0;
945 }
946 if (cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +0000947 (r_type == MachO::ARM_RELOC_HALF ||
948 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
Michael Trenta1703b12017-12-15 17:57:40 +0000949 previous_arm_half = true;
950 else
951 previous_arm_half = false;
952 outs() << "\n";
953 }
954 else {
955 // scattered: address pcrel length extern type scattered value
956 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
957 (unsigned int)r_address, r_pcrel, r_length, r_type,
958 (unsigned int)r_value);
959 }
960 }
961 else {
962 if (verbose) {
963 // plain: address
Fangrui Song523758e2019-04-15 15:31:42 +0000964 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
Michael Trenta1703b12017-12-15 17:57:40 +0000965 outs() << " ";
966 else
967 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000968
Michael Trenta1703b12017-12-15 17:57:40 +0000969 // plain: pcrel
970 if (r_pcrel)
971 outs() << "True ";
972 else
973 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000974
Michael Trenta1703b12017-12-15 17:57:40 +0000975 // plain: length
976 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000977
Michael Trenta1703b12017-12-15 17:57:40 +0000978 if (r_extern) {
979 // plain: extern & type & scattered
980 outs() << "True ";
981 PrintRType(cputype, r_type);
982 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000983
Michael Trenta1703b12017-12-15 17:57:40 +0000984 // plain: symbolnum/value
985 if (r_symbolnum > Symtab.nsyms)
986 outs() << format("?(%d)\n", r_symbolnum);
987 else {
988 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
989 Expected<StringRef> SymNameNext = Symbol.getName();
990 const char *name = NULL;
991 if (SymNameNext)
992 name = SymNameNext->data();
993 if (name == NULL)
994 outs() << format("?(%d)\n", r_symbolnum);
995 else
996 outs() << name << "\n";
997 }
998 }
999 else {
1000 // plain: extern & type & scattered
1001 outs() << "False ";
1002 PrintRType(cputype, r_type);
1003 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001004
Michael Trenta1703b12017-12-15 17:57:40 +00001005 // plain: symbolnum/value
Fangrui Song523758e2019-04-15 15:31:42 +00001006 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
Michael Trenta1703b12017-12-15 17:57:40 +00001007 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
Tim Northoverff6875a2019-05-14 11:25:44 +00001008 else if ((cputype == MachO::CPU_TYPE_ARM64 ||
1009 cputype == MachO::CPU_TYPE_ARM64_32) &&
Fangrui Song523758e2019-04-15 15:31:42 +00001010 r_type == MachO::ARM64_RELOC_ADDEND)
Michael Trenta1703b12017-12-15 17:57:40 +00001011 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
1012 else {
1013 outs() << format("%d ", r_symbolnum);
Fangrui Song523758e2019-04-15 15:31:42 +00001014 if (r_symbolnum == MachO::R_ABS)
Michael Trenta1703b12017-12-15 17:57:40 +00001015 outs() << "R_ABS\n";
1016 else {
1017 // in this case, r_symbolnum is actually a 1-based section number
1018 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
1019 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
Fangrui Song523758e2019-04-15 15:31:42 +00001020 object::DataRefImpl DRI;
Michael Trenta1703b12017-12-15 17:57:40 +00001021 DRI.d.a = r_symbolnum-1;
1022 StringRef SegName = O->getSectionFinalSegmentName(DRI);
Fangrui Song8be28cd2019-05-02 10:32:03 +00001023 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1024 outs() << "(" << SegName << "," << *NameOrErr << ")\n";
Michael Trenta1703b12017-12-15 17:57:40 +00001025 else
Fangrui Song8be28cd2019-05-02 10:32:03 +00001026 outs() << "(?,?)\n";
Michael Trenta1703b12017-12-15 17:57:40 +00001027 }
1028 else {
1029 outs() << "(?,?)\n";
1030 }
1031 }
1032 }
1033 }
1034 if (cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +00001035 (r_type == MachO::ARM_RELOC_HALF ||
1036 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
Michael Trenta1703b12017-12-15 17:57:40 +00001037 previous_arm_half = true;
1038 else
1039 previous_arm_half = false;
1040 }
1041 else {
1042 // plain: address pcrel length extern type scattered symbolnum/section
1043 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
1044 (unsigned int)r_address, r_pcrel, r_length, r_extern,
1045 r_type, r_symbolnum);
1046 }
1047 }
1048 }
1049}
1050
1051static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1052 const uint64_t cputype = O->getHeader().cputype;
1053 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1054 if (Dysymtab.nextrel != 0) {
1055 outs() << "External relocation information " << Dysymtab.nextrel
1056 << " entries";
1057 outs() << "\naddress pcrel length extern type scattered "
1058 "symbolnum/value\n";
1059 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1060 verbose);
1061 }
1062 if (Dysymtab.nlocrel != 0) {
1063 outs() << format("Local relocation information %u entries",
1064 Dysymtab.nlocrel);
1065 outs() << "\naddress pcrel length extern type scattered "
1066 "symbolnum/value\n";
1067 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1068 verbose);
1069 }
1070 for (const auto &Load : O->load_commands()) {
1071 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1072 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1073 for (unsigned J = 0; J < Seg.nsects; ++J) {
1074 const MachO::section_64 Sec = O->getSection64(Load, J);
1075 if (Sec.nreloc != 0) {
1076 DataRefImpl DRI;
1077 DRI.d.a = J;
1078 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
Fangrui Song8be28cd2019-05-02 10:32:03 +00001079 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1080 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1081 << format(") %u entries", Sec.nreloc);
1082 else
Michael Trenta1703b12017-12-15 17:57:40 +00001083 outs() << "Relocation information (" << SegName << ",?) "
1084 << format("%u entries", Sec.nreloc);
Michael Trenta1703b12017-12-15 17:57:40 +00001085 outs() << "\naddress pcrel length extern type scattered "
1086 "symbolnum/value\n";
1087 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1088 O->section_rel_end(DRI), cputype, verbose);
1089 }
1090 }
1091 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1092 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1093 for (unsigned J = 0; J < Seg.nsects; ++J) {
1094 const MachO::section Sec = O->getSection(Load, J);
1095 if (Sec.nreloc != 0) {
1096 DataRefImpl DRI;
1097 DRI.d.a = J;
1098 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
Fangrui Song8be28cd2019-05-02 10:32:03 +00001099 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1100 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1101 << format(") %u entries", Sec.nreloc);
1102 else
Michael Trenta1703b12017-12-15 17:57:40 +00001103 outs() << "Relocation information (" << SegName << ",?) "
1104 << format("%u entries", Sec.nreloc);
Michael Trenta1703b12017-12-15 17:57:40 +00001105 outs() << "\naddress pcrel length extern type scattered "
1106 "symbolnum/value\n";
1107 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1108 O->section_rel_end(DRI), cputype, verbose);
1109 }
1110 }
1111 }
1112 }
1113}
1114
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001115static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1116 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1117 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1118 outs() << "Data in code table (" << nentries << " entries)\n";
1119 outs() << "offset length kind\n";
1120 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1121 ++DI) {
1122 uint32_t Offset;
1123 DI->getOffset(Offset);
1124 outs() << format("0x%08" PRIx32, Offset) << " ";
1125 uint16_t Length;
1126 DI->getLength(Length);
1127 outs() << format("%6u", Length) << " ";
1128 uint16_t Kind;
1129 DI->getKind(Kind);
1130 if (verbose) {
1131 switch (Kind) {
1132 case MachO::DICE_KIND_DATA:
1133 outs() << "DATA";
1134 break;
1135 case MachO::DICE_KIND_JUMP_TABLE8:
1136 outs() << "JUMP_TABLE8";
1137 break;
1138 case MachO::DICE_KIND_JUMP_TABLE16:
1139 outs() << "JUMP_TABLE16";
1140 break;
1141 case MachO::DICE_KIND_JUMP_TABLE32:
1142 outs() << "JUMP_TABLE32";
1143 break;
1144 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1145 outs() << "ABS_JUMP_TABLE32";
1146 break;
1147 default:
1148 outs() << format("0x%04" PRIx32, Kind);
1149 break;
1150 }
1151 } else
1152 outs() << format("0x%04" PRIx32, Kind);
1153 outs() << "\n";
1154 }
1155}
1156
Kevin Enderby9a509442015-01-27 21:28:24 +00001157static void PrintLinkOptHints(MachOObjectFile *O) {
1158 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1159 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1160 uint32_t nloh = LohLC.datasize;
1161 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1162 for (uint32_t i = 0; i < nloh;) {
1163 unsigned n;
1164 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1165 i += n;
1166 outs() << " identifier " << identifier << " ";
1167 if (i >= nloh)
1168 return;
1169 switch (identifier) {
1170 case 1:
1171 outs() << "AdrpAdrp\n";
1172 break;
1173 case 2:
1174 outs() << "AdrpLdr\n";
1175 break;
1176 case 3:
1177 outs() << "AdrpAddLdr\n";
1178 break;
1179 case 4:
1180 outs() << "AdrpLdrGotLdr\n";
1181 break;
1182 case 5:
1183 outs() << "AdrpAddStr\n";
1184 break;
1185 case 6:
1186 outs() << "AdrpLdrGotStr\n";
1187 break;
1188 case 7:
1189 outs() << "AdrpAdd\n";
1190 break;
1191 case 8:
1192 outs() << "AdrpLdrGot\n";
1193 break;
1194 default:
1195 outs() << "Unknown identifier value\n";
1196 break;
1197 }
1198 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1199 i += n;
1200 outs() << " narguments " << narguments << "\n";
1201 if (i >= nloh)
1202 return;
1203
1204 for (uint32_t j = 0; j < narguments; j++) {
1205 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1206 i += n;
1207 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1208 if (i >= nloh)
1209 return;
1210 }
1211 }
1212}
1213
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001214static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001215 unsigned Index = 0;
1216 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001217 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1218 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1219 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1220 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1221 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1222 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1223 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1224 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1225 if (dl.dylib.name < dl.cmdsize) {
1226 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1227 if (JustId)
1228 outs() << p << "\n";
1229 else {
1230 outs() << "\t" << p;
1231 outs() << " (compatibility version "
1232 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1233 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1234 << (dl.dylib.compatibility_version & 0xff) << ",";
1235 outs() << " current version "
1236 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1237 << ((dl.dylib.current_version >> 8) & 0xff) << "."
Michael Trentc2885de2019-06-18 22:20:10 +00001238 << (dl.dylib.current_version & 0xff);
1239 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1240 outs() << ", weak";
1241 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1242 outs() << ", reexport";
1243 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1244 outs() << ", upward";
1245 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1246 outs() << ", lazy";
1247 outs() << ")\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001248 }
1249 } else {
1250 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1251 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1252 outs() << "LC_ID_DYLIB ";
1253 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1254 outs() << "LC_LOAD_DYLIB ";
1255 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1256 outs() << "LC_LOAD_WEAK_DYLIB ";
1257 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1258 outs() << "LC_LAZY_LOAD_DYLIB ";
1259 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1260 outs() << "LC_REEXPORT_DYLIB ";
1261 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1262 outs() << "LC_LOAD_UPWARD_DYLIB ";
1263 else
1264 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001265 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001266 }
1267 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001268 }
1269}
1270
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001271typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1272
1273static void CreateSymbolAddressMap(MachOObjectFile *O,
1274 SymbolAddressMap *AddrMap) {
1275 // Create a map of symbol addresses to symbol names.
Fangrui Songe7834bd2019-04-07 08:19:55 +00001276 const StringRef FileName = O->getFileName();
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001277 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00001278 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001279 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1280 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00001281 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00001282 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
Kevin Enderby846c0002015-04-16 17:19:59 +00001283 if (!SymName.startswith(".objc"))
1284 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001285 }
1286 }
1287}
1288
1289// GuessSymbolName is passed the address of what might be a symbol and a
1290// pointer to the SymbolAddressMap. It returns the name of a symbol
1291// with that address or nullptr if no symbol is found with that address.
1292static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1293 const char *SymbolName = nullptr;
1294 // A DenseMap can't lookup up some values.
1295 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1296 StringRef name = AddrMap->lookup(value);
1297 if (!name.empty())
1298 SymbolName = name.data();
1299 }
1300 return SymbolName;
1301}
1302
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001303static void DumpCstringChar(const char c) {
1304 char p[2];
1305 p[0] = c;
1306 p[1] = '\0';
1307 outs().write_escaped(p);
1308}
1309
Kevin Enderby10ba0412015-02-04 21:38:42 +00001310static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1311 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001312 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +00001313 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001314 if (print_addresses) {
1315 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001316 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001317 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001318 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001319 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001320 for (; i < sect_size && sect[i] != '\0'; i++)
1321 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001322 if (i < sect_size && sect[i] == '\0')
1323 outs() << "\n";
1324 }
1325}
1326
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001327static void DumpLiteral4(uint32_t l, float f) {
1328 outs() << format("0x%08" PRIx32, l);
1329 if ((l & 0x7f800000) != 0x7f800000)
1330 outs() << format(" (%.16e)\n", f);
1331 else {
1332 if (l == 0x7f800000)
1333 outs() << " (+Infinity)\n";
1334 else if (l == 0xff800000)
1335 outs() << " (-Infinity)\n";
1336 else if ((l & 0x00400000) == 0x00400000)
1337 outs() << " (non-signaling Not-a-Number)\n";
1338 else
1339 outs() << " (signaling Not-a-Number)\n";
1340 }
1341}
1342
1343static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1344 uint32_t sect_size, uint64_t sect_addr,
1345 bool print_addresses) {
1346 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1347 if (print_addresses) {
1348 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001349 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001350 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001351 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001352 }
1353 float f;
1354 memcpy(&f, sect + i, sizeof(float));
1355 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1356 sys::swapByteOrder(f);
1357 uint32_t l;
1358 memcpy(&l, sect + i, sizeof(uint32_t));
1359 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1360 sys::swapByteOrder(l);
1361 DumpLiteral4(l, f);
1362 }
1363}
1364
1365static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1366 double d) {
1367 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1368 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001369 Hi = (O->isLittleEndian()) ? l1 : l0;
1370 Lo = (O->isLittleEndian()) ? l0 : l1;
1371
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001372 // Hi is the high word, so this is equivalent to if(isfinite(d))
1373 if ((Hi & 0x7ff00000) != 0x7ff00000)
1374 outs() << format(" (%.16e)\n", d);
1375 else {
1376 if (Hi == 0x7ff00000 && Lo == 0)
1377 outs() << " (+Infinity)\n";
1378 else if (Hi == 0xfff00000 && Lo == 0)
1379 outs() << " (-Infinity)\n";
1380 else if ((Hi & 0x00080000) == 0x00080000)
1381 outs() << " (non-signaling Not-a-Number)\n";
1382 else
1383 outs() << " (signaling Not-a-Number)\n";
1384 }
1385}
1386
1387static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1388 uint32_t sect_size, uint64_t sect_addr,
1389 bool print_addresses) {
1390 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1391 if (print_addresses) {
1392 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001393 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001394 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001395 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001396 }
1397 double d;
1398 memcpy(&d, sect + i, sizeof(double));
1399 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1400 sys::swapByteOrder(d);
1401 uint32_t l0, l1;
1402 memcpy(&l0, sect + i, sizeof(uint32_t));
1403 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1404 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1405 sys::swapByteOrder(l0);
1406 sys::swapByteOrder(l1);
1407 }
1408 DumpLiteral8(O, l0, l1, d);
1409 }
1410}
1411
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001412static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1413 outs() << format("0x%08" PRIx32, l0) << " ";
1414 outs() << format("0x%08" PRIx32, l1) << " ";
1415 outs() << format("0x%08" PRIx32, l2) << " ";
1416 outs() << format("0x%08" PRIx32, l3) << "\n";
1417}
1418
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001419static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1420 uint32_t sect_size, uint64_t sect_addr,
1421 bool print_addresses) {
1422 for (uint32_t i = 0; i < sect_size; i += 16) {
1423 if (print_addresses) {
1424 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001425 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001426 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001427 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001428 }
1429 uint32_t l0, l1, l2, l3;
1430 memcpy(&l0, sect + i, sizeof(uint32_t));
1431 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1432 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1433 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1434 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1435 sys::swapByteOrder(l0);
1436 sys::swapByteOrder(l1);
1437 sys::swapByteOrder(l2);
1438 sys::swapByteOrder(l3);
1439 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001440 DumpLiteral16(l0, l1, l2, l3);
1441 }
1442}
1443
1444static void DumpLiteralPointerSection(MachOObjectFile *O,
1445 const SectionRef &Section,
1446 const char *sect, uint32_t sect_size,
1447 uint64_t sect_addr,
1448 bool print_addresses) {
1449 // Collect the literal sections in this Mach-O file.
1450 std::vector<SectionRef> LiteralSections;
1451 for (const SectionRef &Section : O->sections()) {
1452 DataRefImpl Ref = Section.getRawDataRefImpl();
1453 uint32_t section_type;
1454 if (O->is64Bit()) {
1455 const MachO::section_64 Sec = O->getSection64(Ref);
1456 section_type = Sec.flags & MachO::SECTION_TYPE;
1457 } else {
1458 const MachO::section Sec = O->getSection(Ref);
1459 section_type = Sec.flags & MachO::SECTION_TYPE;
1460 }
1461 if (section_type == MachO::S_CSTRING_LITERALS ||
1462 section_type == MachO::S_4BYTE_LITERALS ||
1463 section_type == MachO::S_8BYTE_LITERALS ||
1464 section_type == MachO::S_16BYTE_LITERALS)
1465 LiteralSections.push_back(Section);
1466 }
1467
1468 // Set the size of the literal pointer.
1469 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1470
Eric Christopher572e03a2015-06-19 01:53:21 +00001471 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001472 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1473 for (const RelocationRef &Reloc : Section.relocations()) {
1474 DataRefImpl Rel;
1475 MachO::any_relocation_info RE;
1476 bool isExtern = false;
1477 Rel = Reloc.getRawDataRefImpl();
1478 RE = O->getRelocation(Rel);
1479 isExtern = O->getPlainRelocationExternal(RE);
1480 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001481 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001482 symbol_iterator RelocSym = Reloc.getSymbol();
1483 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1484 }
1485 }
1486 array_pod_sort(Relocs.begin(), Relocs.end());
1487
1488 // Dump each literal pointer.
1489 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1490 if (print_addresses) {
1491 if (O->is64Bit())
1492 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1493 else
1494 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1495 }
1496 uint64_t lp;
1497 if (O->is64Bit()) {
1498 memcpy(&lp, sect + i, sizeof(uint64_t));
1499 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1500 sys::swapByteOrder(lp);
1501 } else {
1502 uint32_t li;
1503 memcpy(&li, sect + i, sizeof(uint32_t));
1504 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1505 sys::swapByteOrder(li);
1506 lp = li;
1507 }
1508
1509 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001510 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1511 return P.first == i;
1512 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001513 if (Reloc != Relocs.end()) {
1514 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001515 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1516 outs() << "external relocation entry for symbol:" << SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001517 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001518 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001519
1520 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001521 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1522 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1523 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001524 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001525 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001526 continue;
1527 }
1528
1529 uint64_t SectAddress = Sect->getAddress();
1530 uint64_t SectSize = Sect->getSize();
1531
1532 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00001533 Expected<StringRef> SectNameOrErr = Sect->getName();
1534 if (SectNameOrErr)
1535 SectName = *SectNameOrErr;
1536 else
1537 consumeError(SectNameOrErr.takeError());
1538
David Blaikie33dd45d02015-03-23 18:39:02 +00001539 DataRefImpl Ref = Sect->getRawDataRefImpl();
1540 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1541 outs() << SegmentName << ":" << SectName << ":";
1542
1543 uint32_t section_type;
1544 if (O->is64Bit()) {
1545 const MachO::section_64 Sec = O->getSection64(Ref);
1546 section_type = Sec.flags & MachO::SECTION_TYPE;
1547 } else {
1548 const MachO::section Sec = O->getSection(Ref);
1549 section_type = Sec.flags & MachO::SECTION_TYPE;
1550 }
1551
Fangrui Songe1833402019-05-16 13:24:04 +00001552 StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1553
David Blaikie33dd45d02015-03-23 18:39:02 +00001554 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1555
1556 switch (section_type) {
1557 case MachO::S_CSTRING_LITERALS:
1558 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1559 i++) {
1560 DumpCstringChar(Contents[i]);
1561 }
1562 outs() << "\n";
1563 break;
1564 case MachO::S_4BYTE_LITERALS:
1565 float f;
1566 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1567 uint32_t l;
1568 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1569 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1570 sys::swapByteOrder(f);
1571 sys::swapByteOrder(l);
1572 }
1573 DumpLiteral4(l, f);
1574 break;
1575 case MachO::S_8BYTE_LITERALS: {
1576 double d;
1577 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1578 uint32_t l0, l1;
1579 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1580 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1581 sizeof(uint32_t));
1582 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1583 sys::swapByteOrder(f);
1584 sys::swapByteOrder(l0);
1585 sys::swapByteOrder(l1);
1586 }
1587 DumpLiteral8(O, l0, l1, d);
1588 break;
1589 }
1590 case MachO::S_16BYTE_LITERALS: {
1591 uint32_t l0, l1, l2, l3;
1592 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1593 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1594 sizeof(uint32_t));
1595 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1596 sizeof(uint32_t));
1597 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1598 sizeof(uint32_t));
1599 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1600 sys::swapByteOrder(l0);
1601 sys::swapByteOrder(l1);
1602 sys::swapByteOrder(l2);
1603 sys::swapByteOrder(l3);
1604 }
1605 DumpLiteral16(l0, l1, l2, l3);
1606 break;
1607 }
1608 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001609 }
1610}
1611
Kevin Enderby85b7a662018-03-20 20:29:52 +00001612static void DumpInitTermPointerSection(MachOObjectFile *O,
1613 const SectionRef &Section,
1614 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001615 uint32_t sect_size, uint64_t sect_addr,
1616 SymbolAddressMap *AddrMap,
1617 bool verbose) {
1618 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001619 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001620
1621 // Collect the external relocation symbols for the pointers.
1622 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1623 for (const RelocationRef &Reloc : Section.relocations()) {
1624 DataRefImpl Rel;
1625 MachO::any_relocation_info RE;
1626 bool isExtern = false;
1627 Rel = Reloc.getRawDataRefImpl();
1628 RE = O->getRelocation(Rel);
1629 isExtern = O->getPlainRelocationExternal(RE);
1630 if (isExtern) {
1631 uint64_t RelocOffset = Reloc.getOffset();
1632 symbol_iterator RelocSym = Reloc.getSymbol();
1633 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1634 }
1635 }
1636 array_pod_sort(Relocs.begin(), Relocs.end());
1637
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001638 for (uint32_t i = 0; i < sect_size; i += stride) {
1639 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001640 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001641 if (O->is64Bit()) {
1642 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1643 uint64_t pointer_value;
1644 memcpy(&pointer_value, sect + i, stride);
1645 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1646 sys::swapByteOrder(pointer_value);
1647 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001648 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001649 } else {
1650 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1651 uint32_t pointer_value;
1652 memcpy(&pointer_value, sect + i, stride);
1653 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1654 sys::swapByteOrder(pointer_value);
1655 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001656 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001657 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001658 if (verbose) {
1659 // First look for an external relocation entry for this pointer.
1660 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1661 return P.first == i;
1662 });
1663 if (Reloc != Relocs.end()) {
1664 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001665 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
Kevin Enderby85b7a662018-03-20 20:29:52 +00001666 } else {
1667 SymbolName = GuessSymbolName(p, AddrMap);
1668 if (SymbolName)
1669 outs() << " " << SymbolName;
1670 }
1671 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001672 outs() << "\n";
1673 }
1674}
1675
1676static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1677 uint32_t size, uint64_t addr) {
1678 uint32_t cputype = O->getHeader().cputype;
1679 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1680 uint32_t j;
1681 for (uint32_t i = 0; i < size; i += j, addr += j) {
1682 if (O->is64Bit())
1683 outs() << format("%016" PRIx64, addr) << "\t";
1684 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001685 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001686 for (j = 0; j < 16 && i + j < size; j++) {
1687 uint8_t byte_word = *(sect + i + j);
1688 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1689 }
1690 outs() << "\n";
1691 }
1692 } else {
1693 uint32_t j;
1694 for (uint32_t i = 0; i < size; i += j, addr += j) {
1695 if (O->is64Bit())
1696 outs() << format("%016" PRIx64, addr) << "\t";
1697 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001698 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001699 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1700 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001701 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001702 uint32_t long_word;
1703 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1704 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1705 sys::swapByteOrder(long_word);
1706 outs() << format("%08" PRIx32, long_word) << " ";
1707 } else {
1708 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001709 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001710 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1711 }
1712 }
1713 }
1714 outs() << "\n";
1715 }
1716 }
1717}
1718
Kevin Enderby95df54c2015-02-04 01:01:38 +00001719static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1720 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001721static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1722 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001723#ifdef HAVE_LIBXAR
1724static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1725 uint32_t size, bool verbose,
1726 bool PrintXarHeader, bool PrintXarFileHeaders,
1727 std::string XarMemberName);
1728#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001729
1730static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1731 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001732 SymbolAddressMap AddrMap;
1733 if (verbose)
1734 CreateSymbolAddressMap(O, &AddrMap);
1735
Colin LeMahieufcc32762015-07-29 19:08:10 +00001736 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1737 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001738 std::pair<StringRef, StringRef> DumpSegSectName;
1739 DumpSegSectName = DumpSection.split(',');
1740 StringRef DumpSegName, DumpSectName;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001741 if (!DumpSegSectName.second.empty()) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001742 DumpSegName = DumpSegSectName.first;
1743 DumpSectName = DumpSegSectName.second;
1744 } else {
1745 DumpSegName = "";
1746 DumpSectName = DumpSegSectName.first;
1747 }
1748 for (const SectionRef &Section : O->sections()) {
1749 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00001750 Expected<StringRef> SecNameOrErr = Section.getName();
1751 if (SecNameOrErr)
1752 SectName = *SecNameOrErr;
1753 else
1754 consumeError(SecNameOrErr.takeError());
1755
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001756 DataRefImpl Ref = Section.getRawDataRefImpl();
1757 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1758 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1759 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001760
Kevin Enderby95df54c2015-02-04 01:01:38 +00001761 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001762 if (O->is64Bit()) {
1763 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001764 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001765
1766 } else {
1767 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001768 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001769 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001770 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001771
Fangrui Songe1833402019-05-16 13:24:04 +00001772 StringRef BytesStr =
1773 unwrapOrError(Section.getContents(), O->getFileName());
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001774 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1775 uint32_t sect_size = BytesStr.size();
1776 uint64_t sect_addr = Section.getAddress();
1777
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001778 outs() << "Contents of (" << SegName << "," << SectName
1779 << ") section\n";
1780
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001781 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001782 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1783 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1784 DisassembleMachO(Filename, O, SegName, SectName);
1785 continue;
1786 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001787 if (SegName == "__TEXT" && SectName == "__info_plist") {
1788 outs() << sect;
1789 continue;
1790 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001791 if (SegName == "__OBJC" && SectName == "__protocol") {
1792 DumpProtocolSection(O, sect, sect_size, sect_addr);
1793 continue;
1794 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001795#ifdef HAVE_LIBXAR
1796 if (SegName == "__LLVM" && SectName == "__bundle") {
1797 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1798 ArchiveHeaders, "");
1799 continue;
1800 }
1801#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001802 switch (section_type) {
1803 case MachO::S_REGULAR:
1804 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1805 break;
1806 case MachO::S_ZEROFILL:
1807 outs() << "zerofill section and has no contents in the file\n";
1808 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001809 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001810 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001811 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001812 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001813 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001814 break;
1815 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001816 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001817 break;
1818 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001819 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1820 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001821 case MachO::S_LITERAL_POINTERS:
1822 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001823 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001824 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001825 case MachO::S_MOD_INIT_FUNC_POINTERS:
1826 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001827 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1828 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001829 break;
1830 default:
1831 outs() << "Unknown section type ("
1832 << format("0x%08" PRIx32, section_type) << ")\n";
1833 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1834 break;
1835 }
1836 } else {
1837 if (section_type == MachO::S_ZEROFILL)
1838 outs() << "zerofill section and has no contents in the file\n";
1839 else
1840 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1841 }
1842 }
1843 }
1844 }
1845}
1846
Kevin Enderbycd66be52015-03-11 22:06:32 +00001847static void DumpInfoPlistSectionContents(StringRef Filename,
1848 MachOObjectFile *O) {
1849 for (const SectionRef &Section : O->sections()) {
1850 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00001851 Expected<StringRef> SecNameOrErr = Section.getName();
1852 if (SecNameOrErr)
1853 SectName = *SecNameOrErr;
1854 else
1855 consumeError(SecNameOrErr.takeError());
1856
Kevin Enderbycd66be52015-03-11 22:06:32 +00001857 DataRefImpl Ref = Section.getRawDataRefImpl();
1858 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1859 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001860 if (!NoLeadingHeaders)
1861 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Fangrui Songe1833402019-05-16 13:24:04 +00001862 StringRef BytesStr =
1863 unwrapOrError(Section.getContents(), O->getFileName());
Kevin Enderbycd66be52015-03-11 22:06:32 +00001864 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001865 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001866 return;
1867 }
1868 }
1869}
1870
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001871// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1872// and if it is and there is a list of architecture flags is specified then
1873// check to make sure this Mach-O file is one of those architectures or all
1874// architectures were specified. If not then an error is generated and this
1875// routine returns false. Else it returns true.
1876static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001877 auto *MachO = dyn_cast<MachOObjectFile>(O);
1878
1879 if (!MachO || ArchAll || ArchFlags.empty())
1880 return true;
1881
1882 MachO::mach_header H;
1883 MachO::mach_header_64 H_64;
1884 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001885 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001886 if (MachO->is64Bit()) {
1887 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001888 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1889 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001890 } else {
1891 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001892 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1893 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001894 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001895 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001896 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001897 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001898 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001899 WithColor::error(errs(), "llvm-objdump")
1900 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001901 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001902 }
1903 return true;
1904}
1905
Kevin Enderby0fc11822015-04-01 20:57:01 +00001906static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1907
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001908// ProcessMachO() is passed a single opened Mach-O file, which may be an
1909// archive member and or in a slice of a universal file. It prints the
1910// the file name and header info and then processes it according to the
1911// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001912static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001913 StringRef ArchiveMemberName = StringRef(),
1914 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001915 // If we are doing some processing here on the Mach-O file print the header
1916 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001917 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001918 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1919 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1920 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001921 (!FilterSections.empty())) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001922 if (!NoLeadingHeaders) {
1923 outs() << Name;
1924 if (!ArchiveMemberName.empty())
1925 outs() << '(' << ArchiveMemberName << ')';
1926 if (!ArchitectureName.empty())
1927 outs() << " (architecture " << ArchitectureName << ")";
1928 outs() << ":\n";
1929 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001930 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001931 // To use the report_error() form with an ArchiveName and FileName set
1932 // these up based on what is passed for Name and ArchiveMemberName.
1933 StringRef ArchiveName;
1934 StringRef FileName;
1935 if (!ArchiveMemberName.empty()) {
1936 ArchiveName = Name;
1937 FileName = ArchiveMemberName;
1938 } else {
1939 ArchiveName = StringRef();
1940 FileName = Name;
1941 }
1942
1943 // If we need the symbol table to do the operation then check it here to
1944 // produce a good error message as to where the Mach-O file comes from in
1945 // the error message.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001946 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001947 if (Error Err = MachOOF->checkSymbolTable())
George Rimarf0f38d92019-08-21 11:07:31 +00001948 reportError(std::move(Err), ArchiveName, FileName, ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00001949
Michael Trent7e660212019-01-15 20:41:30 +00001950 if (DisassembleAll) {
1951 for (const SectionRef &Section : MachOOF->sections()) {
1952 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00001953 if (Expected<StringRef> NameOrErr = Section.getName())
1954 SectName = *NameOrErr;
1955 else
1956 consumeError(NameOrErr.takeError());
1957
Michael Trent7e660212019-01-15 20:41:30 +00001958 if (SectName.equals("__text")) {
1959 DataRefImpl Ref = Section.getRawDataRefImpl();
1960 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1961 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1962 }
1963 }
1964 }
1965 else if (Disassemble) {
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001966 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001967 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001968 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1969 else
1970 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1971 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001972 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001973 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001974 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001975 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001976 if (LinkOptHints)
1977 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001978 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001979 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001980 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001981 printSectionHeaders(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001982 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001983 printSectionContents(MachOOF);
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001984 if (!FilterSections.empty())
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001985 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001986 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001987 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001988 if (DylibsUsed)
1989 PrintDylibs(MachOOF, false);
1990 if (DylibId)
1991 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001992 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001993 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001994 if (UnwindInfo)
1995 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001996 if (PrivateHeaders) {
1997 printMachOFileHeader(MachOOF);
1998 printMachOLoadCommands(MachOOF);
1999 }
2000 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002001 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00002002 if (ObjcMetaData)
2003 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002004 if (ExportsTrie)
2005 printExportsTrie(MachOOF);
2006 if (Rebase)
2007 printRebaseTable(MachOOF);
2008 if (Bind)
2009 printBindTable(MachOOF);
2010 if (LazyBind)
2011 printLazyBindTable(MachOOF);
2012 if (WeakBind)
2013 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002014
2015 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00002016 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002017 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002018 DIDumpOptions DumpOpts;
2019 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002020 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002021 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002022}
2023
Kevin Enderby131d1772015-01-09 19:22:37 +00002024// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2025static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2026 outs() << " cputype (" << cputype << ")\n";
2027 outs() << " cpusubtype (" << cpusubtype << ")\n";
2028}
2029
2030// printCPUType() helps print_fat_headers by printing the cputype and
2031// pusubtype (symbolically for the one's it knows about).
2032static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2033 switch (cputype) {
2034 case MachO::CPU_TYPE_I386:
2035 switch (cpusubtype) {
2036 case MachO::CPU_SUBTYPE_I386_ALL:
2037 outs() << " cputype CPU_TYPE_I386\n";
2038 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
2039 break;
2040 default:
2041 printUnknownCPUType(cputype, cpusubtype);
2042 break;
2043 }
2044 break;
2045 case MachO::CPU_TYPE_X86_64:
2046 switch (cpusubtype) {
2047 case MachO::CPU_SUBTYPE_X86_64_ALL:
2048 outs() << " cputype CPU_TYPE_X86_64\n";
2049 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2050 break;
2051 case MachO::CPU_SUBTYPE_X86_64_H:
2052 outs() << " cputype CPU_TYPE_X86_64\n";
2053 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
2054 break;
2055 default:
2056 printUnknownCPUType(cputype, cpusubtype);
2057 break;
2058 }
2059 break;
2060 case MachO::CPU_TYPE_ARM:
2061 switch (cpusubtype) {
2062 case MachO::CPU_SUBTYPE_ARM_ALL:
2063 outs() << " cputype CPU_TYPE_ARM\n";
2064 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2065 break;
2066 case MachO::CPU_SUBTYPE_ARM_V4T:
2067 outs() << " cputype CPU_TYPE_ARM\n";
2068 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2069 break;
2070 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2071 outs() << " cputype CPU_TYPE_ARM\n";
2072 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2073 break;
2074 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2075 outs() << " cputype CPU_TYPE_ARM\n";
2076 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2077 break;
2078 case MachO::CPU_SUBTYPE_ARM_V6:
2079 outs() << " cputype CPU_TYPE_ARM\n";
2080 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2081 break;
2082 case MachO::CPU_SUBTYPE_ARM_V6M:
2083 outs() << " cputype CPU_TYPE_ARM\n";
2084 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2085 break;
2086 case MachO::CPU_SUBTYPE_ARM_V7:
2087 outs() << " cputype CPU_TYPE_ARM\n";
2088 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2089 break;
2090 case MachO::CPU_SUBTYPE_ARM_V7EM:
2091 outs() << " cputype CPU_TYPE_ARM\n";
2092 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2093 break;
2094 case MachO::CPU_SUBTYPE_ARM_V7K:
2095 outs() << " cputype CPU_TYPE_ARM\n";
2096 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2097 break;
2098 case MachO::CPU_SUBTYPE_ARM_V7M:
2099 outs() << " cputype CPU_TYPE_ARM\n";
2100 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2101 break;
2102 case MachO::CPU_SUBTYPE_ARM_V7S:
2103 outs() << " cputype CPU_TYPE_ARM\n";
2104 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2105 break;
2106 default:
2107 printUnknownCPUType(cputype, cpusubtype);
2108 break;
2109 }
2110 break;
2111 case MachO::CPU_TYPE_ARM64:
2112 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2113 case MachO::CPU_SUBTYPE_ARM64_ALL:
2114 outs() << " cputype CPU_TYPE_ARM64\n";
2115 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2116 break;
Shoaib Meenai867131a2019-04-08 21:37:08 +00002117 case MachO::CPU_SUBTYPE_ARM64E:
2118 outs() << " cputype CPU_TYPE_ARM64\n";
2119 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2120 break;
Kevin Enderby131d1772015-01-09 19:22:37 +00002121 default:
2122 printUnknownCPUType(cputype, cpusubtype);
2123 break;
2124 }
2125 break;
Tim Northoverff6875a2019-05-14 11:25:44 +00002126 case MachO::CPU_TYPE_ARM64_32:
2127 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2128 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2129 outs() << " cputype CPU_TYPE_ARM64_32\n";
2130 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2131 break;
2132 default:
2133 printUnknownCPUType(cputype, cpusubtype);
2134 break;
2135 }
2136 break;
Kevin Enderby131d1772015-01-09 19:22:37 +00002137 default:
2138 printUnknownCPUType(cputype, cpusubtype);
2139 break;
2140 }
2141}
2142
2143static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2144 bool verbose) {
2145 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00002146 if (verbose) {
2147 if (UB->getMagic() == MachO::FAT_MAGIC)
2148 outs() << "fat_magic FAT_MAGIC\n";
2149 else // UB->getMagic() == MachO::FAT_MAGIC_64
2150 outs() << "fat_magic FAT_MAGIC_64\n";
2151 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00002152 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2153
2154 uint32_t nfat_arch = UB->getNumberOfObjects();
2155 StringRef Buf = UB->getData();
2156 uint64_t size = Buf.size();
2157 uint64_t big_size = sizeof(struct MachO::fat_header) +
2158 nfat_arch * sizeof(struct MachO::fat_arch);
2159 outs() << "nfat_arch " << UB->getNumberOfObjects();
2160 if (nfat_arch == 0)
2161 outs() << " (malformed, contains zero architecture types)\n";
2162 else if (big_size > size)
2163 outs() << " (malformed, architectures past end of file)\n";
2164 else
2165 outs() << "\n";
2166
2167 for (uint32_t i = 0; i < nfat_arch; ++i) {
2168 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2169 uint32_t cputype = OFA.getCPUType();
2170 uint32_t cpusubtype = OFA.getCPUSubType();
2171 outs() << "architecture ";
2172 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2173 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2174 uint32_t other_cputype = other_OFA.getCPUType();
2175 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00002176 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00002177 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00002178 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00002179 outs() << "(illegal duplicate architecture) ";
2180 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00002181 }
Kevin Enderby131d1772015-01-09 19:22:37 +00002182 }
2183 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00002184 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00002185 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2186 } else {
2187 outs() << i << "\n";
2188 outs() << " cputype " << cputype << "\n";
2189 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2190 << "\n";
2191 }
2192 if (verbose &&
2193 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2194 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2195 else
2196 outs() << " capabilities "
2197 << format("0x%" PRIx32,
2198 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2199 outs() << " offset " << OFA.getOffset();
2200 if (OFA.getOffset() > size)
2201 outs() << " (past end of file)";
2202 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2203 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2204 outs() << "\n";
2205 outs() << " size " << OFA.getSize();
2206 big_size = OFA.getOffset() + OFA.getSize();
2207 if (big_size > size)
2208 outs() << " (past end of file)";
2209 outs() << "\n";
2210 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2211 << ")\n";
2212 }
2213}
2214
Kevin Enderby6524bd82016-07-19 20:47:07 +00002215static void printArchiveChild(StringRef Filename, const Archive::Child &C,
George Rimarb232d562019-08-20 13:19:16 +00002216 size_t ChildIndex, bool verbose,
2217 bool print_offset,
Kevin Enderby6524bd82016-07-19 20:47:07 +00002218 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00002219 if (print_offset)
2220 outs() << C.getChildOffset() << "\t";
Fangrui Songe7834bd2019-04-07 08:19:55 +00002221 sys::fs::perms Mode =
George Rimarb232d562019-08-20 13:19:16 +00002222 unwrapOrError(C.getAccessMode(), Filename,
2223 getFileNameForError(C, ChildIndex),
2224 ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002225 if (verbose) {
2226 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2227 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2228 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00002229 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2230 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2231 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2232 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2233 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2234 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2235 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2236 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2237 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00002238 } else {
2239 outs() << format("0%o ", Mode);
2240 }
2241
Fangrui Songe7834bd2019-04-07 08:19:55 +00002242 outs() << format(
2243 "%3d/%-3d %5" PRId64 " ",
George Rimarb232d562019-08-20 13:19:16 +00002244 unwrapOrError(C.getUID(), Filename, getFileNameForError(C, ChildIndex),
2245 ArchitectureName),
2246 unwrapOrError(C.getGID(), Filename, getFileNameForError(C, ChildIndex),
2247 ArchitectureName),
2248 unwrapOrError(C.getRawSize(), Filename,
2249 getFileNameForError(C, ChildIndex), ArchitectureName));
Kevin Enderby13023a12015-01-15 23:19:11 +00002250
2251 StringRef RawLastModified = C.getRawLastModified();
2252 if (verbose) {
2253 unsigned Seconds;
2254 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002255 outs() << "(date: \"" << RawLastModified
2256 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002257 else {
2258 // Since cime(3) returns a 26 character string of the form:
2259 // "Sun Sep 16 01:03:52 1973\n\0"
2260 // just print 24 characters.
2261 time_t t = Seconds;
2262 outs() << format("%.24s ", ctime(&t));
2263 }
2264 } else {
2265 outs() << RawLastModified << " ";
2266 }
2267
2268 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002269 Expected<StringRef> NameOrErr = C.getName();
2270 if (!NameOrErr) {
2271 consumeError(NameOrErr.takeError());
George Rimarb232d562019-08-20 13:19:16 +00002272 outs() << unwrapOrError(C.getRawName(), Filename,
2273 getFileNameForError(C, ChildIndex),
2274 ArchitectureName)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002275 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002276 } else {
2277 StringRef Name = NameOrErr.get();
2278 outs() << Name << "\n";
2279 }
2280 } else {
George Rimarb232d562019-08-20 13:19:16 +00002281 outs() << unwrapOrError(C.getRawName(), Filename,
2282 getFileNameForError(C, ChildIndex),
2283 ArchitectureName)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002284 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002285 }
2286}
2287
Kevin Enderby6524bd82016-07-19 20:47:07 +00002288static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2289 bool print_offset,
2290 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002291 Error Err = Error::success();
George Rimarb232d562019-08-20 13:19:16 +00002292 size_t I = 0;
Lang Hamesfc209622016-07-14 02:24:01 +00002293 for (const auto &C : A->children(Err, false))
George Rimarb232d562019-08-20 13:19:16 +00002294 printArchiveChild(Filename, C, I++, verbose, print_offset,
2295 ArchitectureName);
Kevin Enderby6524bd82016-07-19 20:47:07 +00002296
Lang Hamesfc209622016-07-14 02:24:01 +00002297 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +00002298 reportError(std::move(Err), StringRef(), Filename, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002299}
2300
Dave Lee3fb120f2018-08-03 00:06:38 +00002301static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002302 // Check for -arch all and verifiy the -arch flags are valid.
2303 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2304 if (ArchFlags[i] == "all") {
2305 ArchAll = true;
2306 } else {
2307 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002308 WithColor::error(errs(), "llvm-objdump")
2309 << "unknown architecture named '" + ArchFlags[i] +
2310 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002311 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002312 }
2313 }
2314 }
Dave Lee3fb120f2018-08-03 00:06:38 +00002315 return true;
2316}
2317
2318// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2319// -arch flags selecting just those slices as specified by them and also parses
2320// archive files. Then for each individual Mach-O file ProcessMachO() is
2321// called to process the file based on the command line options.
Fangrui Song523758e2019-04-15 15:31:42 +00002322void parseInputMachO(StringRef Filename) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002323 if (!ValidateArchFlags())
2324 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002325
2326 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002327 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002328 if (!BinaryOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002329 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
George Rimarf0f38d92019-08-21 11:07:31 +00002330 reportError(std::move(E), Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002331 else
2332 outs() << Filename << ": is not an object file\n";
2333 return;
2334 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002335 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00002336
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002337 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2338 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002339 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002340 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2341
Mehdi Amini41af4302016-11-11 04:28:40 +00002342 Error Err = Error::success();
George Rimarb232d562019-08-20 13:19:16 +00002343 unsigned I = -1;
Lang Hamesfc209622016-07-14 02:24:01 +00002344 for (auto &C : A->children(Err)) {
George Rimarb232d562019-08-20 13:19:16 +00002345 ++I;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002346 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2347 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002348 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
George Rimarf0f38d92019-08-21 11:07:31 +00002349 reportError(std::move(E), Filename, getFileNameForError(C, I));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002350 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002351 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002352 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2353 if (!checkMachOAndArchFlags(O, Filename))
2354 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002355 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002356 }
2357 }
Lang Hamesfc209622016-07-14 02:24:01 +00002358 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +00002359 reportError(std::move(Err), Filename);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002360 return;
2361 }
2362 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
George Rimar73a27232019-01-15 09:19:18 +00002363 parseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002364 return;
2365 }
2366 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2367 if (!checkMachOAndArchFlags(O, Filename))
2368 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002369 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002370 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002371 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002372 WithColor::error(errs(), "llvm-objdump")
2373 << Filename << "': "
2374 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002375 return;
2376 }
2377 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002378}
2379
Fangrui Song523758e2019-04-15 15:31:42 +00002380void parseInputMachO(MachOUniversalBinary *UB) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002381 if (!ValidateArchFlags())
2382 return;
2383
2384 auto Filename = UB->getFileName();
2385
2386 if (UniversalHeaders)
2387 printMachOUniversalHeaders(UB, !NonVerbose);
2388
2389 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002390 if (!ArchAll && !ArchFlags.empty()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002391 // Look for a slice in the universal binary that matches each ArchFlag.
2392 bool ArchFound;
2393 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2394 ArchFound = false;
2395 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2396 E = UB->end_objects();
2397 I != E; ++I) {
2398 if (ArchFlags[i] == I->getArchFlagName()) {
2399 ArchFound = true;
2400 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2401 I->getAsObjectFile();
2402 std::string ArchitectureName = "";
2403 if (ArchFlags.size() > 1)
2404 ArchitectureName = I->getArchFlagName();
2405 if (ObjOrErr) {
2406 ObjectFile &O = *ObjOrErr.get();
2407 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2408 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002409 } else if (Error E = isNotObjectErrorInvalidFileType(
2410 ObjOrErr.takeError())) {
George Rimarf0f38d92019-08-21 11:07:31 +00002411 reportError(std::move(E), Filename, StringRef(), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002412 continue;
2413 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002414 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002415 std::unique_ptr<Archive> &A = *AOrErr;
2416 outs() << "Archive : " << Filename;
2417 if (!ArchitectureName.empty())
2418 outs() << " (architecture " << ArchitectureName << ")";
2419 outs() << "\n";
2420 if (ArchiveHeaders)
2421 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2422 ArchiveMemberOffsets, ArchitectureName);
2423 Error Err = Error::success();
George Rimarb232d562019-08-20 13:19:16 +00002424 unsigned I = -1;
Dave Lee3fb120f2018-08-03 00:06:38 +00002425 for (auto &C : A->children(Err)) {
George Rimarb232d562019-08-20 13:19:16 +00002426 ++I;
Dave Lee3fb120f2018-08-03 00:06:38 +00002427 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2428 if (!ChildOrErr) {
George Rimarb232d562019-08-20 13:19:16 +00002429 if (Error E =
2430 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
George Rimarf0f38d92019-08-21 11:07:31 +00002431 reportError(std::move(E), Filename, getFileNameForError(C, I),
2432 ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002433 continue;
2434 }
2435 if (MachOObjectFile *O =
2436 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2437 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2438 }
2439 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +00002440 reportError(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002441 } else {
2442 consumeError(AOrErr.takeError());
George Rimarf0f38d92019-08-21 11:07:31 +00002443 reportError(Filename,
2444 "Mach-O universal file for architecture " +
2445 StringRef(I->getArchFlagName()) +
2446 " is not a Mach-O file or an archive file");
Dave Lee3fb120f2018-08-03 00:06:38 +00002447 }
2448 }
2449 }
2450 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002451 WithColor::error(errs(), "llvm-objdump")
2452 << "file: " + Filename + " does not contain "
2453 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002454 return;
2455 }
2456 }
2457 return;
2458 }
2459 // No architecture flags were specified so if this contains a slice that
2460 // matches the host architecture dump only that.
2461 if (!ArchAll) {
2462 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2463 E = UB->end_objects();
2464 I != E; ++I) {
2465 if (MachOObjectFile::getHostArch().getArchName() ==
2466 I->getArchFlagName()) {
2467 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2468 std::string ArchiveName;
2469 ArchiveName.clear();
2470 if (ObjOrErr) {
2471 ObjectFile &O = *ObjOrErr.get();
2472 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2473 ProcessMachO(Filename, MachOOF);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002474 } else if (Error E =
2475 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
George Rimarf0f38d92019-08-21 11:07:31 +00002476 reportError(std::move(E), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002477 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002478 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002479 std::unique_ptr<Archive> &A = *AOrErr;
2480 outs() << "Archive : " << Filename << "\n";
2481 if (ArchiveHeaders)
2482 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2483 ArchiveMemberOffsets);
2484 Error Err = Error::success();
George Rimarb232d562019-08-20 13:19:16 +00002485 unsigned I = -1;
Dave Lee3fb120f2018-08-03 00:06:38 +00002486 for (auto &C : A->children(Err)) {
George Rimarb232d562019-08-20 13:19:16 +00002487 ++I;
Dave Lee3fb120f2018-08-03 00:06:38 +00002488 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2489 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002490 if (Error E =
2491 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
George Rimarf0f38d92019-08-21 11:07:31 +00002492 reportError(std::move(E), Filename, getFileNameForError(C, I));
Dave Lee3fb120f2018-08-03 00:06:38 +00002493 continue;
2494 }
2495 if (MachOObjectFile *O =
2496 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2497 ProcessMachO(Filename, O, O->getFileName());
2498 }
2499 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +00002500 reportError(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002501 } else {
2502 consumeError(AOrErr.takeError());
George Rimarf0f38d92019-08-21 11:07:31 +00002503 reportError(Filename, "Mach-O universal file for architecture " +
2504 StringRef(I->getArchFlagName()) +
2505 " is not a Mach-O file or an archive file");
Dave Lee3fb120f2018-08-03 00:06:38 +00002506 }
2507 return;
2508 }
2509 }
2510 }
2511 // Either all architectures have been specified or none have been specified
2512 // and this does not contain the host architecture so dump all the slices.
2513 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2514 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2515 E = UB->end_objects();
2516 I != E; ++I) {
2517 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2518 std::string ArchitectureName = "";
2519 if (moreThanOneArch)
2520 ArchitectureName = I->getArchFlagName();
2521 if (ObjOrErr) {
2522 ObjectFile &Obj = *ObjOrErr.get();
2523 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2524 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002525 } else if (Error E =
2526 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
George Rimarf0f38d92019-08-21 11:07:31 +00002527 reportError(std::move(E), StringRef(), Filename, ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002528 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002529 std::unique_ptr<Archive> &A = *AOrErr;
2530 outs() << "Archive : " << Filename;
2531 if (!ArchitectureName.empty())
2532 outs() << " (architecture " << ArchitectureName << ")";
2533 outs() << "\n";
2534 if (ArchiveHeaders)
2535 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2536 ArchiveMemberOffsets, ArchitectureName);
2537 Error Err = Error::success();
George Rimarb232d562019-08-20 13:19:16 +00002538 unsigned I = -1;
Dave Lee3fb120f2018-08-03 00:06:38 +00002539 for (auto &C : A->children(Err)) {
George Rimarb232d562019-08-20 13:19:16 +00002540 ++I;
Dave Lee3fb120f2018-08-03 00:06:38 +00002541 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2542 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002543 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
George Rimarf0f38d92019-08-21 11:07:31 +00002544 reportError(std::move(E), Filename, getFileNameForError(C, I),
2545 ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002546 continue;
2547 }
2548 if (MachOObjectFile *O =
2549 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2550 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2551 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2552 ArchitectureName);
2553 }
2554 }
2555 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +00002556 reportError(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002557 } else {
2558 consumeError(AOrErr.takeError());
George Rimarf0f38d92019-08-21 11:07:31 +00002559 reportError(Filename, "Mach-O universal file for architecture " +
2560 StringRef(I->getArchFlagName()) +
2561 " is not a Mach-O file or an archive file");
Dave Lee3fb120f2018-08-03 00:06:38 +00002562 }
2563 }
2564}
2565
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002566// The block of info used by the Symbolizer call backs.
2567struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002568 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2569 std::vector<SectionRef> *Sections, bool verbose)
2570 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002571 bool verbose;
2572 MachOObjectFile *O;
2573 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002574 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002575 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002576 const char *class_name = nullptr;
2577 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002578 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002579 char *demangled_name = nullptr;
2580 uint64_t adrp_addr = 0;
2581 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002582 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002583 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002584};
2585
2586// SymbolizerGetOpInfo() is the operand information call back function.
2587// This is called to get the symbolic information for operand(s) of an
2588// instruction when it is being done. This routine does this from
2589// the relocation information, symbol table, etc. That block of information
2590// is a pointer to the struct DisassembleInfo that was passed when the
2591// disassembler context was created and passed to back to here when
2592// called back by the disassembler for instruction operands that could have
2593// relocation information. The address of the instruction containing operand is
2594// at the Pc parameter. The immediate value the operand has is passed in
2595// op_info->Value and is at Offset past the start of the instruction and has a
2596// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2597// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2598// names and addends of the symbolic expression to add for the operand. The
2599// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2600// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002601static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2602 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002603 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2604 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002605 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002606
2607 // Make sure all fields returned are zero if we don't set them.
2608 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2609 op_info->Value = value;
2610
2611 // If the TagType is not the value 1 which it code knows about or if no
2612 // verbose symbolic information is wanted then just return 0, indicating no
2613 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002614 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002615 return 0;
2616
2617 unsigned int Arch = info->O->getArch();
2618 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002619 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2620 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002621 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2622 // TODO:
2623 // Search the external relocation entries of a fully linked image
2624 // (if any) for an entry that matches this segment offset.
2625 // uint32_t seg_offset = (Pc + Offset);
2626 return 0;
2627 }
2628 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2629 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002630 uint32_t sect_addr = info->S.getAddress();
2631 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2632 bool reloc_found = false;
2633 DataRefImpl Rel;
2634 MachO::any_relocation_info RE;
2635 bool isExtern = false;
2636 SymbolRef Symbol;
2637 bool r_scattered = false;
2638 uint32_t r_value, pair_r_value, r_type;
2639 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002640 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002641 if (RelocOffset == sect_offset) {
2642 Rel = Reloc.getRawDataRefImpl();
2643 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002644 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002645 r_scattered = info->O->isRelocationScattered(RE);
2646 if (r_scattered) {
2647 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002648 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2649 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2650 DataRefImpl RelNext = Rel;
2651 info->O->moveRelocationNext(RelNext);
2652 MachO::any_relocation_info RENext;
2653 RENext = info->O->getRelocation(RelNext);
2654 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002655 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002656 else
2657 return 0;
2658 }
2659 } else {
2660 isExtern = info->O->getPlainRelocationExternal(RE);
2661 if (isExtern) {
2662 symbol_iterator RelocSym = Reloc.getSymbol();
2663 Symbol = *RelocSym;
2664 }
2665 }
2666 reloc_found = true;
2667 break;
2668 }
2669 }
2670 if (reloc_found && isExtern) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002671 op_info->AddSymbol.Present = 1;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002672 op_info->AddSymbol.Name =
2673 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002674 // For i386 extern relocation entries the value in the instruction is
2675 // the offset from the symbol, and value is already set in op_info->Value.
2676 return 1;
2677 }
2678 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2679 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002680 const char *add = GuessSymbolName(r_value, info->AddrMap);
2681 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002682 uint32_t offset = value - (r_value - pair_r_value);
2683 op_info->AddSymbol.Present = 1;
2684 if (add != nullptr)
2685 op_info->AddSymbol.Name = add;
2686 else
2687 op_info->AddSymbol.Value = r_value;
2688 op_info->SubtractSymbol.Present = 1;
2689 if (sub != nullptr)
2690 op_info->SubtractSymbol.Name = sub;
2691 else
2692 op_info->SubtractSymbol.Value = pair_r_value;
2693 op_info->Value = offset;
2694 return 1;
2695 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002696 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002697 }
2698 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002699 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2700 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002701 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2702 // relocation entries of a linked image (if any) for an entry that matches
2703 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002704 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002705 uint64_t seg_offset = Pc + Offset;
2706 bool reloc_found = false;
2707 DataRefImpl Rel;
2708 MachO::any_relocation_info RE;
2709 bool isExtern = false;
2710 SymbolRef Symbol;
2711 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2712 uint64_t RelocOffset = Reloc.getOffset();
2713 if (RelocOffset == seg_offset) {
2714 Rel = Reloc.getRawDataRefImpl();
2715 RE = info->O->getRelocation(Rel);
2716 // external relocation entries should always be external.
2717 isExtern = info->O->getPlainRelocationExternal(RE);
2718 if (isExtern) {
2719 symbol_iterator RelocSym = Reloc.getSymbol();
2720 Symbol = *RelocSym;
2721 }
2722 reloc_found = true;
2723 break;
2724 }
2725 }
2726 if (reloc_found && isExtern) {
2727 // The Value passed in will be adjusted by the Pc if the instruction
2728 // adds the Pc. But for x86_64 external relocation entries the Value
2729 // is the offset from the external symbol.
2730 if (info->O->getAnyRelocationPCRel(RE))
2731 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002732 const char *name =
2733 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002734 op_info->AddSymbol.Present = 1;
2735 op_info->AddSymbol.Name = name;
2736 return 1;
2737 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002738 return 0;
2739 }
2740 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2741 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002742 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002743 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2744 bool reloc_found = false;
2745 DataRefImpl Rel;
2746 MachO::any_relocation_info RE;
2747 bool isExtern = false;
2748 SymbolRef Symbol;
2749 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002750 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002751 if (RelocOffset == sect_offset) {
2752 Rel = Reloc.getRawDataRefImpl();
2753 RE = info->O->getRelocation(Rel);
2754 // NOTE: Scattered relocations don't exist on x86_64.
2755 isExtern = info->O->getPlainRelocationExternal(RE);
2756 if (isExtern) {
2757 symbol_iterator RelocSym = Reloc.getSymbol();
2758 Symbol = *RelocSym;
2759 }
2760 reloc_found = true;
2761 break;
2762 }
2763 }
2764 if (reloc_found && isExtern) {
2765 // The Value passed in will be adjusted by the Pc if the instruction
2766 // adds the Pc. But for x86_64 external relocation entries the Value
2767 // is the offset from the external symbol.
2768 if (info->O->getAnyRelocationPCRel(RE))
2769 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002770 const char *name =
2771 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002772 unsigned Type = info->O->getAnyRelocationType(RE);
2773 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2774 DataRefImpl RelNext = Rel;
2775 info->O->moveRelocationNext(RelNext);
2776 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2777 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2778 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2779 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2780 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2781 op_info->SubtractSymbol.Present = 1;
2782 op_info->SubtractSymbol.Name = name;
2783 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2784 Symbol = *RelocSymNext;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002785 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002786 }
2787 }
2788 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2789 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2790 op_info->AddSymbol.Present = 1;
2791 op_info->AddSymbol.Name = name;
2792 return 1;
2793 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002794 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002795 }
2796 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002797 if (Offset != 0 || (Size != 4 && Size != 2))
2798 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002799 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2800 // TODO:
2801 // Search the external relocation entries of a fully linked image
2802 // (if any) for an entry that matches this segment offset.
2803 // uint32_t seg_offset = (Pc + Offset);
2804 return 0;
2805 }
2806 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2807 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002808 uint32_t sect_addr = info->S.getAddress();
2809 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002810 DataRefImpl Rel;
2811 MachO::any_relocation_info RE;
2812 bool isExtern = false;
2813 SymbolRef Symbol;
2814 bool r_scattered = false;
2815 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002816 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002817 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2818 uint64_t RelocOffset = Reloc.getOffset();
2819 return RelocOffset == sect_offset;
2820 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002821
2822 if (Reloc == info->S.relocations().end())
2823 return 0;
2824
2825 Rel = Reloc->getRawDataRefImpl();
2826 RE = info->O->getRelocation(Rel);
2827 r_length = info->O->getAnyRelocationLength(RE);
2828 r_scattered = info->O->isRelocationScattered(RE);
2829 if (r_scattered) {
2830 r_value = info->O->getScatteredRelocationValue(RE);
2831 r_type = info->O->getScatteredRelocationType(RE);
2832 } else {
2833 r_type = info->O->getAnyRelocationType(RE);
2834 isExtern = info->O->getPlainRelocationExternal(RE);
2835 if (isExtern) {
2836 symbol_iterator RelocSym = Reloc->getSymbol();
2837 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002838 }
2839 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002840 if (r_type == MachO::ARM_RELOC_HALF ||
2841 r_type == MachO::ARM_RELOC_SECTDIFF ||
2842 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2843 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2844 DataRefImpl RelNext = Rel;
2845 info->O->moveRelocationNext(RelNext);
2846 MachO::any_relocation_info RENext;
2847 RENext = info->O->getRelocation(RelNext);
2848 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2849 if (info->O->isRelocationScattered(RENext))
2850 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2851 }
2852
2853 if (isExtern) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002854 const char *name =
2855 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002856 op_info->AddSymbol.Present = 1;
2857 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002858 switch (r_type) {
2859 case MachO::ARM_RELOC_HALF:
2860 if ((r_length & 0x1) == 1) {
2861 op_info->Value = value << 16 | other_half;
2862 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2863 } else {
2864 op_info->Value = other_half << 16 | value;
2865 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002866 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002867 break;
2868 default:
2869 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002870 }
2871 return 1;
2872 }
2873 // If we have a branch that is not an external relocation entry then
2874 // return 0 so the code in tryAddingSymbolicOperand() can use the
2875 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002876 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002877 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2878 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002879 return 0;
2880
2881 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002882 if (r_type == MachO::ARM_RELOC_HALF ||
2883 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2884 if ((r_length & 0x1) == 1)
2885 value = value << 16 | other_half;
2886 else
2887 value = other_half << 16 | value;
2888 }
2889 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2890 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2891 offset = value - r_value;
2892 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002893 }
2894
David Blaikie33dd45d02015-03-23 18:39:02 +00002895 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002896 if ((r_length & 0x1) == 1)
2897 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2898 else
2899 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002900 const char *add = GuessSymbolName(r_value, info->AddrMap);
2901 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002902 int32_t offset = value - (r_value - pair_r_value);
2903 op_info->AddSymbol.Present = 1;
2904 if (add != nullptr)
2905 op_info->AddSymbol.Name = add;
2906 else
2907 op_info->AddSymbol.Value = r_value;
2908 op_info->SubtractSymbol.Present = 1;
2909 if (sub != nullptr)
2910 op_info->SubtractSymbol.Name = sub;
2911 else
2912 op_info->SubtractSymbol.Value = pair_r_value;
2913 op_info->Value = offset;
2914 return 1;
2915 }
2916
Kevin Enderby930fdc72014-11-06 19:00:13 +00002917 op_info->AddSymbol.Present = 1;
2918 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002919 if (r_type == MachO::ARM_RELOC_HALF) {
2920 if ((r_length & 0x1) == 1)
2921 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2922 else
2923 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002924 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002925 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002926 if (add != nullptr) {
2927 op_info->AddSymbol.Name = add;
2928 return 1;
2929 }
2930 op_info->AddSymbol.Value = value;
2931 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002932 }
2933 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002934 if (Offset != 0 || Size != 4)
2935 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002936 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2937 // TODO:
2938 // Search the external relocation entries of a fully linked image
2939 // (if any) for an entry that matches this segment offset.
2940 // uint64_t seg_offset = (Pc + Offset);
2941 return 0;
2942 }
2943 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2944 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002945 uint64_t sect_addr = info->S.getAddress();
2946 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002947 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002948 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2949 uint64_t RelocOffset = Reloc.getOffset();
2950 return RelocOffset == sect_offset;
2951 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002952
David Blaikie33dd45d02015-03-23 18:39:02 +00002953 if (Reloc == info->S.relocations().end())
2954 return 0;
2955
2956 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2957 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2958 uint32_t r_type = info->O->getAnyRelocationType(RE);
2959 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2960 DataRefImpl RelNext = Rel;
2961 info->O->moveRelocationNext(RelNext);
2962 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2963 if (value == 0) {
2964 value = info->O->getPlainRelocationSymbolNum(RENext);
2965 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002966 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002967 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002968 // NOTE: Scattered relocations don't exist on arm64.
2969 if (!info->O->getPlainRelocationExternal(RE))
2970 return 0;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002971 const char *name =
2972 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2973 .data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002974 op_info->AddSymbol.Present = 1;
2975 op_info->AddSymbol.Name = name;
2976
2977 switch (r_type) {
2978 case MachO::ARM64_RELOC_PAGE21:
2979 /* @page */
2980 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2981 break;
2982 case MachO::ARM64_RELOC_PAGEOFF12:
2983 /* @pageoff */
2984 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2985 break;
2986 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2987 /* @gotpage */
2988 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2989 break;
2990 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2991 /* @gotpageoff */
2992 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2993 break;
2994 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2995 /* @tvlppage is not implemented in llvm-mc */
2996 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2997 break;
2998 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2999 /* @tvlppageoff is not implemented in llvm-mc */
3000 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3001 break;
3002 default:
3003 case MachO::ARM64_RELOC_BRANCH26:
3004 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3005 break;
3006 }
3007 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003008 }
David Blaikie33dd45d02015-03-23 18:39:02 +00003009 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003010}
3011
Kevin Enderbybf246f52014-09-24 23:08:22 +00003012// GuessCstringPointer is passed the address of what might be a pointer to a
3013// literal string in a cstring section. If that address is in a cstring section
3014// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003015static const char *GuessCstringPointer(uint64_t ReferenceValue,
3016 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003017 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00003018 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3019 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3020 for (unsigned J = 0; J < Seg.nsects; ++J) {
3021 MachO::section_64 Sec = info->O->getSection64(Load, J);
3022 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3023 if (section_type == MachO::S_CSTRING_LITERALS &&
3024 ReferenceValue >= Sec.addr &&
3025 ReferenceValue < Sec.addr + Sec.size) {
3026 uint64_t sect_offset = ReferenceValue - Sec.addr;
3027 uint64_t object_offset = Sec.offset + sect_offset;
3028 StringRef MachOContents = info->O->getData();
3029 uint64_t object_size = MachOContents.size();
3030 const char *object_addr = (const char *)MachOContents.data();
3031 if (object_offset < object_size) {
3032 const char *name = object_addr + object_offset;
3033 return name;
3034 } else {
3035 return nullptr;
3036 }
3037 }
3038 }
3039 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3040 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3041 for (unsigned J = 0; J < Seg.nsects; ++J) {
3042 MachO::section Sec = info->O->getSection(Load, J);
3043 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3044 if (section_type == MachO::S_CSTRING_LITERALS &&
3045 ReferenceValue >= Sec.addr &&
3046 ReferenceValue < Sec.addr + Sec.size) {
3047 uint64_t sect_offset = ReferenceValue - Sec.addr;
3048 uint64_t object_offset = Sec.offset + sect_offset;
3049 StringRef MachOContents = info->O->getData();
3050 uint64_t object_size = MachOContents.size();
3051 const char *object_addr = (const char *)MachOContents.data();
3052 if (object_offset < object_size) {
3053 const char *name = object_addr + object_offset;
3054 return name;
3055 } else {
3056 return nullptr;
3057 }
3058 }
3059 }
3060 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00003061 }
3062 return nullptr;
3063}
3064
Kevin Enderby85974882014-09-26 22:20:44 +00003065// GuessIndirectSymbol returns the name of the indirect symbol for the
3066// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
3067// an address of a symbol stub or a lazy or non-lazy pointer to associate the
3068// symbol name being referenced by the stub or pointer.
3069static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3070 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00003071 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3072 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003073 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00003074 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3075 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3076 for (unsigned J = 0; J < Seg.nsects; ++J) {
3077 MachO::section_64 Sec = info->O->getSection64(Load, J);
3078 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3079 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3080 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3081 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3082 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3083 section_type == MachO::S_SYMBOL_STUBS) &&
3084 ReferenceValue >= Sec.addr &&
3085 ReferenceValue < Sec.addr + Sec.size) {
3086 uint32_t stride;
3087 if (section_type == MachO::S_SYMBOL_STUBS)
3088 stride = Sec.reserved2;
3089 else
3090 stride = 8;
3091 if (stride == 0)
3092 return nullptr;
3093 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3094 if (index < Dysymtab.nindirectsyms) {
3095 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003096 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00003097 if (indirect_symbol < Symtab.nsyms) {
3098 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00003099 return unwrapOrError(Sym->getName(), info->O->getFileName())
3100 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00003101 }
3102 }
3103 }
3104 }
3105 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3106 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3107 for (unsigned J = 0; J < Seg.nsects; ++J) {
3108 MachO::section Sec = info->O->getSection(Load, J);
3109 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3110 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3111 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3112 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3113 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3114 section_type == MachO::S_SYMBOL_STUBS) &&
3115 ReferenceValue >= Sec.addr &&
3116 ReferenceValue < Sec.addr + Sec.size) {
3117 uint32_t stride;
3118 if (section_type == MachO::S_SYMBOL_STUBS)
3119 stride = Sec.reserved2;
3120 else
3121 stride = 4;
3122 if (stride == 0)
3123 return nullptr;
3124 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3125 if (index < Dysymtab.nindirectsyms) {
3126 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003127 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00003128 if (indirect_symbol < Symtab.nsyms) {
3129 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00003130 return unwrapOrError(Sym->getName(), info->O->getFileName())
3131 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00003132 }
3133 }
3134 }
3135 }
3136 }
Kevin Enderby85974882014-09-26 22:20:44 +00003137 }
3138 return nullptr;
3139}
3140
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003141// method_reference() is called passing it the ReferenceName that might be
3142// a reference it to an Objective-C method call. If so then it allocates and
3143// assembles a method call string with the values last seen and saved in
3144// the DisassembleInfo's class_name and selector_name fields. This is saved
3145// into the method field of the info and any previous string is free'ed.
3146// Then the class_name field in the info is set to nullptr. The method call
3147// string is set into ReferenceName and ReferenceType is set to
3148// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3149// then both ReferenceType and ReferenceName are left unchanged.
3150static void method_reference(struct DisassembleInfo *info,
3151 uint64_t *ReferenceType,
3152 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003153 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003154 if (*ReferenceName != nullptr) {
3155 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003156 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003157 if (info->class_name != nullptr) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003158 info->method = std::make_unique<char[]>(
David Blaikie0e550682018-02-20 18:48:51 +00003159 5 + strlen(info->class_name) + strlen(info->selector_name));
3160 char *method = info->method.get();
3161 if (method != nullptr) {
3162 strcpy(method, "+[");
3163 strcat(method, info->class_name);
3164 strcat(method, " ");
3165 strcat(method, info->selector_name);
3166 strcat(method, "]");
3167 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003168 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3169 }
3170 } else {
David Blaikie0e550682018-02-20 18:48:51 +00003171 info->method =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003172 std::make_unique<char[]>(9 + strlen(info->selector_name));
David Blaikie0e550682018-02-20 18:48:51 +00003173 char *method = info->method.get();
3174 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003175 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003176 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003177 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003178 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003179 else
David Blaikie0e550682018-02-20 18:48:51 +00003180 strcpy(method, "-[r? ");
3181 strcat(method, info->selector_name);
3182 strcat(method, "]");
3183 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003184 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3185 }
3186 }
3187 info->class_name = nullptr;
3188 }
3189 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003190 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003191 info->method =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003192 std::make_unique<char[]>(17 + strlen(info->selector_name));
David Blaikie0e550682018-02-20 18:48:51 +00003193 char *method = info->method.get();
3194 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003195 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003196 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003197 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003198 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003199 else
David Blaikie0e550682018-02-20 18:48:51 +00003200 strcpy(method, "-[[r? super] ");
3201 strcat(method, info->selector_name);
3202 strcat(method, "]");
3203 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003204 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3205 }
3206 info->class_name = nullptr;
3207 }
3208 }
3209 }
3210}
3211
3212// GuessPointerPointer() is passed the address of what might be a pointer to
3213// a reference to an Objective-C class, selector, message ref or cfstring.
3214// If so the value of the pointer is returned and one of the booleans are set
3215// to true. If not zero is returned and all the booleans are set to false.
3216static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3217 struct DisassembleInfo *info,
3218 bool &classref, bool &selref, bool &msgref,
3219 bool &cfstring) {
3220 classref = false;
3221 selref = false;
3222 msgref = false;
3223 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003224 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003225 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3226 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3227 for (unsigned J = 0; J < Seg.nsects; ++J) {
3228 MachO::section_64 Sec = info->O->getSection64(Load, J);
3229 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3230 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3231 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3232 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3233 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3234 ReferenceValue >= Sec.addr &&
3235 ReferenceValue < Sec.addr + Sec.size) {
3236 uint64_t sect_offset = ReferenceValue - Sec.addr;
3237 uint64_t object_offset = Sec.offset + sect_offset;
3238 StringRef MachOContents = info->O->getData();
3239 uint64_t object_size = MachOContents.size();
3240 const char *object_addr = (const char *)MachOContents.data();
3241 if (object_offset < object_size) {
3242 uint64_t pointer_value;
3243 memcpy(&pointer_value, object_addr + object_offset,
3244 sizeof(uint64_t));
3245 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3246 sys::swapByteOrder(pointer_value);
3247 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3248 selref = true;
3249 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3250 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3251 classref = true;
3252 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3253 ReferenceValue + 8 < Sec.addr + Sec.size) {
3254 msgref = true;
3255 memcpy(&pointer_value, object_addr + object_offset + 8,
3256 sizeof(uint64_t));
3257 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3258 sys::swapByteOrder(pointer_value);
3259 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3260 cfstring = true;
3261 return pointer_value;
3262 } else {
3263 return 0;
3264 }
3265 }
3266 }
3267 }
3268 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003269 }
3270 return 0;
3271}
3272
3273// get_pointer_64 returns a pointer to the bytes in the object file at the
3274// Address from a section in the Mach-O file. And indirectly returns the
3275// offset into the section, number of bytes left in the section past the offset
3276// and which section is was being referenced. If the Address is not in a
3277// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003278static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3279 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003280 DisassembleInfo *info,
3281 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003282 offset = 0;
3283 left = 0;
3284 S = SectionRef();
3285 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3286 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3287 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00003288 if (SectSize == 0)
3289 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00003290 if (objc_only) {
3291 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00003292 Expected<StringRef> SecNameOrErr =
3293 ((*(info->Sections))[SectIdx]).getName();
3294 if (SecNameOrErr)
3295 SectName = *SecNameOrErr;
3296 else
3297 consumeError(SecNameOrErr.takeError());
3298
Kevin Enderby846c0002015-04-16 17:19:59 +00003299 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3300 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3301 if (SegName != "__OBJC" && SectName != "__cstring")
3302 continue;
3303 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003304 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3305 S = (*(info->Sections))[SectIdx];
3306 offset = Address - SectAddress;
3307 left = SectSize - offset;
Fangrui Songe1833402019-05-16 13:24:04 +00003308 StringRef SectContents = unwrapOrError(
3309 ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003310 return SectContents.data() + offset;
3311 }
3312 }
3313 return nullptr;
3314}
3315
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003316static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3317 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003318 DisassembleInfo *info,
3319 bool objc_only = false) {
3320 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003321}
3322
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003323// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3324// the symbol indirectly through n_value. Based on the relocation information
3325// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00003326// If no relocation information is found and a non-zero ReferenceValue for the
3327// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00003328static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3329 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003330 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003331 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00003332 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003333 return nullptr;
3334
3335 // See if there is an external relocation entry at the sect_offset.
3336 bool reloc_found = false;
3337 DataRefImpl Rel;
3338 MachO::any_relocation_info RE;
3339 bool isExtern = false;
3340 SymbolRef Symbol;
3341 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00003342 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003343 if (RelocOffset == sect_offset) {
3344 Rel = Reloc.getRawDataRefImpl();
3345 RE = info->O->getRelocation(Rel);
3346 if (info->O->isRelocationScattered(RE))
3347 continue;
3348 isExtern = info->O->getPlainRelocationExternal(RE);
3349 if (isExtern) {
3350 symbol_iterator RelocSym = Reloc.getSymbol();
3351 Symbol = *RelocSym;
3352 }
3353 reloc_found = true;
3354 break;
3355 }
3356 }
3357 // If there is an external relocation entry for a symbol in this section
3358 // at this section_offset then use that symbol's value for the n_value
3359 // and return its name.
3360 const char *SymbolName = nullptr;
3361 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003362 n_value = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00003363 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003364 if (!Name.empty()) {
3365 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003366 return SymbolName;
3367 }
3368 }
3369
3370 // TODO: For fully linked images, look through the external relocation
3371 // entries off the dynamic symtab command. For these the r_offset is from the
3372 // start of the first writeable segment in the Mach-O file. So the offset
3373 // to this section from that segment is passed to this routine by the caller,
3374 // as the database_offset. Which is the difference of the section's starting
3375 // address and the first writable segment.
3376 //
3377 // NOTE: need add passing the database_offset to this routine.
3378
Kevin Enderby0fc11822015-04-01 20:57:01 +00003379 // We did not find an external relocation entry so look up the ReferenceValue
3380 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003381 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003382
3383 return SymbolName;
3384}
3385
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003386static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3387 DisassembleInfo *info,
3388 uint32_t ReferenceValue) {
3389 uint64_t n_value64;
3390 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3391}
3392
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003393// These are structs in the Objective-C meta data and read to produce the
3394// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003395// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3396// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003397
3398// The cfstring object in a 64-bit Mach-O file.
3399struct cfstring64_t {
3400 uint64_t isa; // class64_t * (64-bit pointer)
3401 uint64_t flags; // flag bits
3402 uint64_t characters; // char * (64-bit pointer)
3403 uint64_t length; // number of non-NULL characters in above
3404};
3405
3406// The class object in a 64-bit Mach-O file.
3407struct class64_t {
3408 uint64_t isa; // class64_t * (64-bit pointer)
3409 uint64_t superclass; // class64_t * (64-bit pointer)
3410 uint64_t cache; // Cache (64-bit pointer)
3411 uint64_t vtable; // IMP * (64-bit pointer)
3412 uint64_t data; // class_ro64_t * (64-bit pointer)
3413};
3414
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003415struct class32_t {
3416 uint32_t isa; /* class32_t * (32-bit pointer) */
3417 uint32_t superclass; /* class32_t * (32-bit pointer) */
3418 uint32_t cache; /* Cache (32-bit pointer) */
3419 uint32_t vtable; /* IMP * (32-bit pointer) */
3420 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3421};
3422
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003423struct class_ro64_t {
3424 uint32_t flags;
3425 uint32_t instanceStart;
3426 uint32_t instanceSize;
3427 uint32_t reserved;
3428 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3429 uint64_t name; // const char * (64-bit pointer)
3430 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3431 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3432 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3433 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3434 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3435};
3436
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003437struct class_ro32_t {
3438 uint32_t flags;
3439 uint32_t instanceStart;
3440 uint32_t instanceSize;
3441 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3442 uint32_t name; /* const char * (32-bit pointer) */
3443 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3444 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3445 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3446 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3447 uint32_t baseProperties; /* const struct objc_property_list *
3448 (32-bit pointer) */
3449};
3450
3451/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003452#define RO_META (1 << 0)
3453#define RO_ROOT (1 << 1)
3454#define RO_HAS_CXX_STRUCTORS (1 << 2)
3455
3456struct method_list64_t {
3457 uint32_t entsize;
3458 uint32_t count;
3459 /* struct method64_t first; These structures follow inline */
3460};
3461
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003462struct method_list32_t {
3463 uint32_t entsize;
3464 uint32_t count;
3465 /* struct method32_t first; These structures follow inline */
3466};
3467
Kevin Enderby0fc11822015-04-01 20:57:01 +00003468struct method64_t {
3469 uint64_t name; /* SEL (64-bit pointer) */
3470 uint64_t types; /* const char * (64-bit pointer) */
3471 uint64_t imp; /* IMP (64-bit pointer) */
3472};
3473
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003474struct method32_t {
3475 uint32_t name; /* SEL (32-bit pointer) */
3476 uint32_t types; /* const char * (32-bit pointer) */
3477 uint32_t imp; /* IMP (32-bit pointer) */
3478};
3479
Kevin Enderby0fc11822015-04-01 20:57:01 +00003480struct protocol_list64_t {
3481 uint64_t count; /* uintptr_t (a 64-bit value) */
3482 /* struct protocol64_t * list[0]; These pointers follow inline */
3483};
3484
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003485struct protocol_list32_t {
3486 uint32_t count; /* uintptr_t (a 32-bit value) */
3487 /* struct protocol32_t * list[0]; These pointers follow inline */
3488};
3489
Kevin Enderby0fc11822015-04-01 20:57:01 +00003490struct protocol64_t {
3491 uint64_t isa; /* id * (64-bit pointer) */
3492 uint64_t name; /* const char * (64-bit pointer) */
3493 uint64_t protocols; /* struct protocol_list64_t *
3494 (64-bit pointer) */
3495 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3496 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3497 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3498 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3499 uint64_t instanceProperties; /* struct objc_property_list *
3500 (64-bit pointer) */
3501};
3502
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003503struct protocol32_t {
3504 uint32_t isa; /* id * (32-bit pointer) */
3505 uint32_t name; /* const char * (32-bit pointer) */
3506 uint32_t protocols; /* struct protocol_list_t *
3507 (32-bit pointer) */
3508 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3509 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3510 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3511 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3512 uint32_t instanceProperties; /* struct objc_property_list *
3513 (32-bit pointer) */
3514};
3515
Kevin Enderby0fc11822015-04-01 20:57:01 +00003516struct ivar_list64_t {
3517 uint32_t entsize;
3518 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003519 /* struct ivar64_t first; These structures follow inline */
3520};
3521
3522struct ivar_list32_t {
3523 uint32_t entsize;
3524 uint32_t count;
3525 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003526};
3527
3528struct ivar64_t {
3529 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3530 uint64_t name; /* const char * (64-bit pointer) */
3531 uint64_t type; /* const char * (64-bit pointer) */
3532 uint32_t alignment;
3533 uint32_t size;
3534};
3535
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003536struct ivar32_t {
3537 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3538 uint32_t name; /* const char * (32-bit pointer) */
3539 uint32_t type; /* const char * (32-bit pointer) */
3540 uint32_t alignment;
3541 uint32_t size;
3542};
3543
Kevin Enderby0fc11822015-04-01 20:57:01 +00003544struct objc_property_list64 {
3545 uint32_t entsize;
3546 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003547 /* struct objc_property64 first; These structures follow inline */
3548};
3549
3550struct objc_property_list32 {
3551 uint32_t entsize;
3552 uint32_t count;
3553 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003554};
3555
3556struct objc_property64 {
3557 uint64_t name; /* const char * (64-bit pointer) */
3558 uint64_t attributes; /* const char * (64-bit pointer) */
3559};
3560
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003561struct objc_property32 {
3562 uint32_t name; /* const char * (32-bit pointer) */
3563 uint32_t attributes; /* const char * (32-bit pointer) */
3564};
3565
Kevin Enderby0fc11822015-04-01 20:57:01 +00003566struct category64_t {
3567 uint64_t name; /* const char * (64-bit pointer) */
3568 uint64_t cls; /* struct class_t * (64-bit pointer) */
3569 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3570 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3571 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3572 uint64_t instanceProperties; /* struct objc_property_list *
3573 (64-bit pointer) */
3574};
3575
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003576struct category32_t {
3577 uint32_t name; /* const char * (32-bit pointer) */
3578 uint32_t cls; /* struct class_t * (32-bit pointer) */
3579 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3580 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3581 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3582 uint32_t instanceProperties; /* struct objc_property_list *
3583 (32-bit pointer) */
3584};
3585
Kevin Enderby0fc11822015-04-01 20:57:01 +00003586struct objc_image_info64 {
3587 uint32_t version;
3588 uint32_t flags;
3589};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003590struct objc_image_info32 {
3591 uint32_t version;
3592 uint32_t flags;
3593};
Kevin Enderby846c0002015-04-16 17:19:59 +00003594struct imageInfo_t {
3595 uint32_t version;
3596 uint32_t flags;
3597};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003598/* masks for objc_image_info.flags */
3599#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3600#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003601#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3602#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003603
3604struct message_ref64 {
3605 uint64_t imp; /* IMP (64-bit pointer) */
3606 uint64_t sel; /* SEL (64-bit pointer) */
3607};
3608
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003609struct message_ref32 {
3610 uint32_t imp; /* IMP (32-bit pointer) */
3611 uint32_t sel; /* SEL (32-bit pointer) */
3612};
3613
Kevin Enderby846c0002015-04-16 17:19:59 +00003614// Objective-C 1 (32-bit only) meta data structs.
3615
3616struct objc_module_t {
3617 uint32_t version;
3618 uint32_t size;
3619 uint32_t name; /* char * (32-bit pointer) */
3620 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3621};
3622
3623struct objc_symtab_t {
3624 uint32_t sel_ref_cnt;
3625 uint32_t refs; /* SEL * (32-bit pointer) */
3626 uint16_t cls_def_cnt;
3627 uint16_t cat_def_cnt;
3628 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3629};
3630
3631struct objc_class_t {
3632 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3633 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3634 uint32_t name; /* const char * (32-bit pointer) */
3635 int32_t version;
3636 int32_t info;
3637 int32_t instance_size;
3638 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3639 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3640 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3641 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3642};
3643
3644#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3645// class is not a metaclass
3646#define CLS_CLASS 0x1
3647// class is a metaclass
3648#define CLS_META 0x2
3649
3650struct objc_category_t {
3651 uint32_t category_name; /* char * (32-bit pointer) */
3652 uint32_t class_name; /* char * (32-bit pointer) */
3653 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3654 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3655 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3656};
3657
3658struct objc_ivar_t {
3659 uint32_t ivar_name; /* char * (32-bit pointer) */
3660 uint32_t ivar_type; /* char * (32-bit pointer) */
3661 int32_t ivar_offset;
3662};
3663
3664struct objc_ivar_list_t {
3665 int32_t ivar_count;
3666 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3667};
3668
3669struct objc_method_list_t {
3670 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3671 int32_t method_count;
3672 // struct objc_method_t method_list[1]; /* variable length structure */
3673};
3674
3675struct objc_method_t {
3676 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3677 uint32_t method_types; /* char * (32-bit pointer) */
3678 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3679 (32-bit pointer) */
3680};
3681
3682struct objc_protocol_list_t {
3683 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3684 int32_t count;
3685 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3686 // (32-bit pointer) */
3687};
3688
3689struct objc_protocol_t {
3690 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3691 uint32_t protocol_name; /* char * (32-bit pointer) */
3692 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3693 uint32_t instance_methods; /* struct objc_method_description_list *
3694 (32-bit pointer) */
3695 uint32_t class_methods; /* struct objc_method_description_list *
3696 (32-bit pointer) */
3697};
3698
3699struct objc_method_description_list_t {
3700 int32_t count;
3701 // struct objc_method_description_t list[1];
3702};
3703
3704struct objc_method_description_t {
3705 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3706 uint32_t types; /* char * (32-bit pointer) */
3707};
3708
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003709inline void swapStruct(struct cfstring64_t &cfs) {
3710 sys::swapByteOrder(cfs.isa);
3711 sys::swapByteOrder(cfs.flags);
3712 sys::swapByteOrder(cfs.characters);
3713 sys::swapByteOrder(cfs.length);
3714}
3715
3716inline void swapStruct(struct class64_t &c) {
3717 sys::swapByteOrder(c.isa);
3718 sys::swapByteOrder(c.superclass);
3719 sys::swapByteOrder(c.cache);
3720 sys::swapByteOrder(c.vtable);
3721 sys::swapByteOrder(c.data);
3722}
3723
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003724inline void swapStruct(struct class32_t &c) {
3725 sys::swapByteOrder(c.isa);
3726 sys::swapByteOrder(c.superclass);
3727 sys::swapByteOrder(c.cache);
3728 sys::swapByteOrder(c.vtable);
3729 sys::swapByteOrder(c.data);
3730}
3731
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003732inline void swapStruct(struct class_ro64_t &cro) {
3733 sys::swapByteOrder(cro.flags);
3734 sys::swapByteOrder(cro.instanceStart);
3735 sys::swapByteOrder(cro.instanceSize);
3736 sys::swapByteOrder(cro.reserved);
3737 sys::swapByteOrder(cro.ivarLayout);
3738 sys::swapByteOrder(cro.name);
3739 sys::swapByteOrder(cro.baseMethods);
3740 sys::swapByteOrder(cro.baseProtocols);
3741 sys::swapByteOrder(cro.ivars);
3742 sys::swapByteOrder(cro.weakIvarLayout);
3743 sys::swapByteOrder(cro.baseProperties);
3744}
3745
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003746inline void swapStruct(struct class_ro32_t &cro) {
3747 sys::swapByteOrder(cro.flags);
3748 sys::swapByteOrder(cro.instanceStart);
3749 sys::swapByteOrder(cro.instanceSize);
3750 sys::swapByteOrder(cro.ivarLayout);
3751 sys::swapByteOrder(cro.name);
3752 sys::swapByteOrder(cro.baseMethods);
3753 sys::swapByteOrder(cro.baseProtocols);
3754 sys::swapByteOrder(cro.ivars);
3755 sys::swapByteOrder(cro.weakIvarLayout);
3756 sys::swapByteOrder(cro.baseProperties);
3757}
3758
Kevin Enderby0fc11822015-04-01 20:57:01 +00003759inline void swapStruct(struct method_list64_t &ml) {
3760 sys::swapByteOrder(ml.entsize);
3761 sys::swapByteOrder(ml.count);
3762}
3763
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003764inline void swapStruct(struct method_list32_t &ml) {
3765 sys::swapByteOrder(ml.entsize);
3766 sys::swapByteOrder(ml.count);
3767}
3768
Kevin Enderby0fc11822015-04-01 20:57:01 +00003769inline void swapStruct(struct method64_t &m) {
3770 sys::swapByteOrder(m.name);
3771 sys::swapByteOrder(m.types);
3772 sys::swapByteOrder(m.imp);
3773}
3774
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003775inline void swapStruct(struct method32_t &m) {
3776 sys::swapByteOrder(m.name);
3777 sys::swapByteOrder(m.types);
3778 sys::swapByteOrder(m.imp);
3779}
3780
Kevin Enderby0fc11822015-04-01 20:57:01 +00003781inline void swapStruct(struct protocol_list64_t &pl) {
3782 sys::swapByteOrder(pl.count);
3783}
3784
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003785inline void swapStruct(struct protocol_list32_t &pl) {
3786 sys::swapByteOrder(pl.count);
3787}
3788
Kevin Enderby0fc11822015-04-01 20:57:01 +00003789inline void swapStruct(struct protocol64_t &p) {
3790 sys::swapByteOrder(p.isa);
3791 sys::swapByteOrder(p.name);
3792 sys::swapByteOrder(p.protocols);
3793 sys::swapByteOrder(p.instanceMethods);
3794 sys::swapByteOrder(p.classMethods);
3795 sys::swapByteOrder(p.optionalInstanceMethods);
3796 sys::swapByteOrder(p.optionalClassMethods);
3797 sys::swapByteOrder(p.instanceProperties);
3798}
3799
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003800inline void swapStruct(struct protocol32_t &p) {
3801 sys::swapByteOrder(p.isa);
3802 sys::swapByteOrder(p.name);
3803 sys::swapByteOrder(p.protocols);
3804 sys::swapByteOrder(p.instanceMethods);
3805 sys::swapByteOrder(p.classMethods);
3806 sys::swapByteOrder(p.optionalInstanceMethods);
3807 sys::swapByteOrder(p.optionalClassMethods);
3808 sys::swapByteOrder(p.instanceProperties);
3809}
3810
Kevin Enderby0fc11822015-04-01 20:57:01 +00003811inline void swapStruct(struct ivar_list64_t &il) {
3812 sys::swapByteOrder(il.entsize);
3813 sys::swapByteOrder(il.count);
3814}
3815
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003816inline void swapStruct(struct ivar_list32_t &il) {
3817 sys::swapByteOrder(il.entsize);
3818 sys::swapByteOrder(il.count);
3819}
3820
Kevin Enderby0fc11822015-04-01 20:57:01 +00003821inline void swapStruct(struct ivar64_t &i) {
3822 sys::swapByteOrder(i.offset);
3823 sys::swapByteOrder(i.name);
3824 sys::swapByteOrder(i.type);
3825 sys::swapByteOrder(i.alignment);
3826 sys::swapByteOrder(i.size);
3827}
3828
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003829inline void swapStruct(struct ivar32_t &i) {
3830 sys::swapByteOrder(i.offset);
3831 sys::swapByteOrder(i.name);
3832 sys::swapByteOrder(i.type);
3833 sys::swapByteOrder(i.alignment);
3834 sys::swapByteOrder(i.size);
3835}
3836
Kevin Enderby0fc11822015-04-01 20:57:01 +00003837inline void swapStruct(struct objc_property_list64 &pl) {
3838 sys::swapByteOrder(pl.entsize);
3839 sys::swapByteOrder(pl.count);
3840}
3841
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003842inline void swapStruct(struct objc_property_list32 &pl) {
3843 sys::swapByteOrder(pl.entsize);
3844 sys::swapByteOrder(pl.count);
3845}
3846
Kevin Enderby0fc11822015-04-01 20:57:01 +00003847inline void swapStruct(struct objc_property64 &op) {
3848 sys::swapByteOrder(op.name);
3849 sys::swapByteOrder(op.attributes);
3850}
3851
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003852inline void swapStruct(struct objc_property32 &op) {
3853 sys::swapByteOrder(op.name);
3854 sys::swapByteOrder(op.attributes);
3855}
3856
Kevin Enderby0fc11822015-04-01 20:57:01 +00003857inline void swapStruct(struct category64_t &c) {
3858 sys::swapByteOrder(c.name);
3859 sys::swapByteOrder(c.cls);
3860 sys::swapByteOrder(c.instanceMethods);
3861 sys::swapByteOrder(c.classMethods);
3862 sys::swapByteOrder(c.protocols);
3863 sys::swapByteOrder(c.instanceProperties);
3864}
3865
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003866inline void swapStruct(struct category32_t &c) {
3867 sys::swapByteOrder(c.name);
3868 sys::swapByteOrder(c.cls);
3869 sys::swapByteOrder(c.instanceMethods);
3870 sys::swapByteOrder(c.classMethods);
3871 sys::swapByteOrder(c.protocols);
3872 sys::swapByteOrder(c.instanceProperties);
3873}
3874
Kevin Enderby0fc11822015-04-01 20:57:01 +00003875inline void swapStruct(struct objc_image_info64 &o) {
3876 sys::swapByteOrder(o.version);
3877 sys::swapByteOrder(o.flags);
3878}
3879
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003880inline void swapStruct(struct objc_image_info32 &o) {
3881 sys::swapByteOrder(o.version);
3882 sys::swapByteOrder(o.flags);
3883}
3884
Kevin Enderby846c0002015-04-16 17:19:59 +00003885inline void swapStruct(struct imageInfo_t &o) {
3886 sys::swapByteOrder(o.version);
3887 sys::swapByteOrder(o.flags);
3888}
3889
Kevin Enderby0fc11822015-04-01 20:57:01 +00003890inline void swapStruct(struct message_ref64 &mr) {
3891 sys::swapByteOrder(mr.imp);
3892 sys::swapByteOrder(mr.sel);
3893}
3894
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003895inline void swapStruct(struct message_ref32 &mr) {
3896 sys::swapByteOrder(mr.imp);
3897 sys::swapByteOrder(mr.sel);
3898}
3899
Kevin Enderby846c0002015-04-16 17:19:59 +00003900inline void swapStruct(struct objc_module_t &module) {
3901 sys::swapByteOrder(module.version);
3902 sys::swapByteOrder(module.size);
3903 sys::swapByteOrder(module.name);
3904 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003905}
Kevin Enderby846c0002015-04-16 17:19:59 +00003906
3907inline void swapStruct(struct objc_symtab_t &symtab) {
3908 sys::swapByteOrder(symtab.sel_ref_cnt);
3909 sys::swapByteOrder(symtab.refs);
3910 sys::swapByteOrder(symtab.cls_def_cnt);
3911 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003912}
Kevin Enderby846c0002015-04-16 17:19:59 +00003913
3914inline void swapStruct(struct objc_class_t &objc_class) {
3915 sys::swapByteOrder(objc_class.isa);
3916 sys::swapByteOrder(objc_class.super_class);
3917 sys::swapByteOrder(objc_class.name);
3918 sys::swapByteOrder(objc_class.version);
3919 sys::swapByteOrder(objc_class.info);
3920 sys::swapByteOrder(objc_class.instance_size);
3921 sys::swapByteOrder(objc_class.ivars);
3922 sys::swapByteOrder(objc_class.methodLists);
3923 sys::swapByteOrder(objc_class.cache);
3924 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003925}
Kevin Enderby846c0002015-04-16 17:19:59 +00003926
3927inline void swapStruct(struct objc_category_t &objc_category) {
3928 sys::swapByteOrder(objc_category.category_name);
3929 sys::swapByteOrder(objc_category.class_name);
3930 sys::swapByteOrder(objc_category.instance_methods);
3931 sys::swapByteOrder(objc_category.class_methods);
3932 sys::swapByteOrder(objc_category.protocols);
3933}
3934
3935inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3936 sys::swapByteOrder(objc_ivar_list.ivar_count);
3937}
3938
3939inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3940 sys::swapByteOrder(objc_ivar.ivar_name);
3941 sys::swapByteOrder(objc_ivar.ivar_type);
3942 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003943}
Kevin Enderby846c0002015-04-16 17:19:59 +00003944
3945inline void swapStruct(struct objc_method_list_t &method_list) {
3946 sys::swapByteOrder(method_list.obsolete);
3947 sys::swapByteOrder(method_list.method_count);
3948}
3949
3950inline void swapStruct(struct objc_method_t &method) {
3951 sys::swapByteOrder(method.method_name);
3952 sys::swapByteOrder(method.method_types);
3953 sys::swapByteOrder(method.method_imp);
3954}
3955
3956inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3957 sys::swapByteOrder(protocol_list.next);
3958 sys::swapByteOrder(protocol_list.count);
3959}
3960
3961inline void swapStruct(struct objc_protocol_t &protocol) {
3962 sys::swapByteOrder(protocol.isa);
3963 sys::swapByteOrder(protocol.protocol_name);
3964 sys::swapByteOrder(protocol.protocol_list);
3965 sys::swapByteOrder(protocol.instance_methods);
3966 sys::swapByteOrder(protocol.class_methods);
3967}
3968
3969inline void swapStruct(struct objc_method_description_list_t &mdl) {
3970 sys::swapByteOrder(mdl.count);
3971}
3972
3973inline void swapStruct(struct objc_method_description_t &md) {
3974 sys::swapByteOrder(md.name);
3975 sys::swapByteOrder(md.types);
3976}
3977
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003978static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3979 struct DisassembleInfo *info);
3980
3981// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3982// to an Objective-C class and returns the class name. It is also passed the
3983// address of the pointer, so when the pointer is zero as it can be in an .o
3984// file, that is used to look for an external relocation entry with a symbol
3985// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003986static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3987 uint64_t ReferenceValue,
3988 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003989 const char *r;
3990 uint32_t offset, left;
3991 SectionRef S;
3992
3993 // The pointer_value can be 0 in an object file and have a relocation
3994 // entry for the class symbol at the ReferenceValue (the address of the
3995 // pointer).
3996 if (pointer_value == 0) {
3997 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3998 if (r == nullptr || left < sizeof(uint64_t))
3999 return nullptr;
4000 uint64_t n_value;
4001 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4002 if (symbol_name == nullptr)
4003 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00004004 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004005 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4006 return class_name + 2;
4007 else
4008 return nullptr;
4009 }
4010
4011 // The case were the pointer_value is non-zero and points to a class defined
4012 // in this Mach-O file.
4013 r = get_pointer_64(pointer_value, offset, left, S, info);
4014 if (r == nullptr || left < sizeof(struct class64_t))
4015 return nullptr;
4016 struct class64_t c;
4017 memcpy(&c, r, sizeof(struct class64_t));
4018 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4019 swapStruct(c);
4020 if (c.data == 0)
4021 return nullptr;
4022 r = get_pointer_64(c.data, offset, left, S, info);
4023 if (r == nullptr || left < sizeof(struct class_ro64_t))
4024 return nullptr;
4025 struct class_ro64_t cro;
4026 memcpy(&cro, r, sizeof(struct class_ro64_t));
4027 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4028 swapStruct(cro);
4029 if (cro.name == 0)
4030 return nullptr;
4031 const char *name = get_pointer_64(cro.name, offset, left, S, info);
4032 return name;
4033}
4034
4035// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4036// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00004037static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4038 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004039 const char *r, *name;
4040 uint32_t offset, left;
4041 SectionRef S;
4042 struct cfstring64_t cfs;
4043 uint64_t cfs_characters;
4044
4045 r = get_pointer_64(ReferenceValue, offset, left, S, info);
4046 if (r == nullptr || left < sizeof(struct cfstring64_t))
4047 return nullptr;
4048 memcpy(&cfs, r, sizeof(struct cfstring64_t));
4049 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4050 swapStruct(cfs);
4051 if (cfs.characters == 0) {
4052 uint64_t n_value;
4053 const char *symbol_name = get_symbol_64(
4054 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4055 if (symbol_name == nullptr)
4056 return nullptr;
4057 cfs_characters = n_value;
4058 } else
4059 cfs_characters = cfs.characters;
4060 name = get_pointer_64(cfs_characters, offset, left, S, info);
4061
4062 return name;
4063}
4064
4065// get_objc2_64bit_selref() is used for disassembly and is passed a the address
4066// of a pointer to an Objective-C selector reference when the pointer value is
4067// zero as in a .o file and is likely to have a external relocation entry with
4068// who's symbol's n_value is the real pointer to the selector name. If that is
4069// the case the real pointer to the selector name is returned else 0 is
4070// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00004071static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4072 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004073 uint32_t offset, left;
4074 SectionRef S;
4075
4076 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4077 if (r == nullptr || left < sizeof(uint64_t))
4078 return 0;
4079 uint64_t n_value;
4080 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4081 if (symbol_name == nullptr)
4082 return 0;
4083 return n_value;
4084}
4085
Kevin Enderby0fc11822015-04-01 20:57:01 +00004086static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4087 const char *sectname) {
4088 for (const SectionRef &Section : O->sections()) {
4089 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00004090 Expected<StringRef> SecNameOrErr = Section.getName();
4091 if (SecNameOrErr)
4092 SectName = *SecNameOrErr;
4093 else
4094 consumeError(SecNameOrErr.takeError());
4095
Kevin Enderby0fc11822015-04-01 20:57:01 +00004096 DataRefImpl Ref = Section.getRawDataRefImpl();
4097 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4098 if (SegName == segname && SectName == sectname)
4099 return Section;
4100 }
4101 return SectionRef();
4102}
4103
4104static void
4105walk_pointer_list_64(const char *listname, const SectionRef S,
4106 MachOObjectFile *O, struct DisassembleInfo *info,
4107 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4108 if (S == SectionRef())
4109 return;
4110
4111 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00004112 Expected<StringRef> SecNameOrErr = S.getName();
4113 if (SecNameOrErr)
4114 SectName = *SecNameOrErr;
4115 else
4116 consumeError(SecNameOrErr.takeError());
4117
Kevin Enderby0fc11822015-04-01 20:57:01 +00004118 DataRefImpl Ref = S.getRawDataRefImpl();
4119 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4120 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4121
Fangrui Songe1833402019-05-16 13:24:04 +00004122 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
Kevin Enderby0fc11822015-04-01 20:57:01 +00004123 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4124
4125 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4126 uint32_t left = S.getSize() - i;
4127 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4128 uint64_t p = 0;
4129 memcpy(&p, Contents + i, size);
4130 if (i + sizeof(uint64_t) > S.getSize())
4131 outs() << listname << " list pointer extends past end of (" << SegName
4132 << "," << SectName << ") section\n";
4133 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4134
4135 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4136 sys::swapByteOrder(p);
4137
4138 uint64_t n_value = 0;
4139 const char *name = get_symbol_64(i, S, info, n_value, p);
4140 if (name == nullptr)
4141 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4142
4143 if (n_value != 0) {
4144 outs() << format("0x%" PRIx64, n_value);
4145 if (p != 0)
4146 outs() << " + " << format("0x%" PRIx64, p);
4147 } else
4148 outs() << format("0x%" PRIx64, p);
4149 if (name != nullptr)
4150 outs() << " " << name;
4151 outs() << "\n";
4152
4153 p += n_value;
4154 if (func)
4155 func(p, info);
4156 }
4157}
4158
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004159static void
4160walk_pointer_list_32(const char *listname, const SectionRef S,
4161 MachOObjectFile *O, struct DisassembleInfo *info,
4162 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4163 if (S == SectionRef())
4164 return;
4165
George Rimarbcc00e12019-08-14 11:10:11 +00004166 StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004167 DataRefImpl Ref = S.getRawDataRefImpl();
4168 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4169 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4170
Fangrui Songe1833402019-05-16 13:24:04 +00004171 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004172 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4173
4174 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4175 uint32_t left = S.getSize() - i;
4176 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4177 uint32_t p = 0;
4178 memcpy(&p, Contents + i, size);
4179 if (i + sizeof(uint32_t) > S.getSize())
4180 outs() << listname << " list pointer extends past end of (" << SegName
4181 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00004182 uint32_t Address = S.getAddress() + i;
4183 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004184
4185 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4186 sys::swapByteOrder(p);
4187 outs() << format("0x%" PRIx32, p);
4188
4189 const char *name = get_symbol_32(i, S, info, p);
4190 if (name != nullptr)
4191 outs() << " " << name;
4192 outs() << "\n";
4193
4194 if (func)
4195 func(p, info);
4196 }
4197}
4198
4199static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004200 if (layout_map == nullptr)
4201 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004202 outs() << " layout map: ";
4203 do {
4204 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4205 left--;
4206 layout_map++;
4207 } while (*layout_map != '\0' && left != 0);
4208 outs() << "\n";
4209}
4210
Kevin Enderby0fc11822015-04-01 20:57:01 +00004211static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4212 uint32_t offset, left;
4213 SectionRef S;
4214 const char *layout_map;
4215
4216 if (p == 0)
4217 return;
4218 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004219 print_layout_map(layout_map, left);
4220}
4221
4222static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4223 uint32_t offset, left;
4224 SectionRef S;
4225 const char *layout_map;
4226
4227 if (p == 0)
4228 return;
4229 layout_map = get_pointer_32(p, offset, left, S, info);
4230 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004231}
4232
4233static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4234 const char *indent) {
4235 struct method_list64_t ml;
4236 struct method64_t m;
4237 const char *r;
4238 uint32_t offset, xoffset, left, i;
4239 SectionRef S, xS;
4240 const char *name, *sym_name;
4241 uint64_t n_value;
4242
4243 r = get_pointer_64(p, offset, left, S, info);
4244 if (r == nullptr)
4245 return;
4246 memset(&ml, '\0', sizeof(struct method_list64_t));
4247 if (left < sizeof(struct method_list64_t)) {
4248 memcpy(&ml, r, left);
4249 outs() << " (method_list_t entends past the end of the section)\n";
4250 } else
4251 memcpy(&ml, r, sizeof(struct method_list64_t));
4252 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4253 swapStruct(ml);
4254 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4255 outs() << indent << "\t\t count " << ml.count << "\n";
4256
4257 p += sizeof(struct method_list64_t);
4258 offset += sizeof(struct method_list64_t);
4259 for (i = 0; i < ml.count; i++) {
4260 r = get_pointer_64(p, offset, left, S, info);
4261 if (r == nullptr)
4262 return;
4263 memset(&m, '\0', sizeof(struct method64_t));
4264 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004265 memcpy(&m, r, left);
4266 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00004267 } else
4268 memcpy(&m, r, sizeof(struct method64_t));
4269 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4270 swapStruct(m);
4271
4272 outs() << indent << "\t\t name ";
4273 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4274 info, n_value, m.name);
4275 if (n_value != 0) {
4276 if (info->verbose && sym_name != nullptr)
4277 outs() << sym_name;
4278 else
4279 outs() << format("0x%" PRIx64, n_value);
4280 if (m.name != 0)
4281 outs() << " + " << format("0x%" PRIx64, m.name);
4282 } else
4283 outs() << format("0x%" PRIx64, m.name);
4284 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4285 if (name != nullptr)
4286 outs() << format(" %.*s", left, name);
4287 outs() << "\n";
4288
4289 outs() << indent << "\t\t types ";
4290 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4291 info, n_value, m.types);
4292 if (n_value != 0) {
4293 if (info->verbose && sym_name != nullptr)
4294 outs() << sym_name;
4295 else
4296 outs() << format("0x%" PRIx64, n_value);
4297 if (m.types != 0)
4298 outs() << " + " << format("0x%" PRIx64, m.types);
4299 } else
4300 outs() << format("0x%" PRIx64, m.types);
4301 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4302 if (name != nullptr)
4303 outs() << format(" %.*s", left, name);
4304 outs() << "\n";
4305
4306 outs() << indent << "\t\t imp ";
4307 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4308 n_value, m.imp);
4309 if (info->verbose && name == nullptr) {
4310 if (n_value != 0) {
4311 outs() << format("0x%" PRIx64, n_value) << " ";
4312 if (m.imp != 0)
4313 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4314 } else
4315 outs() << format("0x%" PRIx64, m.imp) << " ";
4316 }
4317 if (name != nullptr)
4318 outs() << name;
4319 outs() << "\n";
4320
4321 p += sizeof(struct method64_t);
4322 offset += sizeof(struct method64_t);
4323 }
4324}
4325
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004326static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4327 const char *indent) {
4328 struct method_list32_t ml;
4329 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00004330 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004331 uint32_t offset, xoffset, left, i;
4332 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004333
4334 r = get_pointer_32(p, offset, left, S, info);
4335 if (r == nullptr)
4336 return;
4337 memset(&ml, '\0', sizeof(struct method_list32_t));
4338 if (left < sizeof(struct method_list32_t)) {
4339 memcpy(&ml, r, left);
4340 outs() << " (method_list_t entends past the end of the section)\n";
4341 } else
4342 memcpy(&ml, r, sizeof(struct method_list32_t));
4343 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4344 swapStruct(ml);
4345 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4346 outs() << indent << "\t\t count " << ml.count << "\n";
4347
4348 p += sizeof(struct method_list32_t);
4349 offset += sizeof(struct method_list32_t);
4350 for (i = 0; i < ml.count; i++) {
4351 r = get_pointer_32(p, offset, left, S, info);
4352 if (r == nullptr)
4353 return;
4354 memset(&m, '\0', sizeof(struct method32_t));
4355 if (left < sizeof(struct method32_t)) {
4356 memcpy(&ml, r, left);
4357 outs() << indent << " (method_t entends past the end of the section)\n";
4358 } else
4359 memcpy(&m, r, sizeof(struct method32_t));
4360 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4361 swapStruct(m);
4362
4363 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4364 name = get_pointer_32(m.name, xoffset, left, xS, info);
4365 if (name != nullptr)
4366 outs() << format(" %.*s", left, name);
4367 outs() << "\n";
4368
4369 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4370 name = get_pointer_32(m.types, xoffset, left, xS, info);
4371 if (name != nullptr)
4372 outs() << format(" %.*s", left, name);
4373 outs() << "\n";
4374
4375 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4376 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4377 m.imp);
4378 if (name != nullptr)
4379 outs() << " " << name;
4380 outs() << "\n";
4381
4382 p += sizeof(struct method32_t);
4383 offset += sizeof(struct method32_t);
4384 }
4385}
4386
Kevin Enderby846c0002015-04-16 17:19:59 +00004387static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4388 uint32_t offset, left, xleft;
4389 SectionRef S;
4390 struct objc_method_list_t method_list;
4391 struct objc_method_t method;
4392 const char *r, *methods, *name, *SymbolName;
4393 int32_t i;
4394
4395 r = get_pointer_32(p, offset, left, S, info, true);
4396 if (r == nullptr)
4397 return true;
4398
4399 outs() << "\n";
4400 if (left > sizeof(struct objc_method_list_t)) {
4401 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4402 } else {
4403 outs() << "\t\t objc_method_list extends past end of the section\n";
4404 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4405 memcpy(&method_list, r, left);
4406 }
4407 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4408 swapStruct(method_list);
4409
4410 outs() << "\t\t obsolete "
4411 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4412 outs() << "\t\t method_count " << method_list.method_count << "\n";
4413
4414 methods = r + sizeof(struct objc_method_list_t);
4415 for (i = 0; i < method_list.method_count; i++) {
4416 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4417 outs() << "\t\t remaining method's extend past the of the section\n";
4418 break;
4419 }
4420 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4421 sizeof(struct objc_method_t));
4422 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4423 swapStruct(method);
4424
4425 outs() << "\t\t method_name "
4426 << format("0x%08" PRIx32, method.method_name);
4427 if (info->verbose) {
4428 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4429 if (name != nullptr)
4430 outs() << format(" %.*s", xleft, name);
4431 else
4432 outs() << " (not in an __OBJC section)";
4433 }
4434 outs() << "\n";
4435
4436 outs() << "\t\t method_types "
4437 << format("0x%08" PRIx32, method.method_types);
4438 if (info->verbose) {
4439 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4440 if (name != nullptr)
4441 outs() << format(" %.*s", xleft, name);
4442 else
4443 outs() << " (not in an __OBJC section)";
4444 }
4445 outs() << "\n";
4446
4447 outs() << "\t\t method_imp "
4448 << format("0x%08" PRIx32, method.method_imp) << " ";
4449 if (info->verbose) {
4450 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4451 if (SymbolName != nullptr)
4452 outs() << SymbolName;
4453 }
4454 outs() << "\n";
4455 }
4456 return false;
4457}
4458
Kevin Enderby0fc11822015-04-01 20:57:01 +00004459static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4460 struct protocol_list64_t pl;
4461 uint64_t q, n_value;
4462 struct protocol64_t pc;
4463 const char *r;
4464 uint32_t offset, xoffset, left, i;
4465 SectionRef S, xS;
4466 const char *name, *sym_name;
4467
4468 r = get_pointer_64(p, offset, left, S, info);
4469 if (r == nullptr)
4470 return;
4471 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4472 if (left < sizeof(struct protocol_list64_t)) {
4473 memcpy(&pl, r, left);
4474 outs() << " (protocol_list_t entends past the end of the section)\n";
4475 } else
4476 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4477 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4478 swapStruct(pl);
4479 outs() << " count " << pl.count << "\n";
4480
4481 p += sizeof(struct protocol_list64_t);
4482 offset += sizeof(struct protocol_list64_t);
4483 for (i = 0; i < pl.count; i++) {
4484 r = get_pointer_64(p, offset, left, S, info);
4485 if (r == nullptr)
4486 return;
4487 q = 0;
4488 if (left < sizeof(uint64_t)) {
4489 memcpy(&q, r, left);
4490 outs() << " (protocol_t * entends past the end of the section)\n";
4491 } else
4492 memcpy(&q, r, sizeof(uint64_t));
4493 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4494 sys::swapByteOrder(q);
4495
4496 outs() << "\t\t list[" << i << "] ";
4497 sym_name = get_symbol_64(offset, S, info, n_value, q);
4498 if (n_value != 0) {
4499 if (info->verbose && sym_name != nullptr)
4500 outs() << sym_name;
4501 else
4502 outs() << format("0x%" PRIx64, n_value);
4503 if (q != 0)
4504 outs() << " + " << format("0x%" PRIx64, q);
4505 } else
4506 outs() << format("0x%" PRIx64, q);
4507 outs() << " (struct protocol_t *)\n";
4508
4509 r = get_pointer_64(q + n_value, offset, left, S, info);
4510 if (r == nullptr)
4511 return;
4512 memset(&pc, '\0', sizeof(struct protocol64_t));
4513 if (left < sizeof(struct protocol64_t)) {
4514 memcpy(&pc, r, left);
4515 outs() << " (protocol_t entends past the end of the section)\n";
4516 } else
4517 memcpy(&pc, r, sizeof(struct protocol64_t));
4518 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4519 swapStruct(pc);
4520
4521 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4522
4523 outs() << "\t\t\t name ";
4524 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4525 info, n_value, pc.name);
4526 if (n_value != 0) {
4527 if (info->verbose && sym_name != nullptr)
4528 outs() << sym_name;
4529 else
4530 outs() << format("0x%" PRIx64, n_value);
4531 if (pc.name != 0)
4532 outs() << " + " << format("0x%" PRIx64, pc.name);
4533 } else
4534 outs() << format("0x%" PRIx64, pc.name);
4535 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4536 if (name != nullptr)
4537 outs() << format(" %.*s", left, name);
4538 outs() << "\n";
4539
4540 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4541
4542 outs() << "\t\t instanceMethods ";
4543 sym_name =
4544 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4545 S, info, n_value, pc.instanceMethods);
4546 if (n_value != 0) {
4547 if (info->verbose && sym_name != nullptr)
4548 outs() << sym_name;
4549 else
4550 outs() << format("0x%" PRIx64, n_value);
4551 if (pc.instanceMethods != 0)
4552 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4553 } else
4554 outs() << format("0x%" PRIx64, pc.instanceMethods);
4555 outs() << " (struct method_list_t *)\n";
4556 if (pc.instanceMethods + n_value != 0)
4557 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4558
4559 outs() << "\t\t classMethods ";
4560 sym_name =
4561 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4562 info, n_value, pc.classMethods);
4563 if (n_value != 0) {
4564 if (info->verbose && sym_name != nullptr)
4565 outs() << sym_name;
4566 else
4567 outs() << format("0x%" PRIx64, n_value);
4568 if (pc.classMethods != 0)
4569 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4570 } else
4571 outs() << format("0x%" PRIx64, pc.classMethods);
4572 outs() << " (struct method_list_t *)\n";
4573 if (pc.classMethods + n_value != 0)
4574 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4575
4576 outs() << "\t optionalInstanceMethods "
4577 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4578 outs() << "\t optionalClassMethods "
4579 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4580 outs() << "\t instanceProperties "
4581 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4582
4583 p += sizeof(uint64_t);
4584 offset += sizeof(uint64_t);
4585 }
4586}
4587
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004588static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4589 struct protocol_list32_t pl;
4590 uint32_t q;
4591 struct protocol32_t pc;
4592 const char *r;
4593 uint32_t offset, xoffset, left, i;
4594 SectionRef S, xS;
4595 const char *name;
4596
4597 r = get_pointer_32(p, offset, left, S, info);
4598 if (r == nullptr)
4599 return;
4600 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4601 if (left < sizeof(struct protocol_list32_t)) {
4602 memcpy(&pl, r, left);
4603 outs() << " (protocol_list_t entends past the end of the section)\n";
4604 } else
4605 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4606 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4607 swapStruct(pl);
4608 outs() << " count " << pl.count << "\n";
4609
4610 p += sizeof(struct protocol_list32_t);
4611 offset += sizeof(struct protocol_list32_t);
4612 for (i = 0; i < pl.count; i++) {
4613 r = get_pointer_32(p, offset, left, S, info);
4614 if (r == nullptr)
4615 return;
4616 q = 0;
4617 if (left < sizeof(uint32_t)) {
4618 memcpy(&q, r, left);
4619 outs() << " (protocol_t * entends past the end of the section)\n";
4620 } else
4621 memcpy(&q, r, sizeof(uint32_t));
4622 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4623 sys::swapByteOrder(q);
4624 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4625 << " (struct protocol_t *)\n";
4626 r = get_pointer_32(q, offset, left, S, info);
4627 if (r == nullptr)
4628 return;
4629 memset(&pc, '\0', sizeof(struct protocol32_t));
4630 if (left < sizeof(struct protocol32_t)) {
4631 memcpy(&pc, r, left);
4632 outs() << " (protocol_t entends past the end of the section)\n";
4633 } else
4634 memcpy(&pc, r, sizeof(struct protocol32_t));
4635 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4636 swapStruct(pc);
4637 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4638 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4639 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4640 if (name != nullptr)
4641 outs() << format(" %.*s", left, name);
4642 outs() << "\n";
4643 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4644 outs() << "\t\t instanceMethods "
4645 << format("0x%" PRIx32, pc.instanceMethods)
4646 << " (struct method_list_t *)\n";
4647 if (pc.instanceMethods != 0)
4648 print_method_list32_t(pc.instanceMethods, info, "\t");
4649 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4650 << " (struct method_list_t *)\n";
4651 if (pc.classMethods != 0)
4652 print_method_list32_t(pc.classMethods, info, "\t");
4653 outs() << "\t optionalInstanceMethods "
4654 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4655 outs() << "\t optionalClassMethods "
4656 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4657 outs() << "\t instanceProperties "
4658 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4659 p += sizeof(uint32_t);
4660 offset += sizeof(uint32_t);
4661 }
4662}
4663
Kevin Enderby846c0002015-04-16 17:19:59 +00004664static void print_indent(uint32_t indent) {
4665 for (uint32_t i = 0; i < indent;) {
4666 if (indent - i >= 8) {
4667 outs() << "\t";
4668 i += 8;
4669 } else {
4670 for (uint32_t j = i; j < indent; j++)
4671 outs() << " ";
4672 return;
4673 }
4674 }
4675}
4676
4677static bool print_method_description_list(uint32_t p, uint32_t indent,
4678 struct DisassembleInfo *info) {
4679 uint32_t offset, left, xleft;
4680 SectionRef S;
4681 struct objc_method_description_list_t mdl;
4682 struct objc_method_description_t md;
4683 const char *r, *list, *name;
4684 int32_t i;
4685
4686 r = get_pointer_32(p, offset, left, S, info, true);
4687 if (r == nullptr)
4688 return true;
4689
4690 outs() << "\n";
4691 if (left > sizeof(struct objc_method_description_list_t)) {
4692 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4693 } else {
4694 print_indent(indent);
4695 outs() << " objc_method_description_list extends past end of the section\n";
4696 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4697 memcpy(&mdl, r, left);
4698 }
4699 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4700 swapStruct(mdl);
4701
4702 print_indent(indent);
4703 outs() << " count " << mdl.count << "\n";
4704
4705 list = r + sizeof(struct objc_method_description_list_t);
4706 for (i = 0; i < mdl.count; i++) {
4707 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4708 print_indent(indent);
4709 outs() << " remaining list entries extend past the of the section\n";
4710 break;
4711 }
4712 print_indent(indent);
4713 outs() << " list[" << i << "]\n";
4714 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4715 sizeof(struct objc_method_description_t));
4716 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4717 swapStruct(md);
4718
4719 print_indent(indent);
4720 outs() << " name " << format("0x%08" PRIx32, md.name);
4721 if (info->verbose) {
4722 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4723 if (name != nullptr)
4724 outs() << format(" %.*s", xleft, name);
4725 else
4726 outs() << " (not in an __OBJC section)";
4727 }
4728 outs() << "\n";
4729
4730 print_indent(indent);
4731 outs() << " types " << format("0x%08" PRIx32, md.types);
4732 if (info->verbose) {
4733 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4734 if (name != nullptr)
4735 outs() << format(" %.*s", xleft, name);
4736 else
4737 outs() << " (not in an __OBJC section)";
4738 }
4739 outs() << "\n";
4740 }
4741 return false;
4742}
4743
4744static bool print_protocol_list(uint32_t p, uint32_t indent,
4745 struct DisassembleInfo *info);
4746
4747static bool print_protocol(uint32_t p, uint32_t indent,
4748 struct DisassembleInfo *info) {
4749 uint32_t offset, left;
4750 SectionRef S;
4751 struct objc_protocol_t protocol;
4752 const char *r, *name;
4753
4754 r = get_pointer_32(p, offset, left, S, info, true);
4755 if (r == nullptr)
4756 return true;
4757
4758 outs() << "\n";
4759 if (left >= sizeof(struct objc_protocol_t)) {
4760 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4761 } else {
4762 print_indent(indent);
4763 outs() << " Protocol extends past end of the section\n";
4764 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4765 memcpy(&protocol, r, left);
4766 }
4767 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4768 swapStruct(protocol);
4769
4770 print_indent(indent);
4771 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4772 << "\n";
4773
4774 print_indent(indent);
4775 outs() << " protocol_name "
4776 << format("0x%08" PRIx32, protocol.protocol_name);
4777 if (info->verbose) {
4778 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4779 if (name != nullptr)
4780 outs() << format(" %.*s", left, name);
4781 else
4782 outs() << " (not in an __OBJC section)";
4783 }
4784 outs() << "\n";
4785
4786 print_indent(indent);
4787 outs() << " protocol_list "
4788 << format("0x%08" PRIx32, protocol.protocol_list);
4789 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4790 outs() << " (not in an __OBJC section)\n";
4791
4792 print_indent(indent);
4793 outs() << " instance_methods "
4794 << format("0x%08" PRIx32, protocol.instance_methods);
4795 if (print_method_description_list(protocol.instance_methods, indent, info))
4796 outs() << " (not in an __OBJC section)\n";
4797
4798 print_indent(indent);
4799 outs() << " class_methods "
4800 << format("0x%08" PRIx32, protocol.class_methods);
4801 if (print_method_description_list(protocol.class_methods, indent, info))
4802 outs() << " (not in an __OBJC section)\n";
4803
4804 return false;
4805}
4806
4807static bool print_protocol_list(uint32_t p, uint32_t indent,
4808 struct DisassembleInfo *info) {
4809 uint32_t offset, left, l;
4810 SectionRef S;
4811 struct objc_protocol_list_t protocol_list;
4812 const char *r, *list;
4813 int32_t i;
4814
4815 r = get_pointer_32(p, offset, left, S, info, true);
4816 if (r == nullptr)
4817 return true;
4818
4819 outs() << "\n";
4820 if (left > sizeof(struct objc_protocol_list_t)) {
4821 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4822 } else {
4823 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4824 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4825 memcpy(&protocol_list, r, left);
4826 }
4827 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4828 swapStruct(protocol_list);
4829
4830 print_indent(indent);
4831 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4832 << "\n";
4833 print_indent(indent);
4834 outs() << " count " << protocol_list.count << "\n";
4835
4836 list = r + sizeof(struct objc_protocol_list_t);
4837 for (i = 0; i < protocol_list.count; i++) {
4838 if ((i + 1) * sizeof(uint32_t) > left) {
4839 outs() << "\t\t remaining list entries extend past the of the section\n";
4840 break;
4841 }
4842 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4843 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4844 sys::swapByteOrder(l);
4845
4846 print_indent(indent);
4847 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4848 if (print_protocol(l, indent, info))
4849 outs() << "(not in an __OBJC section)\n";
4850 }
4851 return false;
4852}
4853
Kevin Enderby0fc11822015-04-01 20:57:01 +00004854static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4855 struct ivar_list64_t il;
4856 struct ivar64_t i;
4857 const char *r;
4858 uint32_t offset, xoffset, left, j;
4859 SectionRef S, xS;
4860 const char *name, *sym_name, *ivar_offset_p;
4861 uint64_t ivar_offset, n_value;
4862
4863 r = get_pointer_64(p, offset, left, S, info);
4864 if (r == nullptr)
4865 return;
4866 memset(&il, '\0', sizeof(struct ivar_list64_t));
4867 if (left < sizeof(struct ivar_list64_t)) {
4868 memcpy(&il, r, left);
4869 outs() << " (ivar_list_t entends past the end of the section)\n";
4870 } else
4871 memcpy(&il, r, sizeof(struct ivar_list64_t));
4872 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4873 swapStruct(il);
4874 outs() << " entsize " << il.entsize << "\n";
4875 outs() << " count " << il.count << "\n";
4876
4877 p += sizeof(struct ivar_list64_t);
4878 offset += sizeof(struct ivar_list64_t);
4879 for (j = 0; j < il.count; j++) {
4880 r = get_pointer_64(p, offset, left, S, info);
4881 if (r == nullptr)
4882 return;
4883 memset(&i, '\0', sizeof(struct ivar64_t));
4884 if (left < sizeof(struct ivar64_t)) {
4885 memcpy(&i, r, left);
4886 outs() << " (ivar_t entends past the end of the section)\n";
4887 } else
4888 memcpy(&i, r, sizeof(struct ivar64_t));
4889 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4890 swapStruct(i);
4891
4892 outs() << "\t\t\t offset ";
4893 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4894 info, n_value, i.offset);
4895 if (n_value != 0) {
4896 if (info->verbose && sym_name != nullptr)
4897 outs() << sym_name;
4898 else
4899 outs() << format("0x%" PRIx64, n_value);
4900 if (i.offset != 0)
4901 outs() << " + " << format("0x%" PRIx64, i.offset);
4902 } else
4903 outs() << format("0x%" PRIx64, i.offset);
4904 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4905 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4906 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4907 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4908 sys::swapByteOrder(ivar_offset);
4909 outs() << " " << ivar_offset << "\n";
4910 } else
4911 outs() << "\n";
4912
4913 outs() << "\t\t\t name ";
4914 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4915 n_value, i.name);
4916 if (n_value != 0) {
4917 if (info->verbose && sym_name != nullptr)
4918 outs() << sym_name;
4919 else
4920 outs() << format("0x%" PRIx64, n_value);
4921 if (i.name != 0)
4922 outs() << " + " << format("0x%" PRIx64, i.name);
4923 } else
4924 outs() << format("0x%" PRIx64, i.name);
4925 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4926 if (name != nullptr)
4927 outs() << format(" %.*s", left, name);
4928 outs() << "\n";
4929
4930 outs() << "\t\t\t type ";
4931 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4932 n_value, i.name);
4933 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4934 if (n_value != 0) {
4935 if (info->verbose && sym_name != nullptr)
4936 outs() << sym_name;
4937 else
4938 outs() << format("0x%" PRIx64, n_value);
4939 if (i.type != 0)
4940 outs() << " + " << format("0x%" PRIx64, i.type);
4941 } else
4942 outs() << format("0x%" PRIx64, i.type);
4943 if (name != nullptr)
4944 outs() << format(" %.*s", left, name);
4945 outs() << "\n";
4946
4947 outs() << "\t\t\talignment " << i.alignment << "\n";
4948 outs() << "\t\t\t size " << i.size << "\n";
4949
4950 p += sizeof(struct ivar64_t);
4951 offset += sizeof(struct ivar64_t);
4952 }
4953}
4954
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004955static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4956 struct ivar_list32_t il;
4957 struct ivar32_t i;
4958 const char *r;
4959 uint32_t offset, xoffset, left, j;
4960 SectionRef S, xS;
4961 const char *name, *ivar_offset_p;
4962 uint32_t ivar_offset;
4963
4964 r = get_pointer_32(p, offset, left, S, info);
4965 if (r == nullptr)
4966 return;
4967 memset(&il, '\0', sizeof(struct ivar_list32_t));
4968 if (left < sizeof(struct ivar_list32_t)) {
4969 memcpy(&il, r, left);
4970 outs() << " (ivar_list_t entends past the end of the section)\n";
4971 } else
4972 memcpy(&il, r, sizeof(struct ivar_list32_t));
4973 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4974 swapStruct(il);
4975 outs() << " entsize " << il.entsize << "\n";
4976 outs() << " count " << il.count << "\n";
4977
4978 p += sizeof(struct ivar_list32_t);
4979 offset += sizeof(struct ivar_list32_t);
4980 for (j = 0; j < il.count; j++) {
4981 r = get_pointer_32(p, offset, left, S, info);
4982 if (r == nullptr)
4983 return;
4984 memset(&i, '\0', sizeof(struct ivar32_t));
4985 if (left < sizeof(struct ivar32_t)) {
4986 memcpy(&i, r, left);
4987 outs() << " (ivar_t entends past the end of the section)\n";
4988 } else
4989 memcpy(&i, r, sizeof(struct ivar32_t));
4990 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4991 swapStruct(i);
4992
4993 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4994 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4995 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4996 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4997 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4998 sys::swapByteOrder(ivar_offset);
4999 outs() << " " << ivar_offset << "\n";
5000 } else
5001 outs() << "\n";
5002
5003 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
5004 name = get_pointer_32(i.name, xoffset, left, xS, info);
5005 if (name != nullptr)
5006 outs() << format(" %.*s", left, name);
5007 outs() << "\n";
5008
5009 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
5010 name = get_pointer_32(i.type, xoffset, left, xS, info);
5011 if (name != nullptr)
5012 outs() << format(" %.*s", left, name);
5013 outs() << "\n";
5014
5015 outs() << "\t\t\talignment " << i.alignment << "\n";
5016 outs() << "\t\t\t size " << i.size << "\n";
5017
5018 p += sizeof(struct ivar32_t);
5019 offset += sizeof(struct ivar32_t);
5020 }
5021}
5022
Kevin Enderby0fc11822015-04-01 20:57:01 +00005023static void print_objc_property_list64(uint64_t p,
5024 struct DisassembleInfo *info) {
5025 struct objc_property_list64 opl;
5026 struct objc_property64 op;
5027 const char *r;
5028 uint32_t offset, xoffset, left, j;
5029 SectionRef S, xS;
5030 const char *name, *sym_name;
5031 uint64_t n_value;
5032
5033 r = get_pointer_64(p, offset, left, S, info);
5034 if (r == nullptr)
5035 return;
5036 memset(&opl, '\0', sizeof(struct objc_property_list64));
5037 if (left < sizeof(struct objc_property_list64)) {
5038 memcpy(&opl, r, left);
5039 outs() << " (objc_property_list entends past the end of the section)\n";
5040 } else
5041 memcpy(&opl, r, sizeof(struct objc_property_list64));
5042 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5043 swapStruct(opl);
5044 outs() << " entsize " << opl.entsize << "\n";
5045 outs() << " count " << opl.count << "\n";
5046
5047 p += sizeof(struct objc_property_list64);
5048 offset += sizeof(struct objc_property_list64);
5049 for (j = 0; j < opl.count; j++) {
5050 r = get_pointer_64(p, offset, left, S, info);
5051 if (r == nullptr)
5052 return;
5053 memset(&op, '\0', sizeof(struct objc_property64));
5054 if (left < sizeof(struct objc_property64)) {
5055 memcpy(&op, r, left);
5056 outs() << " (objc_property entends past the end of the section)\n";
5057 } else
5058 memcpy(&op, r, sizeof(struct objc_property64));
5059 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5060 swapStruct(op);
5061
5062 outs() << "\t\t\t name ";
5063 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5064 info, n_value, op.name);
5065 if (n_value != 0) {
5066 if (info->verbose && sym_name != nullptr)
5067 outs() << sym_name;
5068 else
5069 outs() << format("0x%" PRIx64, n_value);
5070 if (op.name != 0)
5071 outs() << " + " << format("0x%" PRIx64, op.name);
5072 } else
5073 outs() << format("0x%" PRIx64, op.name);
5074 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5075 if (name != nullptr)
5076 outs() << format(" %.*s", left, name);
5077 outs() << "\n";
5078
5079 outs() << "\t\t\tattributes ";
5080 sym_name =
5081 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5082 info, n_value, op.attributes);
5083 if (n_value != 0) {
5084 if (info->verbose && sym_name != nullptr)
5085 outs() << sym_name;
5086 else
5087 outs() << format("0x%" PRIx64, n_value);
5088 if (op.attributes != 0)
5089 outs() << " + " << format("0x%" PRIx64, op.attributes);
5090 } else
5091 outs() << format("0x%" PRIx64, op.attributes);
5092 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5093 if (name != nullptr)
5094 outs() << format(" %.*s", left, name);
5095 outs() << "\n";
5096
5097 p += sizeof(struct objc_property64);
5098 offset += sizeof(struct objc_property64);
5099 }
5100}
5101
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005102static void print_objc_property_list32(uint32_t p,
5103 struct DisassembleInfo *info) {
5104 struct objc_property_list32 opl;
5105 struct objc_property32 op;
5106 const char *r;
5107 uint32_t offset, xoffset, left, j;
5108 SectionRef S, xS;
5109 const char *name;
5110
5111 r = get_pointer_32(p, offset, left, S, info);
5112 if (r == nullptr)
5113 return;
5114 memset(&opl, '\0', sizeof(struct objc_property_list32));
5115 if (left < sizeof(struct objc_property_list32)) {
5116 memcpy(&opl, r, left);
5117 outs() << " (objc_property_list entends past the end of the section)\n";
5118 } else
5119 memcpy(&opl, r, sizeof(struct objc_property_list32));
5120 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5121 swapStruct(opl);
5122 outs() << " entsize " << opl.entsize << "\n";
5123 outs() << " count " << opl.count << "\n";
5124
5125 p += sizeof(struct objc_property_list32);
5126 offset += sizeof(struct objc_property_list32);
5127 for (j = 0; j < opl.count; j++) {
5128 r = get_pointer_32(p, offset, left, S, info);
5129 if (r == nullptr)
5130 return;
5131 memset(&op, '\0', sizeof(struct objc_property32));
5132 if (left < sizeof(struct objc_property32)) {
5133 memcpy(&op, r, left);
5134 outs() << " (objc_property entends past the end of the section)\n";
5135 } else
5136 memcpy(&op, r, sizeof(struct objc_property32));
5137 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5138 swapStruct(op);
5139
5140 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
5141 name = get_pointer_32(op.name, xoffset, left, xS, info);
5142 if (name != nullptr)
5143 outs() << format(" %.*s", left, name);
5144 outs() << "\n";
5145
5146 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5147 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5148 if (name != nullptr)
5149 outs() << format(" %.*s", left, name);
5150 outs() << "\n";
5151
5152 p += sizeof(struct objc_property32);
5153 offset += sizeof(struct objc_property32);
5154 }
5155}
5156
Richard Smith81ff44d2015-10-09 22:09:56 +00005157static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00005158 bool &is_meta_class) {
5159 struct class_ro64_t cro;
5160 const char *r;
5161 uint32_t offset, xoffset, left;
5162 SectionRef S, xS;
5163 const char *name, *sym_name;
5164 uint64_t n_value;
5165
5166 r = get_pointer_64(p, offset, left, S, info);
5167 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00005168 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00005169 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005170 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5171 swapStruct(cro);
5172 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5173 if (cro.flags & RO_META)
5174 outs() << " RO_META";
5175 if (cro.flags & RO_ROOT)
5176 outs() << " RO_ROOT";
5177 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5178 outs() << " RO_HAS_CXX_STRUCTORS";
5179 outs() << "\n";
5180 outs() << " instanceStart " << cro.instanceStart << "\n";
5181 outs() << " instanceSize " << cro.instanceSize << "\n";
5182 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5183 << "\n";
5184 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5185 << "\n";
5186 print_layout_map64(cro.ivarLayout, info);
5187
5188 outs() << " name ";
5189 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5190 info, n_value, cro.name);
5191 if (n_value != 0) {
5192 if (info->verbose && sym_name != nullptr)
5193 outs() << sym_name;
5194 else
5195 outs() << format("0x%" PRIx64, n_value);
5196 if (cro.name != 0)
5197 outs() << " + " << format("0x%" PRIx64, cro.name);
5198 } else
5199 outs() << format("0x%" PRIx64, cro.name);
5200 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5201 if (name != nullptr)
5202 outs() << format(" %.*s", left, name);
5203 outs() << "\n";
5204
5205 outs() << " baseMethods ";
5206 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5207 S, info, n_value, cro.baseMethods);
5208 if (n_value != 0) {
5209 if (info->verbose && sym_name != nullptr)
5210 outs() << sym_name;
5211 else
5212 outs() << format("0x%" PRIx64, n_value);
5213 if (cro.baseMethods != 0)
5214 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5215 } else
5216 outs() << format("0x%" PRIx64, cro.baseMethods);
5217 outs() << " (struct method_list_t *)\n";
5218 if (cro.baseMethods + n_value != 0)
5219 print_method_list64_t(cro.baseMethods + n_value, info, "");
5220
5221 outs() << " baseProtocols ";
5222 sym_name =
5223 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5224 info, n_value, cro.baseProtocols);
5225 if (n_value != 0) {
5226 if (info->verbose && sym_name != nullptr)
5227 outs() << sym_name;
5228 else
5229 outs() << format("0x%" PRIx64, n_value);
5230 if (cro.baseProtocols != 0)
5231 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5232 } else
5233 outs() << format("0x%" PRIx64, cro.baseProtocols);
5234 outs() << "\n";
5235 if (cro.baseProtocols + n_value != 0)
5236 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5237
5238 outs() << " ivars ";
5239 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005240 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005241 if (n_value != 0) {
5242 if (info->verbose && sym_name != nullptr)
5243 outs() << sym_name;
5244 else
5245 outs() << format("0x%" PRIx64, n_value);
5246 if (cro.ivars != 0)
5247 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5248 } else
5249 outs() << format("0x%" PRIx64, cro.ivars);
5250 outs() << "\n";
5251 if (cro.ivars + n_value != 0)
5252 print_ivar_list64_t(cro.ivars + n_value, info);
5253
5254 outs() << " weakIvarLayout ";
5255 sym_name =
5256 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5257 info, n_value, cro.weakIvarLayout);
5258 if (n_value != 0) {
5259 if (info->verbose && sym_name != nullptr)
5260 outs() << sym_name;
5261 else
5262 outs() << format("0x%" PRIx64, n_value);
5263 if (cro.weakIvarLayout != 0)
5264 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5265 } else
5266 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5267 outs() << "\n";
5268 print_layout_map64(cro.weakIvarLayout + n_value, info);
5269
5270 outs() << " baseProperties ";
5271 sym_name =
5272 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5273 info, n_value, cro.baseProperties);
5274 if (n_value != 0) {
5275 if (info->verbose && sym_name != nullptr)
5276 outs() << sym_name;
5277 else
5278 outs() << format("0x%" PRIx64, n_value);
5279 if (cro.baseProperties != 0)
5280 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5281 } else
5282 outs() << format("0x%" PRIx64, cro.baseProperties);
5283 outs() << "\n";
5284 if (cro.baseProperties + n_value != 0)
5285 print_objc_property_list64(cro.baseProperties + n_value, info);
5286
Rafael Espindolab9091322015-10-24 23:19:10 +00005287 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005288 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005289}
5290
Richard Smith81ff44d2015-10-09 22:09:56 +00005291static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005292 bool &is_meta_class) {
5293 struct class_ro32_t cro;
5294 const char *r;
5295 uint32_t offset, xoffset, left;
5296 SectionRef S, xS;
5297 const char *name;
5298
5299 r = get_pointer_32(p, offset, left, S, info);
5300 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00005301 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005302 memset(&cro, '\0', sizeof(struct class_ro32_t));
5303 if (left < sizeof(struct class_ro32_t)) {
5304 memcpy(&cro, r, left);
5305 outs() << " (class_ro_t entends past the end of the section)\n";
5306 } else
5307 memcpy(&cro, r, sizeof(struct class_ro32_t));
5308 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5309 swapStruct(cro);
5310 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5311 if (cro.flags & RO_META)
5312 outs() << " RO_META";
5313 if (cro.flags & RO_ROOT)
5314 outs() << " RO_ROOT";
5315 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5316 outs() << " RO_HAS_CXX_STRUCTORS";
5317 outs() << "\n";
5318 outs() << " instanceStart " << cro.instanceStart << "\n";
5319 outs() << " instanceSize " << cro.instanceSize << "\n";
5320 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5321 << "\n";
5322 print_layout_map32(cro.ivarLayout, info);
5323
5324 outs() << " name " << format("0x%" PRIx32, cro.name);
5325 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5326 if (name != nullptr)
5327 outs() << format(" %.*s", left, name);
5328 outs() << "\n";
5329
5330 outs() << " baseMethods "
5331 << format("0x%" PRIx32, cro.baseMethods)
5332 << " (struct method_list_t *)\n";
5333 if (cro.baseMethods != 0)
5334 print_method_list32_t(cro.baseMethods, info, "");
5335
5336 outs() << " baseProtocols "
5337 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5338 if (cro.baseProtocols != 0)
5339 print_protocol_list32_t(cro.baseProtocols, info);
5340 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5341 << "\n";
5342 if (cro.ivars != 0)
5343 print_ivar_list32_t(cro.ivars, info);
5344 outs() << " weakIvarLayout "
5345 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5346 print_layout_map32(cro.weakIvarLayout, info);
5347 outs() << " baseProperties "
5348 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5349 if (cro.baseProperties != 0)
5350 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00005351 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005352 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005353}
5354
Kevin Enderby0fc11822015-04-01 20:57:01 +00005355static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5356 struct class64_t c;
5357 const char *r;
5358 uint32_t offset, left;
5359 SectionRef S;
5360 const char *name;
5361 uint64_t isa_n_value, n_value;
5362
5363 r = get_pointer_64(p, offset, left, S, info);
5364 if (r == nullptr || left < sizeof(struct class64_t))
5365 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005366 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005367 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5368 swapStruct(c);
5369
5370 outs() << " isa " << format("0x%" PRIx64, c.isa);
5371 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5372 isa_n_value, c.isa);
5373 if (name != nullptr)
5374 outs() << " " << name;
5375 outs() << "\n";
5376
5377 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5378 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5379 n_value, c.superclass);
5380 if (name != nullptr)
5381 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005382 else {
5383 name = get_dyld_bind_info_symbolname(S.getAddress() +
5384 offset + offsetof(struct class64_t, superclass), info);
5385 if (name != nullptr)
5386 outs() << " " << name;
5387 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005388 outs() << "\n";
5389
5390 outs() << " cache " << format("0x%" PRIx64, c.cache);
5391 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5392 n_value, c.cache);
5393 if (name != nullptr)
5394 outs() << " " << name;
5395 outs() << "\n";
5396
5397 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5398 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5399 n_value, c.vtable);
5400 if (name != nullptr)
5401 outs() << " " << name;
5402 outs() << "\n";
5403
5404 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5405 n_value, c.data);
5406 outs() << " data ";
5407 if (n_value != 0) {
5408 if (info->verbose && name != nullptr)
5409 outs() << name;
5410 else
5411 outs() << format("0x%" PRIx64, n_value);
5412 if (c.data != 0)
5413 outs() << " + " << format("0x%" PRIx64, c.data);
5414 } else
5415 outs() << format("0x%" PRIx64, c.data);
5416 outs() << " (struct class_ro_t *)";
5417
5418 // This is a Swift class if some of the low bits of the pointer are set.
5419 if ((c.data + n_value) & 0x7)
5420 outs() << " Swift class";
5421 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005422 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005423 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5424 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005425
Kevin Enderbyaac75382015-10-08 16:56:35 +00005426 if (!is_meta_class &&
5427 c.isa + isa_n_value != p &&
5428 c.isa + isa_n_value != 0 &&
5429 info->depth < 100) {
5430 info->depth++;
5431 outs() << "Meta Class\n";
5432 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005433 }
5434}
5435
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005436static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5437 struct class32_t c;
5438 const char *r;
5439 uint32_t offset, left;
5440 SectionRef S;
5441 const char *name;
5442
5443 r = get_pointer_32(p, offset, left, S, info);
5444 if (r == nullptr)
5445 return;
5446 memset(&c, '\0', sizeof(struct class32_t));
5447 if (left < sizeof(struct class32_t)) {
5448 memcpy(&c, r, left);
5449 outs() << " (class_t entends past the end of the section)\n";
5450 } else
5451 memcpy(&c, r, sizeof(struct class32_t));
5452 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5453 swapStruct(c);
5454
5455 outs() << " isa " << format("0x%" PRIx32, c.isa);
5456 name =
5457 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5458 if (name != nullptr)
5459 outs() << " " << name;
5460 outs() << "\n";
5461
5462 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5463 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5464 c.superclass);
5465 if (name != nullptr)
5466 outs() << " " << name;
5467 outs() << "\n";
5468
5469 outs() << " cache " << format("0x%" PRIx32, c.cache);
5470 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5471 c.cache);
5472 if (name != nullptr)
5473 outs() << " " << name;
5474 outs() << "\n";
5475
5476 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5477 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5478 c.vtable);
5479 if (name != nullptr)
5480 outs() << " " << name;
5481 outs() << "\n";
5482
5483 name =
5484 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5485 outs() << " data " << format("0x%" PRIx32, c.data)
5486 << " (struct class_ro_t *)";
5487
5488 // This is a Swift class if some of the low bits of the pointer are set.
5489 if (c.data & 0x3)
5490 outs() << " Swift class";
5491 outs() << "\n";
5492 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005493 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5494 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005495
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005496 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005497 outs() << "Meta Class\n";
5498 print_class32_t(c.isa, info);
5499 }
5500}
5501
Kevin Enderby846c0002015-04-16 17:19:59 +00005502static void print_objc_class_t(struct objc_class_t *objc_class,
5503 struct DisassembleInfo *info) {
5504 uint32_t offset, left, xleft;
5505 const char *name, *p, *ivar_list;
5506 SectionRef S;
5507 int32_t i;
5508 struct objc_ivar_list_t objc_ivar_list;
5509 struct objc_ivar_t ivar;
5510
5511 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5512 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5513 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5514 if (name != nullptr)
5515 outs() << format(" %.*s", left, name);
5516 else
5517 outs() << " (not in an __OBJC section)";
5518 }
5519 outs() << "\n";
5520
5521 outs() << "\t super_class "
5522 << format("0x%08" PRIx32, objc_class->super_class);
5523 if (info->verbose) {
5524 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5525 if (name != nullptr)
5526 outs() << format(" %.*s", left, name);
5527 else
5528 outs() << " (not in an __OBJC section)";
5529 }
5530 outs() << "\n";
5531
5532 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5533 if (info->verbose) {
5534 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5535 if (name != nullptr)
5536 outs() << format(" %.*s", left, name);
5537 else
5538 outs() << " (not in an __OBJC section)";
5539 }
5540 outs() << "\n";
5541
5542 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5543 << "\n";
5544
5545 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5546 if (info->verbose) {
5547 if (CLS_GETINFO(objc_class, CLS_CLASS))
5548 outs() << " CLS_CLASS";
5549 else if (CLS_GETINFO(objc_class, CLS_META))
5550 outs() << " CLS_META";
5551 }
5552 outs() << "\n";
5553
5554 outs() << "\t instance_size "
5555 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5556
5557 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5558 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5559 if (p != nullptr) {
5560 if (left > sizeof(struct objc_ivar_list_t)) {
5561 outs() << "\n";
5562 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5563 } else {
5564 outs() << " (entends past the end of the section)\n";
5565 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5566 memcpy(&objc_ivar_list, p, left);
5567 }
5568 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5569 swapStruct(objc_ivar_list);
5570 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5571 ivar_list = p + sizeof(struct objc_ivar_list_t);
5572 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5573 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5574 outs() << "\t\t remaining ivar's extend past the of the section\n";
5575 break;
5576 }
5577 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5578 sizeof(struct objc_ivar_t));
5579 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5580 swapStruct(ivar);
5581
5582 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5583 if (info->verbose) {
5584 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5585 if (name != nullptr)
5586 outs() << format(" %.*s", xleft, name);
5587 else
5588 outs() << " (not in an __OBJC section)";
5589 }
5590 outs() << "\n";
5591
5592 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5593 if (info->verbose) {
5594 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5595 if (name != nullptr)
5596 outs() << format(" %.*s", xleft, name);
5597 else
5598 outs() << " (not in an __OBJC section)";
5599 }
5600 outs() << "\n";
5601
5602 outs() << "\t\t ivar_offset "
5603 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5604 }
5605 } else {
5606 outs() << " (not in an __OBJC section)\n";
5607 }
5608
5609 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5610 if (print_method_list(objc_class->methodLists, info))
5611 outs() << " (not in an __OBJC section)\n";
5612
5613 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5614 << "\n";
5615
5616 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5617 if (print_protocol_list(objc_class->protocols, 16, info))
5618 outs() << " (not in an __OBJC section)\n";
5619}
5620
5621static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5622 struct DisassembleInfo *info) {
5623 uint32_t offset, left;
5624 const char *name;
5625 SectionRef S;
5626
5627 outs() << "\t category name "
5628 << format("0x%08" PRIx32, objc_category->category_name);
5629 if (info->verbose) {
5630 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5631 true);
5632 if (name != nullptr)
5633 outs() << format(" %.*s", left, name);
5634 else
5635 outs() << " (not in an __OBJC section)";
5636 }
5637 outs() << "\n";
5638
5639 outs() << "\t\t class name "
5640 << format("0x%08" PRIx32, objc_category->class_name);
5641 if (info->verbose) {
5642 name =
5643 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5644 if (name != nullptr)
5645 outs() << format(" %.*s", left, name);
5646 else
5647 outs() << " (not in an __OBJC section)";
5648 }
5649 outs() << "\n";
5650
5651 outs() << "\t instance methods "
5652 << format("0x%08" PRIx32, objc_category->instance_methods);
5653 if (print_method_list(objc_category->instance_methods, info))
5654 outs() << " (not in an __OBJC section)\n";
5655
5656 outs() << "\t class methods "
5657 << format("0x%08" PRIx32, objc_category->class_methods);
5658 if (print_method_list(objc_category->class_methods, info))
5659 outs() << " (not in an __OBJC section)\n";
5660}
5661
Kevin Enderby0fc11822015-04-01 20:57:01 +00005662static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5663 struct category64_t c;
5664 const char *r;
5665 uint32_t offset, xoffset, left;
5666 SectionRef S, xS;
5667 const char *name, *sym_name;
5668 uint64_t n_value;
5669
5670 r = get_pointer_64(p, offset, left, S, info);
5671 if (r == nullptr)
5672 return;
5673 memset(&c, '\0', sizeof(struct category64_t));
5674 if (left < sizeof(struct category64_t)) {
5675 memcpy(&c, r, left);
5676 outs() << " (category_t entends past the end of the section)\n";
5677 } else
5678 memcpy(&c, r, sizeof(struct category64_t));
5679 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5680 swapStruct(c);
5681
5682 outs() << " name ";
5683 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5684 info, n_value, c.name);
5685 if (n_value != 0) {
5686 if (info->verbose && sym_name != nullptr)
5687 outs() << sym_name;
5688 else
5689 outs() << format("0x%" PRIx64, n_value);
5690 if (c.name != 0)
5691 outs() << " + " << format("0x%" PRIx64, c.name);
5692 } else
5693 outs() << format("0x%" PRIx64, c.name);
5694 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5695 if (name != nullptr)
5696 outs() << format(" %.*s", left, name);
5697 outs() << "\n";
5698
5699 outs() << " cls ";
5700 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5701 n_value, c.cls);
5702 if (n_value != 0) {
5703 if (info->verbose && sym_name != nullptr)
5704 outs() << sym_name;
5705 else
5706 outs() << format("0x%" PRIx64, n_value);
5707 if (c.cls != 0)
5708 outs() << " + " << format("0x%" PRIx64, c.cls);
5709 } else
5710 outs() << format("0x%" PRIx64, c.cls);
5711 outs() << "\n";
5712 if (c.cls + n_value != 0)
5713 print_class64_t(c.cls + n_value, info);
5714
5715 outs() << " instanceMethods ";
5716 sym_name =
5717 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5718 info, n_value, c.instanceMethods);
5719 if (n_value != 0) {
5720 if (info->verbose && sym_name != nullptr)
5721 outs() << sym_name;
5722 else
5723 outs() << format("0x%" PRIx64, n_value);
5724 if (c.instanceMethods != 0)
5725 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5726 } else
5727 outs() << format("0x%" PRIx64, c.instanceMethods);
5728 outs() << "\n";
5729 if (c.instanceMethods + n_value != 0)
5730 print_method_list64_t(c.instanceMethods + n_value, info, "");
5731
5732 outs() << " classMethods ";
5733 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5734 S, info, n_value, c.classMethods);
5735 if (n_value != 0) {
5736 if (info->verbose && sym_name != nullptr)
5737 outs() << sym_name;
5738 else
5739 outs() << format("0x%" PRIx64, n_value);
5740 if (c.classMethods != 0)
5741 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5742 } else
5743 outs() << format("0x%" PRIx64, c.classMethods);
5744 outs() << "\n";
5745 if (c.classMethods + n_value != 0)
5746 print_method_list64_t(c.classMethods + n_value, info, "");
5747
5748 outs() << " protocols ";
5749 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5750 info, n_value, c.protocols);
5751 if (n_value != 0) {
5752 if (info->verbose && sym_name != nullptr)
5753 outs() << sym_name;
5754 else
5755 outs() << format("0x%" PRIx64, n_value);
5756 if (c.protocols != 0)
5757 outs() << " + " << format("0x%" PRIx64, c.protocols);
5758 } else
5759 outs() << format("0x%" PRIx64, c.protocols);
5760 outs() << "\n";
5761 if (c.protocols + n_value != 0)
5762 print_protocol_list64_t(c.protocols + n_value, info);
5763
5764 outs() << "instanceProperties ";
5765 sym_name =
5766 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5767 S, info, n_value, c.instanceProperties);
5768 if (n_value != 0) {
5769 if (info->verbose && sym_name != nullptr)
5770 outs() << sym_name;
5771 else
5772 outs() << format("0x%" PRIx64, n_value);
5773 if (c.instanceProperties != 0)
5774 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5775 } else
5776 outs() << format("0x%" PRIx64, c.instanceProperties);
5777 outs() << "\n";
5778 if (c.instanceProperties + n_value != 0)
5779 print_objc_property_list64(c.instanceProperties + n_value, info);
5780}
5781
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005782static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5783 struct category32_t c;
5784 const char *r;
5785 uint32_t offset, left;
5786 SectionRef S, xS;
5787 const char *name;
5788
5789 r = get_pointer_32(p, offset, left, S, info);
5790 if (r == nullptr)
5791 return;
5792 memset(&c, '\0', sizeof(struct category32_t));
5793 if (left < sizeof(struct category32_t)) {
5794 memcpy(&c, r, left);
5795 outs() << " (category_t entends past the end of the section)\n";
5796 } else
5797 memcpy(&c, r, sizeof(struct category32_t));
5798 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5799 swapStruct(c);
5800
5801 outs() << " name " << format("0x%" PRIx32, c.name);
5802 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5803 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005804 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005805 outs() << " " << name;
5806 outs() << "\n";
5807
5808 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5809 if (c.cls != 0)
5810 print_class32_t(c.cls, info);
5811 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5812 << "\n";
5813 if (c.instanceMethods != 0)
5814 print_method_list32_t(c.instanceMethods, info, "");
5815 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5816 << "\n";
5817 if (c.classMethods != 0)
5818 print_method_list32_t(c.classMethods, info, "");
5819 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5820 if (c.protocols != 0)
5821 print_protocol_list32_t(c.protocols, info);
5822 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5823 << "\n";
5824 if (c.instanceProperties != 0)
5825 print_objc_property_list32(c.instanceProperties, info);
5826}
5827
Kevin Enderby0fc11822015-04-01 20:57:01 +00005828static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5829 uint32_t i, left, offset, xoffset;
5830 uint64_t p, n_value;
5831 struct message_ref64 mr;
5832 const char *name, *sym_name;
5833 const char *r;
5834 SectionRef xS;
5835
5836 if (S == SectionRef())
5837 return;
5838
5839 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00005840 Expected<StringRef> SecNameOrErr = S.getName();
5841 if (SecNameOrErr)
5842 SectName = *SecNameOrErr;
5843 else
5844 consumeError(SecNameOrErr.takeError());
5845
Kevin Enderby0fc11822015-04-01 20:57:01 +00005846 DataRefImpl Ref = S.getRawDataRefImpl();
5847 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5848 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5849 offset = 0;
5850 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5851 p = S.getAddress() + i;
5852 r = get_pointer_64(p, offset, left, S, info);
5853 if (r == nullptr)
5854 return;
5855 memset(&mr, '\0', sizeof(struct message_ref64));
5856 if (left < sizeof(struct message_ref64)) {
5857 memcpy(&mr, r, left);
5858 outs() << " (message_ref entends past the end of the section)\n";
5859 } else
5860 memcpy(&mr, r, sizeof(struct message_ref64));
5861 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5862 swapStruct(mr);
5863
5864 outs() << " imp ";
5865 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5866 n_value, mr.imp);
5867 if (n_value != 0) {
5868 outs() << format("0x%" PRIx64, n_value) << " ";
5869 if (mr.imp != 0)
5870 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5871 } else
5872 outs() << format("0x%" PRIx64, mr.imp) << " ";
5873 if (name != nullptr)
5874 outs() << " " << name;
5875 outs() << "\n";
5876
5877 outs() << " sel ";
5878 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5879 info, n_value, mr.sel);
5880 if (n_value != 0) {
5881 if (info->verbose && sym_name != nullptr)
5882 outs() << sym_name;
5883 else
5884 outs() << format("0x%" PRIx64, n_value);
5885 if (mr.sel != 0)
5886 outs() << " + " << format("0x%" PRIx64, mr.sel);
5887 } else
5888 outs() << format("0x%" PRIx64, mr.sel);
5889 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5890 if (name != nullptr)
5891 outs() << format(" %.*s", left, name);
5892 outs() << "\n";
5893
5894 offset += sizeof(struct message_ref64);
5895 }
5896}
5897
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005898static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5899 uint32_t i, left, offset, xoffset, p;
5900 struct message_ref32 mr;
5901 const char *name, *r;
5902 SectionRef xS;
5903
5904 if (S == SectionRef())
5905 return;
5906
5907 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00005908 Expected<StringRef> SecNameOrErr = S.getName();
5909 if (SecNameOrErr)
5910 SectName = *SecNameOrErr;
5911 else
5912 consumeError(SecNameOrErr.takeError());
5913
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005914 DataRefImpl Ref = S.getRawDataRefImpl();
5915 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5916 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5917 offset = 0;
5918 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5919 p = S.getAddress() + i;
5920 r = get_pointer_32(p, offset, left, S, info);
5921 if (r == nullptr)
5922 return;
5923 memset(&mr, '\0', sizeof(struct message_ref32));
5924 if (left < sizeof(struct message_ref32)) {
5925 memcpy(&mr, r, left);
5926 outs() << " (message_ref entends past the end of the section)\n";
5927 } else
5928 memcpy(&mr, r, sizeof(struct message_ref32));
5929 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5930 swapStruct(mr);
5931
5932 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5933 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5934 mr.imp);
5935 if (name != nullptr)
5936 outs() << " " << name;
5937 outs() << "\n";
5938
5939 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5940 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5941 if (name != nullptr)
5942 outs() << " " << name;
5943 outs() << "\n";
5944
5945 offset += sizeof(struct message_ref32);
5946 }
5947}
5948
Kevin Enderby0fc11822015-04-01 20:57:01 +00005949static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5950 uint32_t left, offset, swift_version;
5951 uint64_t p;
5952 struct objc_image_info64 o;
5953 const char *r;
5954
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005955 if (S == SectionRef())
5956 return;
5957
Kevin Enderby0fc11822015-04-01 20:57:01 +00005958 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00005959 Expected<StringRef> SecNameOrErr = S.getName();
5960 if (SecNameOrErr)
5961 SectName = *SecNameOrErr;
5962 else
5963 consumeError(SecNameOrErr.takeError());
5964
Kevin Enderby0fc11822015-04-01 20:57:01 +00005965 DataRefImpl Ref = S.getRawDataRefImpl();
5966 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5967 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5968 p = S.getAddress();
5969 r = get_pointer_64(p, offset, left, S, info);
5970 if (r == nullptr)
5971 return;
5972 memset(&o, '\0', sizeof(struct objc_image_info64));
5973 if (left < sizeof(struct objc_image_info64)) {
5974 memcpy(&o, r, left);
5975 outs() << " (objc_image_info entends past the end of the section)\n";
5976 } else
5977 memcpy(&o, r, sizeof(struct objc_image_info64));
5978 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5979 swapStruct(o);
5980 outs() << " version " << o.version << "\n";
5981 outs() << " flags " << format("0x%" PRIx32, o.flags);
5982 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5983 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5984 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5985 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005986 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5987 outs() << " OBJC_IMAGE_IS_SIMULATED";
5988 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5989 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005990 swift_version = (o.flags >> 8) & 0xff;
5991 if (swift_version != 0) {
5992 if (swift_version == 1)
5993 outs() << " Swift 1.0";
5994 else if (swift_version == 2)
5995 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005996 else if(swift_version == 3)
5997 outs() << " Swift 2.0";
5998 else if(swift_version == 4)
5999 outs() << " Swift 3.0";
6000 else if(swift_version == 5)
6001 outs() << " Swift 4.0";
6002 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00006003 outs() << " Swift 4.1/Swift 4.2";
6004 else if(swift_version == 7)
6005 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00006006 else
6007 outs() << " unknown future Swift version (" << swift_version << ")";
6008 }
6009 outs() << "\n";
6010}
6011
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006012static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6013 uint32_t left, offset, swift_version, p;
6014 struct objc_image_info32 o;
6015 const char *r;
6016
Kevin Enderby19be2512016-04-21 19:49:29 +00006017 if (S == SectionRef())
6018 return;
6019
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006020 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00006021 Expected<StringRef> SecNameOrErr = S.getName();
6022 if (SecNameOrErr)
6023 SectName = *SecNameOrErr;
6024 else
6025 consumeError(SecNameOrErr.takeError());
6026
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006027 DataRefImpl Ref = S.getRawDataRefImpl();
6028 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6029 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6030 p = S.getAddress();
6031 r = get_pointer_32(p, offset, left, S, info);
6032 if (r == nullptr)
6033 return;
6034 memset(&o, '\0', sizeof(struct objc_image_info32));
6035 if (left < sizeof(struct objc_image_info32)) {
6036 memcpy(&o, r, left);
6037 outs() << " (objc_image_info entends past the end of the section)\n";
6038 } else
6039 memcpy(&o, r, sizeof(struct objc_image_info32));
6040 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6041 swapStruct(o);
6042 outs() << " version " << o.version << "\n";
6043 outs() << " flags " << format("0x%" PRIx32, o.flags);
6044 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6045 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6046 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6047 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6048 swift_version = (o.flags >> 8) & 0xff;
6049 if (swift_version != 0) {
6050 if (swift_version == 1)
6051 outs() << " Swift 1.0";
6052 else if (swift_version == 2)
6053 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00006054 else if(swift_version == 3)
6055 outs() << " Swift 2.0";
6056 else if(swift_version == 4)
6057 outs() << " Swift 3.0";
6058 else if(swift_version == 5)
6059 outs() << " Swift 4.0";
6060 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00006061 outs() << " Swift 4.1/Swift 4.2";
6062 else if(swift_version == 7)
6063 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006064 else
6065 outs() << " unknown future Swift version (" << swift_version << ")";
6066 }
6067 outs() << "\n";
6068}
6069
Kevin Enderby846c0002015-04-16 17:19:59 +00006070static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6071 uint32_t left, offset, p;
6072 struct imageInfo_t o;
6073 const char *r;
6074
6075 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00006076 Expected<StringRef> SecNameOrErr = S.getName();
6077 if (SecNameOrErr)
6078 SectName = *SecNameOrErr;
6079 else
6080 consumeError(SecNameOrErr.takeError());
6081
Kevin Enderby846c0002015-04-16 17:19:59 +00006082 DataRefImpl Ref = S.getRawDataRefImpl();
6083 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6084 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6085 p = S.getAddress();
6086 r = get_pointer_32(p, offset, left, S, info);
6087 if (r == nullptr)
6088 return;
6089 memset(&o, '\0', sizeof(struct imageInfo_t));
6090 if (left < sizeof(struct imageInfo_t)) {
6091 memcpy(&o, r, left);
6092 outs() << " (imageInfo entends past the end of the section)\n";
6093 } else
6094 memcpy(&o, r, sizeof(struct imageInfo_t));
6095 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6096 swapStruct(o);
6097 outs() << " version " << o.version << "\n";
6098 outs() << " flags " << format("0x%" PRIx32, o.flags);
6099 if (o.flags & 0x1)
6100 outs() << " F&C";
6101 if (o.flags & 0x2)
6102 outs() << " GC";
6103 if (o.flags & 0x4)
6104 outs() << " GC-only";
6105 else
6106 outs() << " RR";
6107 outs() << "\n";
6108}
6109
Kevin Enderby0fc11822015-04-01 20:57:01 +00006110static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6111 SymbolAddressMap AddrMap;
6112 if (verbose)
6113 CreateSymbolAddressMap(O, &AddrMap);
6114
6115 std::vector<SectionRef> Sections;
George Rimarbcc00e12019-08-14 11:10:11 +00006116 for (const SectionRef &Section : O->sections())
Kevin Enderby0fc11822015-04-01 20:57:01 +00006117 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006118
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006119 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006120
Davide Italiano62507042015-12-11 22:27:59 +00006121 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6122 if (CL == SectionRef())
6123 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006124 if (CL == SectionRef())
6125 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6126 if (CL == SectionRef())
6127 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00006128 info.S = CL;
6129 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006130
Davide Italiano62507042015-12-11 22:27:59 +00006131 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6132 if (CR == SectionRef())
6133 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006134 if (CR == SectionRef())
6135 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6136 if (CR == SectionRef())
6137 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006138 info.S = CR;
6139 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006140
Davide Italiano62507042015-12-11 22:27:59 +00006141 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6142 if (SR == SectionRef())
6143 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006144 if (SR == SectionRef())
6145 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6146 if (SR == SectionRef())
6147 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006148 info.S = SR;
6149 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006150
Davide Italiano62507042015-12-11 22:27:59 +00006151 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6152 if (CA == SectionRef())
6153 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006154 if (CA == SectionRef())
6155 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6156 if (CA == SectionRef())
6157 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00006158 info.S = CA;
6159 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006160
Davide Italiano62507042015-12-11 22:27:59 +00006161 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6162 if (PL == SectionRef())
6163 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006164 if (PL == SectionRef())
6165 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6166 if (PL == SectionRef())
6167 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00006168 info.S = PL;
6169 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006170
Davide Italiano62507042015-12-11 22:27:59 +00006171 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6172 if (MR == SectionRef())
6173 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006174 if (MR == SectionRef())
6175 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6176 if (MR == SectionRef())
6177 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006178 info.S = MR;
6179 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006180
Davide Italiano62507042015-12-11 22:27:59 +00006181 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6182 if (II == SectionRef())
6183 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00006184 if (II == SectionRef())
6185 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6186 if (II == SectionRef())
6187 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00006188 info.S = II;
6189 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006190}
6191
6192static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006193 SymbolAddressMap AddrMap;
6194 if (verbose)
6195 CreateSymbolAddressMap(O, &AddrMap);
6196
6197 std::vector<SectionRef> Sections;
George Rimarbcc00e12019-08-14 11:10:11 +00006198 for (const SectionRef &Section : O->sections())
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006199 Sections.push_back(Section);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006200
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006201 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006202
Kevin Enderby5879a482017-02-09 17:56:26 +00006203 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6204 if (CL == SectionRef())
6205 CL = get_section(O, "__DATA", "__objc_classlist");
6206 if (CL == SectionRef())
6207 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6208 if (CL == SectionRef())
6209 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6210 info.S = CL;
6211 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006212
Kevin Enderby5879a482017-02-09 17:56:26 +00006213 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6214 if (CR == SectionRef())
6215 CR = get_section(O, "__DATA", "__objc_classrefs");
6216 if (CR == SectionRef())
6217 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6218 if (CR == SectionRef())
6219 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6220 info.S = CR;
6221 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006222
Kevin Enderby5879a482017-02-09 17:56:26 +00006223 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6224 if (SR == SectionRef())
6225 SR = get_section(O, "__DATA", "__objc_superrefs");
6226 if (SR == SectionRef())
6227 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6228 if (SR == SectionRef())
6229 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6230 info.S = SR;
6231 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006232
Kevin Enderby5879a482017-02-09 17:56:26 +00006233 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6234 if (CA == SectionRef())
6235 CA = get_section(O, "__DATA", "__objc_catlist");
6236 if (CA == SectionRef())
6237 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6238 if (CA == SectionRef())
6239 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6240 info.S = CA;
6241 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006242
Kevin Enderby5879a482017-02-09 17:56:26 +00006243 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6244 if (PL == SectionRef())
6245 PL = get_section(O, "__DATA", "__objc_protolist");
6246 if (PL == SectionRef())
6247 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6248 if (PL == SectionRef())
6249 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6250 info.S = PL;
6251 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006252
Kevin Enderby5879a482017-02-09 17:56:26 +00006253 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6254 if (MR == SectionRef())
6255 MR = get_section(O, "__DATA", "__objc_msgrefs");
6256 if (MR == SectionRef())
6257 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6258 if (MR == SectionRef())
6259 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6260 info.S = MR;
6261 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006262
Kevin Enderby5879a482017-02-09 17:56:26 +00006263 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6264 if (II == SectionRef())
6265 II = get_section(O, "__DATA", "__objc_imageinfo");
6266 if (II == SectionRef())
6267 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6268 if (II == SectionRef())
6269 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6270 info.S = II;
6271 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006272}
6273
6274static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00006275 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6276 const char *r, *name, *defs;
6277 struct objc_module_t module;
6278 SectionRef S, xS;
6279 struct objc_symtab_t symtab;
6280 struct objc_class_t objc_class;
6281 struct objc_category_t objc_category;
6282
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006283 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00006284 S = get_section(O, "__OBJC", "__module_info");
6285 if (S == SectionRef())
6286 return false;
6287
6288 SymbolAddressMap AddrMap;
6289 if (verbose)
6290 CreateSymbolAddressMap(O, &AddrMap);
6291
6292 std::vector<SectionRef> Sections;
George Rimarbcc00e12019-08-14 11:10:11 +00006293 for (const SectionRef &Section : O->sections())
Kevin Enderby846c0002015-04-16 17:19:59 +00006294 Sections.push_back(Section);
Kevin Enderby846c0002015-04-16 17:19:59 +00006295
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006296 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00006297
6298 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6299 p = S.getAddress() + i;
6300 r = get_pointer_32(p, offset, left, S, &info, true);
6301 if (r == nullptr)
6302 return true;
6303 memset(&module, '\0', sizeof(struct objc_module_t));
6304 if (left < sizeof(struct objc_module_t)) {
6305 memcpy(&module, r, left);
6306 outs() << " (module extends past end of __module_info section)\n";
6307 } else
6308 memcpy(&module, r, sizeof(struct objc_module_t));
6309 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6310 swapStruct(module);
6311
6312 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6313 outs() << " version " << module.version << "\n";
6314 outs() << " size " << module.size << "\n";
6315 outs() << " name ";
6316 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6317 if (name != nullptr)
6318 outs() << format("%.*s", left, name);
6319 else
6320 outs() << format("0x%08" PRIx32, module.name)
6321 << "(not in an __OBJC section)";
6322 outs() << "\n";
6323
6324 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6325 if (module.symtab == 0 || r == nullptr) {
6326 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6327 << " (not in an __OBJC section)\n";
6328 continue;
6329 }
6330 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6331 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6332 defs_left = 0;
6333 defs = nullptr;
6334 if (left < sizeof(struct objc_symtab_t)) {
6335 memcpy(&symtab, r, left);
6336 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6337 } else {
6338 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6339 if (left > sizeof(struct objc_symtab_t)) {
6340 defs_left = left - sizeof(struct objc_symtab_t);
6341 defs = r + sizeof(struct objc_symtab_t);
6342 }
6343 }
6344 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6345 swapStruct(symtab);
6346
6347 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6348 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6349 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6350 if (r == nullptr)
6351 outs() << " (not in an __OBJC section)";
6352 outs() << "\n";
6353 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6354 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6355 if (symtab.cls_def_cnt > 0)
6356 outs() << "\tClass Definitions\n";
6357 for (j = 0; j < symtab.cls_def_cnt; j++) {
6358 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6359 outs() << "\t(remaining class defs entries entends past the end of the "
6360 << "section)\n";
6361 break;
6362 }
6363 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6364 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6365 sys::swapByteOrder(def);
6366
6367 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6368 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6369 if (r != nullptr) {
6370 if (left > sizeof(struct objc_class_t)) {
6371 outs() << "\n";
6372 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6373 } else {
6374 outs() << " (entends past the end of the section)\n";
6375 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6376 memcpy(&objc_class, r, left);
6377 }
6378 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6379 swapStruct(objc_class);
6380 print_objc_class_t(&objc_class, &info);
6381 } else {
6382 outs() << "(not in an __OBJC section)\n";
6383 }
6384
6385 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6386 outs() << "\tMeta Class";
6387 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6388 if (r != nullptr) {
6389 if (left > sizeof(struct objc_class_t)) {
6390 outs() << "\n";
6391 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6392 } else {
6393 outs() << " (entends past the end of the section)\n";
6394 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6395 memcpy(&objc_class, r, left);
6396 }
6397 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6398 swapStruct(objc_class);
6399 print_objc_class_t(&objc_class, &info);
6400 } else {
6401 outs() << "(not in an __OBJC section)\n";
6402 }
6403 }
6404 }
6405 if (symtab.cat_def_cnt > 0)
6406 outs() << "\tCategory Definitions\n";
6407 for (j = 0; j < symtab.cat_def_cnt; j++) {
6408 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6409 outs() << "\t(remaining category defs entries entends past the end of "
6410 << "the section)\n";
6411 break;
6412 }
6413 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6414 sizeof(uint32_t));
6415 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6416 sys::swapByteOrder(def);
6417
6418 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6419 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6420 << format("0x%08" PRIx32, def);
6421 if (r != nullptr) {
6422 if (left > sizeof(struct objc_category_t)) {
6423 outs() << "\n";
6424 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6425 } else {
6426 outs() << " (entends past the end of the section)\n";
6427 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6428 memcpy(&objc_category, r, left);
6429 }
6430 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6431 swapStruct(objc_category);
6432 print_objc_objc_category_t(&objc_category, &info);
6433 } else {
6434 outs() << "(not in an __OBJC section)\n";
6435 }
6436 }
6437 }
6438 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6439 if (II != SectionRef())
6440 print_image_info(II, &info);
6441
6442 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006443}
6444
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006445static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6446 uint32_t size, uint32_t addr) {
6447 SymbolAddressMap AddrMap;
6448 CreateSymbolAddressMap(O, &AddrMap);
6449
6450 std::vector<SectionRef> Sections;
George Rimarbcc00e12019-08-14 11:10:11 +00006451 for (const SectionRef &Section : O->sections())
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006452 Sections.push_back(Section);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006453
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006454 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006455
6456 const char *p;
6457 struct objc_protocol_t protocol;
6458 uint32_t left, paddr;
6459 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6460 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6461 left = size - (p - sect);
6462 if (left < sizeof(struct objc_protocol_t)) {
6463 outs() << "Protocol extends past end of __protocol section\n";
6464 memcpy(&protocol, p, left);
6465 } else
6466 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6467 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6468 swapStruct(protocol);
6469 paddr = addr + (p - sect);
6470 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6471 if (print_protocol(paddr, 0, &info))
6472 outs() << "(not in an __OBJC section)\n";
6473 }
6474}
6475
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006476#ifdef HAVE_LIBXAR
6477inline void swapStruct(struct xar_header &xar) {
6478 sys::swapByteOrder(xar.magic);
6479 sys::swapByteOrder(xar.size);
6480 sys::swapByteOrder(xar.version);
6481 sys::swapByteOrder(xar.toc_length_compressed);
6482 sys::swapByteOrder(xar.toc_length_uncompressed);
6483 sys::swapByteOrder(xar.cksum_alg);
6484}
6485
6486static void PrintModeVerbose(uint32_t mode) {
6487 switch(mode & S_IFMT){
6488 case S_IFDIR:
6489 outs() << "d";
6490 break;
6491 case S_IFCHR:
6492 outs() << "c";
6493 break;
6494 case S_IFBLK:
6495 outs() << "b";
6496 break;
6497 case S_IFREG:
6498 outs() << "-";
6499 break;
6500 case S_IFLNK:
6501 outs() << "l";
6502 break;
6503 case S_IFSOCK:
6504 outs() << "s";
6505 break;
6506 default:
6507 outs() << "?";
6508 break;
6509 }
6510
6511 /* owner permissions */
6512 if(mode & S_IREAD)
6513 outs() << "r";
6514 else
6515 outs() << "-";
6516 if(mode & S_IWRITE)
6517 outs() << "w";
6518 else
6519 outs() << "-";
6520 if(mode & S_ISUID)
6521 outs() << "s";
6522 else if(mode & S_IEXEC)
6523 outs() << "x";
6524 else
6525 outs() << "-";
6526
6527 /* group permissions */
6528 if(mode & (S_IREAD >> 3))
6529 outs() << "r";
6530 else
6531 outs() << "-";
6532 if(mode & (S_IWRITE >> 3))
6533 outs() << "w";
6534 else
6535 outs() << "-";
6536 if(mode & S_ISGID)
6537 outs() << "s";
6538 else if(mode & (S_IEXEC >> 3))
6539 outs() << "x";
6540 else
6541 outs() << "-";
6542
6543 /* other permissions */
6544 if(mode & (S_IREAD >> 6))
6545 outs() << "r";
6546 else
6547 outs() << "-";
6548 if(mode & (S_IWRITE >> 6))
6549 outs() << "w";
6550 else
6551 outs() << "-";
6552 if(mode & S_ISVTX)
6553 outs() << "t";
6554 else if(mode & (S_IEXEC >> 6))
6555 outs() << "x";
6556 else
6557 outs() << "-";
6558}
6559
6560static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006561 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006562 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6563 char *endp;
6564 uint32_t mode_value;
6565
Francis Ricci6f942972017-10-06 15:33:28 +00006566 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006567 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006568 WithColor::error(errs(), "llvm-objdump")
6569 << "can't obtain an xar iterator for xar archive " << XarFilename
6570 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006571 return;
6572 }
6573
6574 // Go through the xar's files.
6575 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006576 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006577 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006578 WithColor::error(errs(), "llvm-objdump")
6579 << "can't obtain an xar iterator for xar archive " << XarFilename
6580 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006581 return;
6582 }
6583 type = nullptr;
6584 mode = nullptr;
6585 user = nullptr;
6586 group = nullptr;
6587 size = nullptr;
6588 mtime = nullptr;
6589 name = nullptr;
6590 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006591 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006592 xar_prop_get(xf, key, &val);
6593#if 0 // Useful for debugging.
6594 outs() << "key: " << key << " value: " << val << "\n";
6595#endif
6596 if(strcmp(key, "type") == 0)
6597 type = val;
6598 if(strcmp(key, "mode") == 0)
6599 mode = val;
6600 if(strcmp(key, "user") == 0)
6601 user = val;
6602 if(strcmp(key, "group") == 0)
6603 group = val;
6604 if(strcmp(key, "data/size") == 0)
6605 size = val;
6606 if(strcmp(key, "mtime") == 0)
6607 mtime = val;
6608 if(strcmp(key, "name") == 0)
6609 name = val;
6610 }
6611 if(mode != nullptr){
6612 mode_value = strtoul(mode, &endp, 8);
6613 if(*endp != '\0')
6614 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6615 if(strcmp(type, "file") == 0)
6616 mode_value |= S_IFREG;
6617 PrintModeVerbose(mode_value);
6618 outs() << " ";
6619 }
6620 if(user != nullptr)
6621 outs() << format("%10s/", user);
6622 if(group != nullptr)
6623 outs() << format("%-10s ", group);
6624 if(size != nullptr)
6625 outs() << format("%7s ", size);
6626 if(mtime != nullptr){
6627 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6628 outs() << *m;
6629 if(*m == 'T')
6630 m++;
6631 outs() << " ";
6632 for( ; *m != 'Z' && *m != '\0'; m++)
6633 outs() << *m;
6634 outs() << " ";
6635 }
6636 if(name != nullptr)
6637 outs() << name;
6638 outs() << "\n";
6639 }
6640}
6641
6642static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6643 uint32_t size, bool verbose,
6644 bool PrintXarHeader, bool PrintXarFileHeaders,
6645 std::string XarMemberName) {
6646 if(size < sizeof(struct xar_header)) {
6647 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6648 "of struct xar_header)\n";
6649 return;
6650 }
6651 struct xar_header XarHeader;
6652 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6653 if (sys::IsLittleEndianHost)
6654 swapStruct(XarHeader);
6655 if (PrintXarHeader) {
6656 if (!XarMemberName.empty())
6657 outs() << "In xar member " << XarMemberName << ": ";
6658 else
6659 outs() << "For (__LLVM,__bundle) section: ";
6660 outs() << "xar header\n";
6661 if (XarHeader.magic == XAR_HEADER_MAGIC)
6662 outs() << " magic XAR_HEADER_MAGIC\n";
6663 else
6664 outs() << " magic "
6665 << format_hex(XarHeader.magic, 10, true)
6666 << " (not XAR_HEADER_MAGIC)\n";
6667 outs() << " size " << XarHeader.size << "\n";
6668 outs() << " version " << XarHeader.version << "\n";
6669 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6670 << "\n";
6671 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6672 << "\n";
6673 outs() << " cksum_alg ";
6674 switch (XarHeader.cksum_alg) {
6675 case XAR_CKSUM_NONE:
6676 outs() << "XAR_CKSUM_NONE\n";
6677 break;
6678 case XAR_CKSUM_SHA1:
6679 outs() << "XAR_CKSUM_SHA1\n";
6680 break;
6681 case XAR_CKSUM_MD5:
6682 outs() << "XAR_CKSUM_MD5\n";
6683 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006684#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006685 case XAR_CKSUM_SHA256:
6686 outs() << "XAR_CKSUM_SHA256\n";
6687 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006688#endif
6689#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006690 case XAR_CKSUM_SHA512:
6691 outs() << "XAR_CKSUM_SHA512\n";
6692 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006693#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006694 default:
6695 outs() << XarHeader.cksum_alg << "\n";
6696 }
6697 }
6698
6699 SmallString<128> XarFilename;
6700 int FD;
6701 std::error_code XarEC =
6702 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6703 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006704 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006705 return;
6706 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006707 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006708 raw_fd_ostream &XarOut = XarFile.os();
6709 StringRef XarContents(sect, size);
6710 XarOut << XarContents;
6711 XarOut.close();
6712 if (XarOut.has_error())
6713 return;
6714
Francis Ricci6f942972017-10-06 15:33:28 +00006715 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006716 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006717 WithColor::error(errs(), "llvm-objdump")
6718 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006719 return;
6720 }
6721
6722 SmallString<128> TocFilename;
6723 std::error_code TocEC =
6724 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6725 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006726 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006727 return;
6728 }
6729 xar_serialize(xar, TocFilename.c_str());
6730
6731 if (PrintXarFileHeaders) {
6732 if (!XarMemberName.empty())
6733 outs() << "In xar member " << XarMemberName << ": ";
6734 else
6735 outs() << "For (__LLVM,__bundle) section: ";
6736 outs() << "xar archive files:\n";
6737 PrintXarFilesSummary(XarFilename.c_str(), xar);
6738 }
6739
6740 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6741 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6742 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006743 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006744 return;
6745 }
6746 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6747
6748 if (!XarMemberName.empty())
6749 outs() << "In xar member " << XarMemberName << ": ";
6750 else
6751 outs() << "For (__LLVM,__bundle) section: ";
6752 outs() << "xar table of contents:\n";
6753 outs() << Buffer->getBuffer() << "\n";
6754
6755 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006756 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006757 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006758 WithColor::error(errs(), "llvm-objdump")
6759 << "can't obtain an xar iterator for xar archive "
6760 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006761 return;
6762 }
6763 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6764 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006765 const char *member_name, *member_type, *member_size_string;
6766 size_t member_size;
6767
Francis Ricci6f942972017-10-06 15:33:28 +00006768 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006769 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006770 WithColor::error(errs(), "llvm-objdump")
6771 << "can't obtain an xar iterator for xar archive "
6772 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006773 return;
6774 }
6775 member_name = NULL;
6776 member_type = NULL;
6777 member_size_string = NULL;
6778 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006779 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006780 xar_prop_get(xf, key, &val);
6781#if 0 // Useful for debugging.
6782 outs() << "key: " << key << " value: " << val << "\n";
6783#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006784 if (strcmp(key, "name") == 0)
6785 member_name = val;
6786 if (strcmp(key, "type") == 0)
6787 member_type = val;
6788 if (strcmp(key, "data/size") == 0)
6789 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006790 }
6791 /*
6792 * If we find a file with a name, date/size and type properties
6793 * and with the type being "file" see if that is a xar file.
6794 */
6795 if (member_name != NULL && member_type != NULL &&
6796 strcmp(member_type, "file") == 0 &&
6797 member_size_string != NULL){
6798 // Extract the file into a buffer.
6799 char *endptr;
6800 member_size = strtoul(member_size_string, &endptr, 10);
6801 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006802 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006803 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006804#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006805 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006806#endif
6807 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006808 std::string OldXarMemberName;
6809 // If XarMemberName is already set this is nested. So
6810 // save the old name and create the nested name.
6811 if (!XarMemberName.empty()) {
6812 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006813 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006814 (Twine("[") + XarMemberName + "]" + member_name).str();
6815 } else {
6816 OldXarMemberName = "";
6817 XarMemberName = member_name;
6818 }
6819 // See if this is could be a xar file (nested).
6820 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006821#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006822 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006823#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006824 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006825 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006826 swapStruct(XarHeader);
6827 if (XarHeader.magic == XAR_HEADER_MAGIC)
6828 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006829 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006830 XarMemberName);
6831 }
6832 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006833 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006834 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006835 }
6836 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006837 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006838}
6839#endif // defined(HAVE_LIBXAR)
6840
Kevin Enderby0fc11822015-04-01 20:57:01 +00006841static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6842 if (O->is64Bit())
6843 printObjc2_64bit_MetaData(O, verbose);
6844 else {
6845 MachO::mach_header H;
6846 H = O->getHeader();
6847 if (H.cputype == MachO::CPU_TYPE_ARM)
6848 printObjc2_32bit_MetaData(O, verbose);
6849 else {
6850 // This is the 32-bit non-arm cputype case. Which is normally
6851 // the first Objective-C ABI. But it may be the case of a
6852 // binary for the iOS simulator which is the second Objective-C
6853 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6854 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006855 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006856 printObjc2_32bit_MetaData(O, verbose);
6857 }
6858 }
6859}
6860
Kevin Enderbybf246f52014-09-24 23:08:22 +00006861// GuessLiteralPointer returns a string which for the item in the Mach-O file
6862// for the address passed in as ReferenceValue for printing as a comment with
6863// the instruction and also returns the corresponding type of that item
6864// indirectly through ReferenceType.
6865//
6866// If ReferenceValue is an address of literal cstring then a pointer to the
6867// cstring is returned and ReferenceType is set to
6868// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6869//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006870// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6871// Class ref that name is returned and the ReferenceType is set accordingly.
6872//
6873// Lastly, literals which are Symbol address in a literal pool are looked for
6874// and if found the symbol name is returned and ReferenceType is set to
6875// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6876//
6877// If there is no item in the Mach-O file for the address passed in as
6878// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006879static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6880 uint64_t ReferencePC,
6881 uint64_t *ReferenceType,
6882 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006883 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006884 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6885 uint64_t sect_addr = info->S.getAddress();
6886 uint64_t sect_offset = ReferencePC - sect_addr;
6887 bool reloc_found = false;
6888 DataRefImpl Rel;
6889 MachO::any_relocation_info RE;
6890 bool isExtern = false;
6891 SymbolRef Symbol;
6892 for (const RelocationRef &Reloc : info->S.relocations()) {
6893 uint64_t RelocOffset = Reloc.getOffset();
6894 if (RelocOffset == sect_offset) {
6895 Rel = Reloc.getRawDataRefImpl();
6896 RE = info->O->getRelocation(Rel);
6897 if (info->O->isRelocationScattered(RE))
6898 continue;
6899 isExtern = info->O->getPlainRelocationExternal(RE);
6900 if (isExtern) {
6901 symbol_iterator RelocSym = Reloc.getSymbol();
6902 Symbol = *RelocSym;
6903 }
6904 reloc_found = true;
6905 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006906 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006907 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006908 // If there is an external relocation entry for a symbol in a section
6909 // then used that symbol's value for the value of the reference.
6910 if (reloc_found && isExtern) {
6911 if (info->O->getAnyRelocationPCRel(RE)) {
6912 unsigned Type = info->O->getAnyRelocationType(RE);
6913 if (Type == MachO::X86_64_RELOC_SIGNED) {
6914 ReferenceValue = Symbol.getValue();
6915 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006916 }
6917 }
6918 }
6919
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006920 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6921 // Message refs and Class refs.
6922 bool classref, selref, msgref, cfstring;
6923 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6924 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006925 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006926 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6927 // And the pointer_value in that section is typically zero as it will be
6928 // set by dyld as part of the "bind information".
6929 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6930 if (name != nullptr) {
6931 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006932 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006933 if (class_name != nullptr && class_name[1] == '_' &&
6934 class_name[2] != '\0') {
6935 info->class_name = class_name + 2;
6936 return name;
6937 }
6938 }
6939 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006940
David Blaikie33dd45d02015-03-23 18:39:02 +00006941 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006942 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6943 const char *name =
6944 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6945 if (name != nullptr)
6946 info->class_name = name;
6947 else
6948 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006949 return name;
6950 }
6951
David Blaikie33dd45d02015-03-23 18:39:02 +00006952 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006953 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6954 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6955 return name;
6956 }
6957
David Blaikie33dd45d02015-03-23 18:39:02 +00006958 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006959 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6960
6961 if (pointer_value != 0)
6962 ReferenceValue = pointer_value;
6963
6964 const char *name = GuessCstringPointer(ReferenceValue, info);
6965 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006966 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006967 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6968 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006969 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006970 info->class_name = nullptr;
6971 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6972 info->selector_name = name;
6973 } else
6974 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6975 return name;
6976 }
6977
6978 // Lastly look for an indirect symbol with this ReferenceValue which is in
6979 // a literal pool. If found return that symbol name.
6980 name = GuessIndirectSymbol(ReferenceValue, info);
6981 if (name) {
6982 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6983 return name;
6984 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006985
6986 return nullptr;
6987}
6988
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006989// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006990// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006991// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6992// is created and returns the symbol name that matches the ReferenceValue or
6993// nullptr if none. The ReferenceType is passed in for the IN type of
6994// reference the instruction is making from the values in defined in the header
6995// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6996// Out type and the ReferenceName will also be set which is added as a comment
6997// to the disassembled instruction.
6998//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006999// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007000// returned through ReferenceName and ReferenceType is set to
7001// LLVMDisassembler_ReferenceType_DeMangled_Name .
7002//
7003// When this is called to get a symbol name for a branch target then the
7004// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7005// SymbolValue will be looked for in the indirect symbol table to determine if
7006// it is an address for a symbol stub. If so then the symbol name for that
7007// stub is returned indirectly through ReferenceName and then ReferenceType is
7008// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7009//
Kevin Enderbybf246f52014-09-24 23:08:22 +00007010// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007011// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7012// SymbolValue is checked to be an address of literal pointer, symbol pointer,
7013// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007014// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00007015static const char *SymbolizerSymbolLookUp(void *DisInfo,
7016 uint64_t ReferenceValue,
7017 uint64_t *ReferenceType,
7018 uint64_t ReferencePC,
7019 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007020 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007021 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00007022 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007023 *ReferenceName = nullptr;
7024 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007025 return nullptr;
7026 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007027
Kevin Enderbyf6d25852015-01-31 00:37:11 +00007028 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007029
Kevin Enderby85974882014-09-26 22:20:44 +00007030 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7031 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007032 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007033 method_reference(info, ReferenceType, ReferenceName);
7034 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7035 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00007036 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00007037 if (info->demangled_name != nullptr)
7038 free(info->demangled_name);
7039 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007040 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00007041 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007042 if (info->demangled_name != nullptr) {
7043 *ReferenceName = info->demangled_name;
7044 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7045 } else
7046 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7047 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007048 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7049 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7050 *ReferenceName =
7051 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00007052 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007053 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00007054 else
7055 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007056 // If this is arm64 and the reference is an adrp instruction save the
7057 // instruction, passed in ReferenceValue and the address of the instruction
7058 // for use later if we see and add immediate instruction.
7059 } else if (info->O->getArch() == Triple::aarch64 &&
7060 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7061 info->adrp_inst = ReferenceValue;
7062 info->adrp_addr = ReferencePC;
7063 SymbolName = nullptr;
7064 *ReferenceName = nullptr;
7065 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7066 // If this is arm64 and reference is an add immediate instruction and we
7067 // have
7068 // seen an adrp instruction just before it and the adrp's Xd register
7069 // matches
7070 // this add's Xn register reconstruct the value being referenced and look to
7071 // see if it is a literal pointer. Note the add immediate instruction is
7072 // passed in ReferenceValue.
7073 } else if (info->O->getArch() == Triple::aarch64 &&
7074 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7075 ReferencePC - 4 == info->adrp_addr &&
7076 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7077 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7078 uint32_t addxri_inst;
7079 uint64_t adrp_imm, addxri_imm;
7080
7081 adrp_imm =
7082 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7083 if (info->adrp_inst & 0x0200000)
7084 adrp_imm |= 0xfffffffffc000000LL;
7085
7086 addxri_inst = ReferenceValue;
7087 addxri_imm = (addxri_inst >> 10) & 0xfff;
7088 if (((addxri_inst >> 22) & 0x3) == 1)
7089 addxri_imm <<= 12;
7090
7091 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7092 (adrp_imm << 12) + addxri_imm;
7093
7094 *ReferenceName =
7095 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7096 if (*ReferenceName == nullptr)
7097 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7098 // If this is arm64 and the reference is a load register instruction and we
7099 // have seen an adrp instruction just before it and the adrp's Xd register
7100 // matches this add's Xn register reconstruct the value being referenced and
7101 // look to see if it is a literal pointer. Note the load register
7102 // instruction is passed in ReferenceValue.
7103 } else if (info->O->getArch() == Triple::aarch64 &&
7104 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7105 ReferencePC - 4 == info->adrp_addr &&
7106 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7107 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7108 uint32_t ldrxui_inst;
7109 uint64_t adrp_imm, ldrxui_imm;
7110
7111 adrp_imm =
7112 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7113 if (info->adrp_inst & 0x0200000)
7114 adrp_imm |= 0xfffffffffc000000LL;
7115
7116 ldrxui_inst = ReferenceValue;
7117 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7118
7119 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7120 (adrp_imm << 12) + (ldrxui_imm << 3);
7121
7122 *ReferenceName =
7123 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7124 if (*ReferenceName == nullptr)
7125 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7126 }
7127 // If this arm64 and is an load register (PC-relative) instruction the
7128 // ReferenceValue is the PC plus the immediate value.
7129 else if (info->O->getArch() == Triple::aarch64 &&
7130 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7131 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7132 *ReferenceName =
7133 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7134 if (*ReferenceName == nullptr)
7135 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00007136 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00007137 if (info->demangled_name != nullptr)
7138 free(info->demangled_name);
7139 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007140 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00007141 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007142 if (info->demangled_name != nullptr) {
7143 *ReferenceName = info->demangled_name;
7144 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7145 }
7146 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007147 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007148 *ReferenceName = nullptr;
7149 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7150 }
7151
7152 return SymbolName;
7153}
7154
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007155/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007156/// Each comment in the CommentStream must end with a newline.
7157static void emitComments(raw_svector_ostream &CommentStream,
7158 SmallString<128> &CommentsToEmit,
7159 formatted_raw_ostream &FormattedOS,
7160 const MCAsmInfo &MAI) {
7161 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007162 StringRef Comments = CommentsToEmit.str();
7163 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00007164 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00007165 unsigned CommentColumn = MAI.getCommentColumn();
7166 bool IsFirst = true;
7167 while (!Comments.empty()) {
7168 if (!IsFirst)
7169 FormattedOS << '\n';
7170 // Emit a line of comments.
7171 FormattedOS.PadToColumn(CommentColumn);
7172 size_t Position = Comments.find('\n');
7173 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7174 // Move after the newline character.
7175 Comments = Comments.substr(Position + 1);
7176 IsFirst = false;
7177 }
7178 FormattedOS.flush();
7179
7180 // Tell the comment stream that the vector changed underneath it.
7181 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007182}
7183
Kevin Enderby95df54c2015-02-04 01:01:38 +00007184static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7185 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007186 const char *McpuDefault = nullptr;
7187 const Target *ThumbTarget = nullptr;
7188 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007189 if (!TheTarget) {
7190 // GetTarget prints out stuff.
7191 return;
7192 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00007193 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007194 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00007195 MachOMCPU = McpuDefault;
7196 else
7197 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007198
Ahmed Charles56440fd2014-03-06 05:51:42 +00007199 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007200 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007201 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007202 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007203
Kevin Enderbyc9595622014-08-06 23:24:41 +00007204 // Package up features to be passed to target/subtarget
7205 std::string FeaturesStr;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007206 if (!MAttrs.empty()) {
Kevin Enderbyc9595622014-08-06 23:24:41 +00007207 SubtargetFeatures Features;
7208 for (unsigned i = 0; i != MAttrs.size(); ++i)
7209 Features.AddFeature(MAttrs[i]);
7210 FeaturesStr = Features.getString();
7211 }
7212
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007213 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00007214 std::unique_ptr<const MCRegisterInfo> MRI(
7215 TheTarget->createMCRegInfo(TripleName));
7216 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00007217 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00007218 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007219 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00007220 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007221 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007222 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007223 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007224 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007225 std::unique_ptr<MCRelocationInfo> RelInfo(
7226 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7227 if (RelInfo) {
7228 Symbolizer.reset(TheTarget->createMCSymbolizer(
7229 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007230 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007231 DisAsm->setSymbolizer(std::move(Symbolizer));
7232 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007233 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00007234 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007235 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007236 // Set the display preference for hex vs. decimal immediates.
7237 IP->setPrintImmHex(PrintImmHex);
7238 // Comment stream and backing vector.
7239 SmallString<128> CommentsToEmit;
7240 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007241 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7242 // if it is done then arm64 comments for string literals don't get printed
7243 // and some constant get printed instead and not setting it causes intel
7244 // (32-bit and 64-bit) comments printed with different spacing before the
7245 // comment causing different diffs with the 'C' disassembler library API.
7246 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007247
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007248 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007249 WithColor::error(errs(), "llvm-objdump")
7250 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007251 return;
7252 }
7253
Tim Northover09ca33e2016-04-22 23:23:31 +00007254 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007255 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7256 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7257 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007258 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007259 std::unique_ptr<MCInstPrinter> ThumbIP;
7260 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007261 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007262 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007263 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007264 if (ThumbTarget) {
7265 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7266 ThumbAsmInfo.reset(
7267 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7268 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007269 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7270 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007271 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7272 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007273 MCContext *PtrThumbCtx = ThumbCtx.get();
7274 ThumbRelInfo.reset(
7275 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7276 if (ThumbRelInfo) {
7277 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7278 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007279 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007280 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7281 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007282 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7283 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007284 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7285 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007286 // Set the display preference for hex vs. decimal immediates.
7287 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007288 }
7289
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007290 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007291 WithColor::error(errs(), "llvm-objdump")
7292 << "couldn't initialize disassembler for target " << ThumbTripleName
7293 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007294 return;
7295 }
7296
Charles Davis8bdfafd2013-09-01 04:28:48 +00007297 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007298
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007299 // FIXME: Using the -cfg command line option, this code used to be able to
7300 // annotate relocations with the referenced symbol's name, and if this was
7301 // inside a __[cf]string section, the data it points to. This is now replaced
7302 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00007303 std::vector<SectionRef> Sections;
7304 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007305 SmallVector<uint64_t, 8> FoundFns;
Kuba Mraceka7c48b72019-08-01 15:51:14 +00007306 uint64_t BaseSegmentAddress = 0;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007307
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00007308 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00007309 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007310
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007311 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00007312 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007313
Kevin Enderby273ae012013-06-06 17:20:50 +00007314 // Build a data in code table that is sorted on by the address of each entry.
7315 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00007316 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00007317 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00007318 else
7319 BaseAddress = BaseSegmentAddress;
7320 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00007321 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00007322 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007323 uint32_t Offset;
7324 DI->getOffset(Offset);
7325 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7326 }
7327 array_pod_sort(Dices.begin(), Dices.end());
7328
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007329#ifndef NDEBUG
7330 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7331#else
7332 raw_ostream &DebugOut = nulls();
7333#endif
7334
Michael Trent5d5f6292019-05-30 18:17:10 +00007335 // Try to find debug info and set up the DIContext for it.
Michael Trentc58130b2019-05-30 20:09:09 +00007336 std::unique_ptr<DIContext> diContext;
7337 std::unique_ptr<Binary> DSYMBinary;
7338 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00007339 if (UseDbg) {
Michael Trentc58130b2019-05-30 20:09:09 +00007340 ObjectFile *DbgObj = MachOOF;
7341
Benjamin Kramer699128e2011-09-21 01:13:19 +00007342 // A separate DSym file path was specified, parse it as a macho file,
7343 // get the sections and supply it to the section name parsing machinery.
7344 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00007345 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00007346 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00007347 if (std::error_code EC = BufOrErr.getError()) {
George Rimarf0f38d92019-08-21 11:07:31 +00007348 reportError(errorCodeToError(EC), DSYMFile);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007349 return;
7350 }
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007351
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007352 // We need to keep the file alive, because we're replacing DbgObj with it.
7353 DSYMBuf = std::move(BufOrErr.get());
Michael Trentc58130b2019-05-30 20:09:09 +00007354
7355 Expected<std::unique_ptr<Binary>> BinaryOrErr =
7356 createBinary(DSYMBuf.get()->getMemBufferRef());
7357 if (!BinaryOrErr) {
George Rimarf0f38d92019-08-21 11:07:31 +00007358 reportError(BinaryOrErr.takeError(), DSYMFile);
Michael Trentc58130b2019-05-30 20:09:09 +00007359 return;
7360 }
7361
7362 // We need to keep the Binary elive with the buffer
7363 DSYMBinary = std::move(BinaryOrErr.get());
7364
7365 if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7366 // this is a Mach-O object file, use it
7367 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7368 DbgObj = MachDSYM;
7369 }
7370 else {
7371 WithColor::error(errs(), "llvm-objdump")
7372 << DSYMFile << " is not a Mach-O file type.\n";
7373 return;
7374 }
7375 }
7376 else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7377 // this is a Universal Binary, find a Mach-O for this architecture
7378 uint32_t CPUType, CPUSubType;
7379 const char *ArchFlag;
7380 if (MachOOF->is64Bit()) {
7381 const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7382 CPUType = H_64.cputype;
7383 CPUSubType = H_64.cpusubtype;
7384 } else {
7385 const MachO::mach_header H = MachOOF->getHeader();
7386 CPUType = H.cputype;
7387 CPUSubType = H.cpusubtype;
7388 }
7389 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7390 &ArchFlag);
7391 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7392 UB->getObjectForArch(ArchFlag);
7393 if (!MachDSYM) {
George Rimarf0f38d92019-08-21 11:07:31 +00007394 reportError(MachDSYM.takeError(), DSYMFile);
Michael Trentc58130b2019-05-30 20:09:09 +00007395 return;
7396 }
7397
7398 // We need to keep the Binary elive with the buffer
7399 DbgObj = &*MachDSYM.get();
7400 DSYMBinary = std::move(*MachDSYM);
7401 }
7402 else {
7403 WithColor::error(errs(), "llvm-objdump")
7404 << DSYMFile << " is not a Mach-O or Universal file type.\n";
7405 return;
7406 }
Benjamin Kramer699128e2011-09-21 01:13:19 +00007407 }
7408
Eric Christopher7370b552012-11-12 21:40:38 +00007409 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00007410 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007411 }
7412
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007413 if (FilterSections.empty())
Kevin Enderby95df54c2015-02-04 01:01:38 +00007414 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007415
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007416 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
George Rimarbcc00e12019-08-14 11:10:11 +00007417 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7418 if (!SecNameOrErr) {
7419 consumeError(SecNameOrErr.takeError());
7420 continue;
7421 }
7422 if (*SecNameOrErr != DisSectName)
Kevin Enderby95df54c2015-02-04 01:01:38 +00007423 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007424
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007425 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007426
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007427 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007428 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007429 continue;
7430
Fangrui Songe1833402019-05-16 13:24:04 +00007431 StringRef BytesStr =
7432 unwrapOrError(Sections[SectIdx].getContents(), Filename);
Fangrui Song6a0746a2019-04-07 03:58:42 +00007433 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
Rafael Espindola80291272014-10-08 15:28:58 +00007434 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007435
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007436 bool symbolTableWorked = false;
7437
Kevin Enderbybf246f52014-09-24 23:08:22 +00007438 // Create a map of symbol addresses to symbol names for use by
7439 // the SymbolizerSymbolLookUp() routine.
7440 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007441 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007442 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007443 SymbolRef::Type ST =
7444 unwrapOrError(Symbol.getType(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007445 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7446 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007447 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00007448 StringRef SymName =
7449 unwrapOrError(Symbol.getName(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007450 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007451 if (!DisSymName.empty() && DisSymName == SymName)
7452 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007453 }
7454 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007455 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007456 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7457 return;
7458 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007459 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007460 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007461 SymbolizerInfo.O = MachOOF;
7462 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007463 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007464 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007465 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007466 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007467 ThumbSymbolizerInfo.O = MachOOF;
7468 ThumbSymbolizerInfo.S = Sections[SectIdx];
7469 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7470 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007471
Kevin Enderby4b627be2016-04-28 20:14:13 +00007472 unsigned int Arch = MachOOF->getArch();
7473
Tim Northoverf203ab52016-07-14 22:13:32 +00007474 // Skip all symbols if this is a stubs file.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007475 if (Bytes.empty())
Tim Northoverf203ab52016-07-14 22:13:32 +00007476 return;
7477
Kevin Enderbyc138da32017-02-06 18:43:18 +00007478 // If the section has symbols but no symbol at the start of the section
7479 // these are used to make sure the bytes before the first symbol are
7480 // disassembled.
7481 bool FirstSymbol = true;
7482 bool FirstSymbolAtSectionStart = true;
7483
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007484 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007485 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007486 StringRef SymName =
7487 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7488 SymbolRef::Type ST =
7489 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
Kuba Breckade833222015-11-12 09:40:29 +00007490 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007491 continue;
7492
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007493 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007494 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007495 if (!containsSym) {
7496 if (!DisSymName.empty() && DisSymName == SymName) {
7497 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7498 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007499 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007500 continue;
7501 }
7502 // The __mh_execute_header is special and we need to deal with that fact
7503 // this symbol is before the start of the (__TEXT,__text) section and at the
7504 // address of the start of the __TEXT segment. This is because this symbol
7505 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7506 // start of the section in a standard MH_EXECUTE filetype.
7507 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7508 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7509 return;
7510 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007511 // When this code is trying to disassemble a symbol at a time and in the
7512 // case there is only the __mh_execute_header symbol left as in a stripped
7513 // executable, we need to deal with this by ignoring this symbol so the
7514 // whole section is disassembled and this symbol is then not displayed.
7515 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7516 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7517 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007518 continue;
7519
Kevin Enderby6a221752015-03-17 17:10:57 +00007520 // If we are only disassembling one symbol see if this is that symbol.
7521 if (!DisSymName.empty() && DisSymName != SymName)
7522 continue;
7523
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007524 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007525 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007526 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007527 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007528 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007529
Tim Northoverf203ab52016-07-14 22:13:32 +00007530 if (Start > SectSize) {
7531 outs() << "section data ends, " << SymName
7532 << " lies outside valid range\n";
7533 return;
7534 }
7535
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007536 // Stop disassembling either at the beginning of the next symbol or at
7537 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007538 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007539 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007540 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007541 while (Symbols.size() > NextSymIdx) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007542 SymbolRef::Type NextSymType = unwrapOrError(
7543 Symbols[NextSymIdx].getType(), MachOOF->getFileName());
Owen Andersond9243c42011-10-17 21:37:35 +00007544 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007545 containsNextSym =
7546 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007547 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007548 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007549 break;
7550 }
7551 ++NextSymIdx;
7552 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007553
Tim Northoverf203ab52016-07-14 22:13:32 +00007554 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007555 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007556
7557 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007558
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007559 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007560 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7561
7562 // We only need the dedicated Thumb target if there's a real choice
7563 // (i.e. we're not targeting M-class) and the function is Thumb.
7564 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007565
Kevin Enderbyc138da32017-02-06 18:43:18 +00007566 // If we are not specifying a symbol to start disassembly with and this
7567 // is the first symbol in the section but not at the start of the section
7568 // then move the disassembly index to the start of the section and
7569 // don't print the symbol name just yet. This is so the bytes before the
7570 // first symbol are disassembled.
7571 uint64_t SymbolStart = Start;
7572 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7573 FirstSymbolAtSectionStart = false;
7574 Start = 0;
7575 }
7576 else
7577 outs() << SymName << ":\n";
7578
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007579 DILineInfo lastLine;
7580 for (uint64_t Index = Start; Index < End; Index += Size) {
7581 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007582
Kevin Enderbyc138da32017-02-06 18:43:18 +00007583 // If this is the first symbol in the section and it was not at the
7584 // start of the section, see if we are at its Index now and if so print
7585 // the symbol name.
7586 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7587 outs() << SymName << ":\n";
7588
Kevin Enderbybf246f52014-09-24 23:08:22 +00007589 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007590 if (!NoLeadingAddr) {
7591 if (FullLeadingAddr) {
7592 if (MachOOF->is64Bit())
7593 outs() << format("%016" PRIx64, PC);
7594 else
7595 outs() << format("%08" PRIx64, PC);
7596 } else {
7597 outs() << format("%8" PRIx64 ":", PC);
7598 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007599 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007600 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007601 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007602
Kuba Mraceka7c48b72019-08-01 15:51:14 +00007603 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
Kevin Enderby273ae012013-06-06 17:20:50 +00007604 continue;
Kevin Enderby273ae012013-06-06 17:20:50 +00007605
Kevin Enderbybf246f52014-09-24 23:08:22 +00007606 SmallVector<char, 64> AnnotationsBytes;
7607 raw_svector_ostream Annotations(AnnotationsBytes);
7608
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007609 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007610 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007611 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007612 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007613 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007614 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007615 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007616 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007617 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007618 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007619 }
7620 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007621 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007622 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007623 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007624 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007625 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007626 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007627
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007628 // Print debug info.
7629 if (diContext) {
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00007630 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007631 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007632 if (dli != lastLine && dli.Line != 0)
7633 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7634 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007635 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007636 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007637 outs() << "\n";
7638 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007639 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007640 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007641 outs() << format("\t.byte 0x%02x #bad opcode\n",
7642 *(Bytes.data() + Index) & 0xff);
7643 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007644 } else if (Arch == Triple::aarch64 ||
7645 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007646 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7647 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7648 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7649 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7650 outs() << format("\t.long\t0x%08x\n", opcode);
7651 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007652 } else if (Arch == Triple::arm) {
7653 assert(IsThumb && "ARM mode should have been dealt with above");
7654 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7655 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7656 outs() << format("\t.short\t0x%04x\n", opcode);
7657 Size = 2;
7658 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007659 WithColor::warning(errs(), "llvm-objdump")
7660 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007661 if (Size == 0)
7662 Size = 1; // skip illegible bytes
7663 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007664 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007665 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007666 // Now that we are done disassembled the first symbol set the bool that
7667 // were doing this to false.
7668 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007669 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007670 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007671 // Reading the symbol table didn't work, disassemble the whole section.
7672 uint64_t SectAddress = Sections[SectIdx].getAddress();
7673 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007674 uint64_t InstSize;
7675 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007676 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007677
Kevin Enderbybf246f52014-09-24 23:08:22 +00007678 uint64_t PC = SectAddress + Index;
Kuba Mraceka7c48b72019-08-01 15:51:14 +00007679
7680 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7681 continue;
7682
Kevin Enderby02d3a372017-01-31 18:09:10 +00007683 SmallVector<char, 64> AnnotationsBytes;
7684 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007685 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007686 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007687 if (!NoLeadingAddr) {
7688 if (FullLeadingAddr) {
7689 if (MachOOF->is64Bit())
7690 outs() << format("%016" PRIx64, PC);
7691 else
7692 outs() << format("%08" PRIx64, PC);
7693 } else {
7694 outs() << format("%8" PRIx64 ":", PC);
7695 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007696 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007697 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007698 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007699 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007700 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007701 StringRef AnnotationsStr = Annotations.str();
7702 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007703 outs() << "\n";
7704 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007705 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007706 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007707 outs() << format("\t.byte 0x%02x #bad opcode\n",
7708 *(Bytes.data() + Index) & 0xff);
7709 InstSize = 1; // skip exactly one illegible byte and move on.
7710 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007711 WithColor::warning(errs(), "llvm-objdump")
7712 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007713 if (InstSize == 0)
7714 InstSize = 1; // skip illegible bytes
7715 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007716 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007717 }
7718 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007719 // The TripleName's need to be reset if we are called again for a different
7720 // archtecture.
7721 TripleName = "";
7722 ThumbTripleName = "";
7723
Kevin Enderby04bf6932014-10-28 23:39:46 +00007724 if (SymbolizerInfo.demangled_name != nullptr)
7725 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007726 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7727 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007728 }
7729}
Tim Northover4bd286a2014-08-01 13:07:19 +00007730
Tim Northover39c70bb2014-08-12 11:52:59 +00007731//===----------------------------------------------------------------------===//
7732// __compact_unwind section dumping
7733//===----------------------------------------------------------------------===//
7734
Tim Northover4bd286a2014-08-01 13:07:19 +00007735namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007736
Tim Northover3a4e1c72018-01-23 13:51:57 +00007737template <typename T>
7738static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007739 using llvm::support::little;
7740 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007741
Tim Northover3a4e1c72018-01-23 13:51:57 +00007742 if (Offset + sizeof(T) > Contents.size()) {
7743 outs() << "warning: attempt to read past end of buffer\n";
7744 return T();
7745 }
7746
7747 uint64_t Val =
7748 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7749 return Val;
7750}
7751
7752template <typename T>
7753static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7754 T Val = read<T>(Contents, Offset);
7755 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007756 return Val;
7757}
Tim Northover39c70bb2014-08-12 11:52:59 +00007758
Tim Northover4bd286a2014-08-01 13:07:19 +00007759struct CompactUnwindEntry {
7760 uint32_t OffsetInSection;
7761
7762 uint64_t FunctionAddr;
7763 uint32_t Length;
7764 uint32_t CompactEncoding;
7765 uint64_t PersonalityAddr;
7766 uint64_t LSDAAddr;
7767
7768 RelocationRef FunctionReloc;
7769 RelocationRef PersonalityReloc;
7770 RelocationRef LSDAReloc;
7771
7772 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007773 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007774 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007775 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007776 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007777 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007778 }
7779
7780private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007781 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7782 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7783 Length = readNext<uint32_t>(Contents, Offset);
7784 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7785 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7786 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007787 }
7788};
7789}
7790
7791/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7792/// and data being relocated, determine the best base Name and Addend to use for
7793/// display purposes.
7794///
7795/// 1. An Extern relocation will directly reference a symbol (and the data is
7796/// then already an addend), so use that.
7797/// 2. Otherwise the data is an offset in the object file's layout; try to find
7798// a symbol before it in the same section, and use the offset from there.
7799/// 3. Finally, if all that fails, fall back to an offset from the start of the
7800/// referenced section.
7801static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7802 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007803 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007804 StringRef &Name, uint64_t &Addend) {
7805 if (Reloc.getSymbol() != Obj->symbol_end()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007806 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007807 Addend = Addr;
7808 return;
7809 }
7810
7811 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007812 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007813
Rafael Espindola80291272014-10-08 15:28:58 +00007814 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007815
7816 auto Sym = Symbols.upper_bound(Addr);
7817 if (Sym == Symbols.begin()) {
7818 // The first symbol in the object is after this reference, the best we can
George Rimarbcc00e12019-08-14 11:10:11 +00007819 // do is section-relative notation.
7820 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7821 Name = *NameOrErr;
7822 else
7823 consumeError(NameOrErr.takeError());
7824
Tim Northover4bd286a2014-08-01 13:07:19 +00007825 Addend = Addr - SectionAddr;
7826 return;
7827 }
7828
7829 // Go back one so that SymbolAddress <= Addr.
7830 --Sym;
7831
Fangrui Songe7834bd2019-04-07 08:19:55 +00007832 section_iterator SymSection =
7833 unwrapOrError(Sym->second.getSection(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007834 if (RelocSection == *SymSection) {
7835 // There's a valid symbol in the same section before this reference.
Fangrui Songe7834bd2019-04-07 08:19:55 +00007836 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007837 Addend = Addr - Sym->first;
7838 return;
7839 }
7840
7841 // There is a symbol before this reference, but it's in a different
7842 // section. Probably not helpful to mention it, so use the section name.
George Rimarbcc00e12019-08-14 11:10:11 +00007843 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7844 Name = *NameOrErr;
7845 else
7846 consumeError(NameOrErr.takeError());
7847
Tim Northover4bd286a2014-08-01 13:07:19 +00007848 Addend = Addr - SectionAddr;
7849}
7850
7851static void printUnwindRelocDest(const MachOObjectFile *Obj,
7852 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007853 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007854 StringRef Name;
7855 uint64_t Addend;
7856
Rafael Espindola854038e2015-06-26 14:51:16 +00007857 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007858 return;
7859
Tim Northover4bd286a2014-08-01 13:07:19 +00007860 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7861
7862 outs() << Name;
7863 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007864 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007865}
7866
7867static void
7868printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7869 std::map<uint64_t, SymbolRef> &Symbols,
7870 const SectionRef &CompactUnwind) {
7871
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007872 if (!Obj->isLittleEndian()) {
7873 outs() << "Skipping big-endian __compact_unwind section\n";
7874 return;
7875 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007876
7877 bool Is64 = Obj->is64Bit();
7878 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7879 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7880
Fangrui Songe1833402019-05-16 13:24:04 +00007881 StringRef Contents =
7882 unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007883 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7884
7885 // First populate the initial raw offsets, encodings and so on from the entry.
7886 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007887 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007888 CompactUnwinds.push_back(Entry);
7889 }
7890
7891 // Next we need to look at the relocations to find out what objects are
7892 // actually being referred to.
7893 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007894 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007895
7896 uint32_t EntryIdx = RelocAddress / EntrySize;
7897 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7898 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7899
7900 if (OffsetInEntry == 0)
7901 Entry.FunctionReloc = Reloc;
7902 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7903 Entry.PersonalityReloc = Reloc;
7904 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7905 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007906 else {
7907 outs() << "Invalid relocation in __compact_unwind section\n";
7908 return;
7909 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007910 }
7911
7912 // Finally, we're ready to print the data we've gathered.
7913 outs() << "Contents of __compact_unwind section:\n";
7914 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007915 outs() << " Entry at offset "
7916 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007917
7918 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007919 outs() << " start: " << format("0x%" PRIx64,
7920 Entry.FunctionAddr) << ' ';
7921 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007922 outs() << '\n';
7923
7924 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007925 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7926 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007927 // 3. The 32-bit compact encoding.
7928 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007929 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007930
7931 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007932 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007933 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007934 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007935 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7936 Entry.PersonalityAddr);
7937 outs() << '\n';
7938 }
7939
7940 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007941 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007942 outs() << " LSDA: " << format("0x%" PRIx64,
7943 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007944 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7945 outs() << '\n';
7946 }
7947 }
7948}
7949
Tim Northover39c70bb2014-08-12 11:52:59 +00007950//===----------------------------------------------------------------------===//
7951// __unwind_info section dumping
7952//===----------------------------------------------------------------------===//
7953
Tim Northover3a4e1c72018-01-23 13:51:57 +00007954static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7955 ptrdiff_t Pos = 0;
7956 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007957 (void)Kind;
7958 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7959
Tim Northover3a4e1c72018-01-23 13:51:57 +00007960 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7961 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007962
Tim Northover3a4e1c72018-01-23 13:51:57 +00007963 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007964 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007965 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7966 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007967
7968 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007969 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7970 << ", "
7971 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007972 }
7973}
7974
7975static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007976 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007977 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007978 ptrdiff_t Pos = 0;
7979 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007980 (void)Kind;
7981 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7982
Tim Northover3a4e1c72018-01-23 13:51:57 +00007983 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7984 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007985
Tim Northover3a4e1c72018-01-23 13:51:57 +00007986 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7987 readNext<uint16_t>(PageData, Pos);
7988 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007989
Tim Northover3a4e1c72018-01-23 13:51:57 +00007990 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007991 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007992 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007993 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7994 uint32_t EncodingIdx = Entry >> 24;
7995
7996 uint32_t Encoding;
7997 if (EncodingIdx < CommonEncodings.size())
7998 Encoding = CommonEncodings[EncodingIdx];
7999 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00008000 Encoding = read<uint32_t>(PageEncodings,
8001 sizeof(uint32_t) *
8002 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00008003
8004 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008005 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8006 << ", "
8007 << "encoding[" << EncodingIdx
8008 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00008009 }
8010}
8011
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008012static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8013 std::map<uint64_t, SymbolRef> &Symbols,
8014 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00008015
Tim Northoverbf55f7e2016-11-15 20:26:01 +00008016 if (!Obj->isLittleEndian()) {
8017 outs() << "Skipping big-endian __unwind_info section\n";
8018 return;
8019 }
Tim Northover39c70bb2014-08-12 11:52:59 +00008020
8021 outs() << "Contents of __unwind_info section:\n";
8022
Fangrui Songe1833402019-05-16 13:24:04 +00008023 StringRef Contents =
8024 unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
Tim Northover3a4e1c72018-01-23 13:51:57 +00008025 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00008026
8027 //===----------------------------------
8028 // Section header
8029 //===----------------------------------
8030
Tim Northover3a4e1c72018-01-23 13:51:57 +00008031 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008032 outs() << " Version: "
8033 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00008034 if (Version != 1) {
8035 outs() << " Skipping section with unknown version\n";
8036 return;
8037 }
Tim Northover39c70bb2014-08-12 11:52:59 +00008038
Tim Northover3a4e1c72018-01-23 13:51:57 +00008039 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008040 outs() << " Common encodings array section offset: "
8041 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00008042 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008043 outs() << " Number of common encodings in array: "
8044 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8045
Tim Northover3a4e1c72018-01-23 13:51:57 +00008046 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008047 outs() << " Personality function array section offset: "
8048 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00008049 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008050 outs() << " Number of personality functions in array: "
8051 << format("0x%" PRIx32, NumPersonalities) << '\n';
8052
Tim Northover3a4e1c72018-01-23 13:51:57 +00008053 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008054 outs() << " Index array section offset: "
8055 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00008056 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008057 outs() << " Number of indices in array: "
8058 << format("0x%" PRIx32, NumIndices) << '\n';
8059
8060 //===----------------------------------
8061 // A shared list of common encodings
8062 //===----------------------------------
8063
8064 // These occupy indices in the range [0, N] whenever an encoding is referenced
8065 // from a compressed 2nd level index table. In practice the linker only
8066 // creates ~128 of these, so that indices are available to embed encodings in
8067 // the 2nd level index.
8068
8069 SmallVector<uint32_t, 64> CommonEncodings;
8070 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00008071 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00008072 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00008073 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008074 CommonEncodings.push_back(Encoding);
8075
8076 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8077 << '\n';
8078 }
8079
Tim Northover39c70bb2014-08-12 11:52:59 +00008080 //===----------------------------------
8081 // Personality functions used in this executable
8082 //===----------------------------------
8083
8084 // There should be only a handful of these (one per source language,
8085 // roughly). Particularly since they only get 2 bits in the compact encoding.
8086
8087 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00008088 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00008089 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00008090 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008091 outs() << " personality[" << i + 1
8092 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8093 }
8094
8095 //===----------------------------------
8096 // The level 1 index entries
8097 //===----------------------------------
8098
8099 // These specify an approximate place to start searching for the more detailed
8100 // information, sorted by PC.
8101
8102 struct IndexEntry {
8103 uint32_t FunctionOffset;
8104 uint32_t SecondLevelPageStart;
8105 uint32_t LSDAStart;
8106 };
8107
8108 SmallVector<IndexEntry, 4> IndexEntries;
8109
8110 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00008111 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00008112 for (unsigned i = 0; i < NumIndices; ++i) {
8113 IndexEntry Entry;
8114
Tim Northover3a4e1c72018-01-23 13:51:57 +00008115 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8116 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8117 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008118 IndexEntries.push_back(Entry);
8119
8120 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008121 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8122 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00008123 << "2nd level page offset="
8124 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008125 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00008126 }
8127
Tim Northover39c70bb2014-08-12 11:52:59 +00008128 //===----------------------------------
8129 // Next come the LSDA tables
8130 //===----------------------------------
8131
8132 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8133 // the first top-level index's LSDAOffset to the last (sentinel).
8134
8135 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00008136 Pos = IndexEntries[0].LSDAStart;
8137 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8138 int NumLSDAs =
8139 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8140
Tim Northover39c70bb2014-08-12 11:52:59 +00008141 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00008142 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8143 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008144 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008145 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8146 << ", "
8147 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00008148 }
8149
8150 //===----------------------------------
8151 // Finally, the 2nd level indices
8152 //===----------------------------------
8153
8154 // Generally these are 4K in size, and have 2 possible forms:
8155 // + Regular stores up to 511 entries with disparate encodings
8156 // + Compressed stores up to 1021 entries if few enough compact encoding
8157 // values are used.
8158 outs() << " Second level indices:\n";
8159 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8160 // The final sentinel top-level index has no associated 2nd level page
8161 if (IndexEntries[i].SecondLevelPageStart == 0)
8162 break;
8163
8164 outs() << " Second level index[" << i << "]: "
8165 << "offset in section="
8166 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8167 << ", "
8168 << "base function offset="
8169 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8170
Tim Northover3a4e1c72018-01-23 13:51:57 +00008171 Pos = IndexEntries[i].SecondLevelPageStart;
8172 if (Pos + sizeof(uint32_t) > Contents.size()) {
8173 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8174 continue;
8175 }
8176
8177 uint32_t Kind =
8178 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008179 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00008180 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00008181 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00008182 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8183 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00008184 CommonEncodings);
8185 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00008186 outs() << " Skipping 2nd level page with unknown kind " << Kind
8187 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00008188 }
8189}
8190
Fangrui Song523758e2019-04-15 15:31:42 +00008191void printMachOUnwindInfo(const MachOObjectFile *Obj) {
Tim Northover4bd286a2014-08-01 13:07:19 +00008192 std::map<uint64_t, SymbolRef> Symbols;
8193 for (const SymbolRef &SymRef : Obj->symbols()) {
8194 // Discard any undefined or absolute symbols. They're not going to take part
8195 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00008196 auto SectOrErr = SymRef.getSection();
8197 if (!SectOrErr) {
8198 // TODO: Actually report errors helpfully.
8199 consumeError(SectOrErr.takeError());
8200 continue;
8201 }
8202 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00008203 if (Section == Obj->section_end())
8204 continue;
8205
Rafael Espindoladea00162015-07-03 17:44:18 +00008206 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00008207 Symbols.insert(std::make_pair(Addr, SymRef));
8208 }
8209
8210 for (const SectionRef &Section : Obj->sections()) {
8211 StringRef SectName;
George Rimarbcc00e12019-08-14 11:10:11 +00008212 if (Expected<StringRef> NameOrErr = Section.getName())
8213 SectName = *NameOrErr;
8214 else
8215 consumeError(NameOrErr.takeError());
8216
Tim Northover4bd286a2014-08-01 13:07:19 +00008217 if (SectName == "__compact_unwind")
8218 printMachOCompactUnwindSection(Obj, Symbols, Section);
8219 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00008220 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00008221 }
8222}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008223
8224static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8225 uint32_t cpusubtype, uint32_t filetype,
8226 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8227 bool verbose) {
8228 outs() << "Mach header\n";
8229 outs() << " magic cputype cpusubtype caps filetype ncmds "
8230 "sizeofcmds flags\n";
8231 if (verbose) {
8232 if (magic == MachO::MH_MAGIC)
8233 outs() << " MH_MAGIC";
8234 else if (magic == MachO::MH_MAGIC_64)
8235 outs() << "MH_MAGIC_64";
8236 else
8237 outs() << format(" 0x%08" PRIx32, magic);
8238 switch (cputype) {
8239 case MachO::CPU_TYPE_I386:
8240 outs() << " I386";
8241 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8242 case MachO::CPU_SUBTYPE_I386_ALL:
8243 outs() << " ALL";
8244 break;
8245 default:
8246 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8247 break;
8248 }
8249 break;
8250 case MachO::CPU_TYPE_X86_64:
8251 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00008252 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8253 case MachO::CPU_SUBTYPE_X86_64_ALL:
8254 outs() << " ALL";
8255 break;
8256 case MachO::CPU_SUBTYPE_X86_64_H:
8257 outs() << " Haswell";
8258 break;
8259 default:
8260 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8261 break;
8262 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008263 break;
8264 case MachO::CPU_TYPE_ARM:
8265 outs() << " ARM";
8266 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8267 case MachO::CPU_SUBTYPE_ARM_ALL:
8268 outs() << " ALL";
8269 break;
8270 case MachO::CPU_SUBTYPE_ARM_V4T:
8271 outs() << " V4T";
8272 break;
8273 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8274 outs() << " V5TEJ";
8275 break;
8276 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8277 outs() << " XSCALE";
8278 break;
8279 case MachO::CPU_SUBTYPE_ARM_V6:
8280 outs() << " V6";
8281 break;
8282 case MachO::CPU_SUBTYPE_ARM_V6M:
8283 outs() << " V6M";
8284 break;
8285 case MachO::CPU_SUBTYPE_ARM_V7:
8286 outs() << " V7";
8287 break;
8288 case MachO::CPU_SUBTYPE_ARM_V7EM:
8289 outs() << " V7EM";
8290 break;
8291 case MachO::CPU_SUBTYPE_ARM_V7K:
8292 outs() << " V7K";
8293 break;
8294 case MachO::CPU_SUBTYPE_ARM_V7M:
8295 outs() << " V7M";
8296 break;
8297 case MachO::CPU_SUBTYPE_ARM_V7S:
8298 outs() << " V7S";
8299 break;
8300 default:
8301 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8302 break;
8303 }
8304 break;
8305 case MachO::CPU_TYPE_ARM64:
8306 outs() << " ARM64";
8307 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8308 case MachO::CPU_SUBTYPE_ARM64_ALL:
8309 outs() << " ALL";
8310 break;
Shoaib Meenai867131a2019-04-08 21:37:08 +00008311 case MachO::CPU_SUBTYPE_ARM64E:
8312 outs() << " E";
8313 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008314 default:
8315 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8316 break;
8317 }
8318 break;
Tim Northoverff6875a2019-05-14 11:25:44 +00008319 case MachO::CPU_TYPE_ARM64_32:
8320 outs() << " ARM64_32";
8321 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8322 case MachO::CPU_SUBTYPE_ARM64_32_V8:
8323 outs() << " V8";
8324 break;
8325 default:
8326 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8327 break;
8328 }
8329 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008330 case MachO::CPU_TYPE_POWERPC:
8331 outs() << " PPC";
8332 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8333 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8334 outs() << " ALL";
8335 break;
8336 default:
8337 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8338 break;
8339 }
8340 break;
8341 case MachO::CPU_TYPE_POWERPC64:
8342 outs() << " PPC64";
8343 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8344 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8345 outs() << " ALL";
8346 break;
8347 default:
8348 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8349 break;
8350 }
8351 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00008352 default:
8353 outs() << format(" %7d", cputype);
8354 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8355 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008356 }
8357 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008358 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008359 } else {
8360 outs() << format(" 0x%02" PRIx32,
8361 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8362 }
8363 switch (filetype) {
8364 case MachO::MH_OBJECT:
8365 outs() << " OBJECT";
8366 break;
8367 case MachO::MH_EXECUTE:
8368 outs() << " EXECUTE";
8369 break;
8370 case MachO::MH_FVMLIB:
8371 outs() << " FVMLIB";
8372 break;
8373 case MachO::MH_CORE:
8374 outs() << " CORE";
8375 break;
8376 case MachO::MH_PRELOAD:
8377 outs() << " PRELOAD";
8378 break;
8379 case MachO::MH_DYLIB:
8380 outs() << " DYLIB";
8381 break;
8382 case MachO::MH_DYLIB_STUB:
8383 outs() << " DYLIB_STUB";
8384 break;
8385 case MachO::MH_DYLINKER:
8386 outs() << " DYLINKER";
8387 break;
8388 case MachO::MH_BUNDLE:
8389 outs() << " BUNDLE";
8390 break;
8391 case MachO::MH_DSYM:
8392 outs() << " DSYM";
8393 break;
8394 case MachO::MH_KEXT_BUNDLE:
8395 outs() << " KEXTBUNDLE";
8396 break;
8397 default:
8398 outs() << format(" %10u", filetype);
8399 break;
8400 }
8401 outs() << format(" %5u", ncmds);
8402 outs() << format(" %10u", sizeofcmds);
8403 uint32_t f = flags;
8404 if (f & MachO::MH_NOUNDEFS) {
8405 outs() << " NOUNDEFS";
8406 f &= ~MachO::MH_NOUNDEFS;
8407 }
8408 if (f & MachO::MH_INCRLINK) {
8409 outs() << " INCRLINK";
8410 f &= ~MachO::MH_INCRLINK;
8411 }
8412 if (f & MachO::MH_DYLDLINK) {
8413 outs() << " DYLDLINK";
8414 f &= ~MachO::MH_DYLDLINK;
8415 }
8416 if (f & MachO::MH_BINDATLOAD) {
8417 outs() << " BINDATLOAD";
8418 f &= ~MachO::MH_BINDATLOAD;
8419 }
8420 if (f & MachO::MH_PREBOUND) {
8421 outs() << " PREBOUND";
8422 f &= ~MachO::MH_PREBOUND;
8423 }
8424 if (f & MachO::MH_SPLIT_SEGS) {
8425 outs() << " SPLIT_SEGS";
8426 f &= ~MachO::MH_SPLIT_SEGS;
8427 }
8428 if (f & MachO::MH_LAZY_INIT) {
8429 outs() << " LAZY_INIT";
8430 f &= ~MachO::MH_LAZY_INIT;
8431 }
8432 if (f & MachO::MH_TWOLEVEL) {
8433 outs() << " TWOLEVEL";
8434 f &= ~MachO::MH_TWOLEVEL;
8435 }
8436 if (f & MachO::MH_FORCE_FLAT) {
8437 outs() << " FORCE_FLAT";
8438 f &= ~MachO::MH_FORCE_FLAT;
8439 }
8440 if (f & MachO::MH_NOMULTIDEFS) {
8441 outs() << " NOMULTIDEFS";
8442 f &= ~MachO::MH_NOMULTIDEFS;
8443 }
8444 if (f & MachO::MH_NOFIXPREBINDING) {
8445 outs() << " NOFIXPREBINDING";
8446 f &= ~MachO::MH_NOFIXPREBINDING;
8447 }
8448 if (f & MachO::MH_PREBINDABLE) {
8449 outs() << " PREBINDABLE";
8450 f &= ~MachO::MH_PREBINDABLE;
8451 }
8452 if (f & MachO::MH_ALLMODSBOUND) {
8453 outs() << " ALLMODSBOUND";
8454 f &= ~MachO::MH_ALLMODSBOUND;
8455 }
8456 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8457 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8458 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8459 }
8460 if (f & MachO::MH_CANONICAL) {
8461 outs() << " CANONICAL";
8462 f &= ~MachO::MH_CANONICAL;
8463 }
8464 if (f & MachO::MH_WEAK_DEFINES) {
8465 outs() << " WEAK_DEFINES";
8466 f &= ~MachO::MH_WEAK_DEFINES;
8467 }
8468 if (f & MachO::MH_BINDS_TO_WEAK) {
8469 outs() << " BINDS_TO_WEAK";
8470 f &= ~MachO::MH_BINDS_TO_WEAK;
8471 }
8472 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8473 outs() << " ALLOW_STACK_EXECUTION";
8474 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8475 }
8476 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8477 outs() << " DEAD_STRIPPABLE_DYLIB";
8478 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8479 }
8480 if (f & MachO::MH_PIE) {
8481 outs() << " PIE";
8482 f &= ~MachO::MH_PIE;
8483 }
8484 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8485 outs() << " NO_REEXPORTED_DYLIBS";
8486 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8487 }
8488 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8489 outs() << " MH_HAS_TLV_DESCRIPTORS";
8490 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8491 }
8492 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8493 outs() << " MH_NO_HEAP_EXECUTION";
8494 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8495 }
8496 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8497 outs() << " APP_EXTENSION_SAFE";
8498 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8499 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008500 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8501 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8502 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8503 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008504 if (f != 0 || flags == 0)
8505 outs() << format(" 0x%08" PRIx32, f);
8506 } else {
8507 outs() << format(" 0x%08" PRIx32, magic);
8508 outs() << format(" %7d", cputype);
8509 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8510 outs() << format(" 0x%02" PRIx32,
8511 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8512 outs() << format(" %10u", filetype);
8513 outs() << format(" %5u", ncmds);
8514 outs() << format(" %10u", sizeofcmds);
8515 outs() << format(" 0x%08" PRIx32, flags);
8516 }
8517 outs() << "\n";
8518}
8519
Kevin Enderby956366c2014-08-29 22:30:52 +00008520static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8521 StringRef SegName, uint64_t vmaddr,
8522 uint64_t vmsize, uint64_t fileoff,
8523 uint64_t filesize, uint32_t maxprot,
8524 uint32_t initprot, uint32_t nsects,
8525 uint32_t flags, uint32_t object_size,
8526 bool verbose) {
8527 uint64_t expected_cmdsize;
8528 if (cmd == MachO::LC_SEGMENT) {
8529 outs() << " cmd LC_SEGMENT\n";
8530 expected_cmdsize = nsects;
8531 expected_cmdsize *= sizeof(struct MachO::section);
8532 expected_cmdsize += sizeof(struct MachO::segment_command);
8533 } else {
8534 outs() << " cmd LC_SEGMENT_64\n";
8535 expected_cmdsize = nsects;
8536 expected_cmdsize *= sizeof(struct MachO::section_64);
8537 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8538 }
8539 outs() << " cmdsize " << cmdsize;
8540 if (cmdsize != expected_cmdsize)
8541 outs() << " Inconsistent size\n";
8542 else
8543 outs() << "\n";
8544 outs() << " segname " << SegName << "\n";
8545 if (cmd == MachO::LC_SEGMENT_64) {
8546 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8547 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8548 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008549 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8550 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008551 }
8552 outs() << " fileoff " << fileoff;
8553 if (fileoff > object_size)
8554 outs() << " (past end of file)\n";
8555 else
8556 outs() << "\n";
8557 outs() << " filesize " << filesize;
8558 if (fileoff + filesize > object_size)
8559 outs() << " (past end of file)\n";
8560 else
8561 outs() << "\n";
8562 if (verbose) {
8563 if ((maxprot &
8564 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8565 MachO::VM_PROT_EXECUTE)) != 0)
8566 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8567 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008568 outs() << " maxprot ";
8569 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8570 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8571 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008572 }
8573 if ((initprot &
8574 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8575 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008576 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008577 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008578 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008579 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8580 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8581 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008582 }
8583 } else {
8584 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8585 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8586 }
8587 outs() << " nsects " << nsects << "\n";
8588 if (verbose) {
8589 outs() << " flags";
8590 if (flags == 0)
8591 outs() << " (none)\n";
8592 else {
8593 if (flags & MachO::SG_HIGHVM) {
8594 outs() << " HIGHVM";
8595 flags &= ~MachO::SG_HIGHVM;
8596 }
8597 if (flags & MachO::SG_FVMLIB) {
8598 outs() << " FVMLIB";
8599 flags &= ~MachO::SG_FVMLIB;
8600 }
8601 if (flags & MachO::SG_NORELOC) {
8602 outs() << " NORELOC";
8603 flags &= ~MachO::SG_NORELOC;
8604 }
8605 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8606 outs() << " PROTECTED_VERSION_1";
8607 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8608 }
8609 if (flags)
8610 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8611 else
8612 outs() << "\n";
8613 }
8614 } else {
8615 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8616 }
8617}
8618
8619static void PrintSection(const char *sectname, const char *segname,
8620 uint64_t addr, uint64_t size, uint32_t offset,
8621 uint32_t align, uint32_t reloff, uint32_t nreloc,
8622 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8623 uint32_t cmd, const char *sg_segname,
8624 uint32_t filetype, uint32_t object_size,
8625 bool verbose) {
8626 outs() << "Section\n";
8627 outs() << " sectname " << format("%.16s\n", sectname);
8628 outs() << " segname " << format("%.16s", segname);
8629 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8630 outs() << " (does not match segment)\n";
8631 else
8632 outs() << "\n";
8633 if (cmd == MachO::LC_SEGMENT_64) {
8634 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8635 outs() << " size " << format("0x%016" PRIx64, size);
8636 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008637 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8638 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008639 }
8640 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8641 outs() << " (past end of file)\n";
8642 else
8643 outs() << "\n";
8644 outs() << " offset " << offset;
8645 if (offset > object_size)
8646 outs() << " (past end of file)\n";
8647 else
8648 outs() << "\n";
8649 uint32_t align_shifted = 1 << align;
8650 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8651 outs() << " reloff " << reloff;
8652 if (reloff > object_size)
8653 outs() << " (past end of file)\n";
8654 else
8655 outs() << "\n";
8656 outs() << " nreloc " << nreloc;
8657 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8658 outs() << " (past end of file)\n";
8659 else
8660 outs() << "\n";
8661 uint32_t section_type = flags & MachO::SECTION_TYPE;
8662 if (verbose) {
8663 outs() << " type";
8664 if (section_type == MachO::S_REGULAR)
8665 outs() << " S_REGULAR\n";
8666 else if (section_type == MachO::S_ZEROFILL)
8667 outs() << " S_ZEROFILL\n";
8668 else if (section_type == MachO::S_CSTRING_LITERALS)
8669 outs() << " S_CSTRING_LITERALS\n";
8670 else if (section_type == MachO::S_4BYTE_LITERALS)
8671 outs() << " S_4BYTE_LITERALS\n";
8672 else if (section_type == MachO::S_8BYTE_LITERALS)
8673 outs() << " S_8BYTE_LITERALS\n";
8674 else if (section_type == MachO::S_16BYTE_LITERALS)
8675 outs() << " S_16BYTE_LITERALS\n";
8676 else if (section_type == MachO::S_LITERAL_POINTERS)
8677 outs() << " S_LITERAL_POINTERS\n";
8678 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8679 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8680 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8681 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8682 else if (section_type == MachO::S_SYMBOL_STUBS)
8683 outs() << " S_SYMBOL_STUBS\n";
8684 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8685 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8686 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8687 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8688 else if (section_type == MachO::S_COALESCED)
8689 outs() << " S_COALESCED\n";
8690 else if (section_type == MachO::S_INTERPOSING)
8691 outs() << " S_INTERPOSING\n";
8692 else if (section_type == MachO::S_DTRACE_DOF)
8693 outs() << " S_DTRACE_DOF\n";
8694 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8695 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8696 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8697 outs() << " S_THREAD_LOCAL_REGULAR\n";
8698 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8699 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8700 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8701 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8702 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8703 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8704 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8705 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8706 else
8707 outs() << format("0x%08" PRIx32, section_type) << "\n";
8708 outs() << "attributes";
8709 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8710 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8711 outs() << " PURE_INSTRUCTIONS";
8712 if (section_attributes & MachO::S_ATTR_NO_TOC)
8713 outs() << " NO_TOC";
8714 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8715 outs() << " STRIP_STATIC_SYMS";
8716 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8717 outs() << " NO_DEAD_STRIP";
8718 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8719 outs() << " LIVE_SUPPORT";
8720 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8721 outs() << " SELF_MODIFYING_CODE";
8722 if (section_attributes & MachO::S_ATTR_DEBUG)
8723 outs() << " DEBUG";
8724 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8725 outs() << " SOME_INSTRUCTIONS";
8726 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8727 outs() << " EXT_RELOC";
8728 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8729 outs() << " LOC_RELOC";
8730 if (section_attributes == 0)
8731 outs() << " (none)";
8732 outs() << "\n";
8733 } else
8734 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8735 outs() << " reserved1 " << reserved1;
8736 if (section_type == MachO::S_SYMBOL_STUBS ||
8737 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8738 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8739 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8740 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8741 outs() << " (index into indirect symbol table)\n";
8742 else
8743 outs() << "\n";
8744 outs() << " reserved2 " << reserved2;
8745 if (section_type == MachO::S_SYMBOL_STUBS)
8746 outs() << " (size of stubs)\n";
8747 else
8748 outs() << "\n";
8749}
8750
David Majnemer73cc6ff2014-11-13 19:48:56 +00008751static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008752 uint32_t object_size) {
8753 outs() << " cmd LC_SYMTAB\n";
8754 outs() << " cmdsize " << st.cmdsize;
8755 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8756 outs() << " Incorrect size\n";
8757 else
8758 outs() << "\n";
8759 outs() << " symoff " << st.symoff;
8760 if (st.symoff > object_size)
8761 outs() << " (past end of file)\n";
8762 else
8763 outs() << "\n";
8764 outs() << " nsyms " << st.nsyms;
8765 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008766 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008767 big_size = st.nsyms;
8768 big_size *= sizeof(struct MachO::nlist_64);
8769 big_size += st.symoff;
8770 if (big_size > object_size)
8771 outs() << " (past end of file)\n";
8772 else
8773 outs() << "\n";
8774 } else {
8775 big_size = st.nsyms;
8776 big_size *= sizeof(struct MachO::nlist);
8777 big_size += st.symoff;
8778 if (big_size > object_size)
8779 outs() << " (past end of file)\n";
8780 else
8781 outs() << "\n";
8782 }
8783 outs() << " stroff " << st.stroff;
8784 if (st.stroff > object_size)
8785 outs() << " (past end of file)\n";
8786 else
8787 outs() << "\n";
8788 outs() << " strsize " << st.strsize;
8789 big_size = st.stroff;
8790 big_size += st.strsize;
8791 if (big_size > object_size)
8792 outs() << " (past end of file)\n";
8793 else
8794 outs() << "\n";
8795}
8796
8797static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8798 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008799 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008800 outs() << " cmd LC_DYSYMTAB\n";
8801 outs() << " cmdsize " << dyst.cmdsize;
8802 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8803 outs() << " Incorrect size\n";
8804 else
8805 outs() << "\n";
8806 outs() << " ilocalsym " << dyst.ilocalsym;
8807 if (dyst.ilocalsym > nsyms)
8808 outs() << " (greater than the number of symbols)\n";
8809 else
8810 outs() << "\n";
8811 outs() << " nlocalsym " << dyst.nlocalsym;
8812 uint64_t big_size;
8813 big_size = dyst.ilocalsym;
8814 big_size += dyst.nlocalsym;
8815 if (big_size > nsyms)
8816 outs() << " (past the end of the symbol table)\n";
8817 else
8818 outs() << "\n";
8819 outs() << " iextdefsym " << dyst.iextdefsym;
8820 if (dyst.iextdefsym > nsyms)
8821 outs() << " (greater than the number of symbols)\n";
8822 else
8823 outs() << "\n";
8824 outs() << " nextdefsym " << dyst.nextdefsym;
8825 big_size = dyst.iextdefsym;
8826 big_size += dyst.nextdefsym;
8827 if (big_size > nsyms)
8828 outs() << " (past the end of the symbol table)\n";
8829 else
8830 outs() << "\n";
8831 outs() << " iundefsym " << dyst.iundefsym;
8832 if (dyst.iundefsym > nsyms)
8833 outs() << " (greater than the number of symbols)\n";
8834 else
8835 outs() << "\n";
8836 outs() << " nundefsym " << dyst.nundefsym;
8837 big_size = dyst.iundefsym;
8838 big_size += dyst.nundefsym;
8839 if (big_size > nsyms)
8840 outs() << " (past the end of the symbol table)\n";
8841 else
8842 outs() << "\n";
8843 outs() << " tocoff " << dyst.tocoff;
8844 if (dyst.tocoff > object_size)
8845 outs() << " (past end of file)\n";
8846 else
8847 outs() << "\n";
8848 outs() << " ntoc " << dyst.ntoc;
8849 big_size = dyst.ntoc;
8850 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8851 big_size += dyst.tocoff;
8852 if (big_size > object_size)
8853 outs() << " (past end of file)\n";
8854 else
8855 outs() << "\n";
8856 outs() << " modtaboff " << dyst.modtaboff;
8857 if (dyst.modtaboff > object_size)
8858 outs() << " (past end of file)\n";
8859 else
8860 outs() << "\n";
8861 outs() << " nmodtab " << dyst.nmodtab;
8862 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008863 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008864 modtabend = dyst.nmodtab;
8865 modtabend *= sizeof(struct MachO::dylib_module_64);
8866 modtabend += dyst.modtaboff;
8867 } else {
8868 modtabend = dyst.nmodtab;
8869 modtabend *= sizeof(struct MachO::dylib_module);
8870 modtabend += dyst.modtaboff;
8871 }
8872 if (modtabend > object_size)
8873 outs() << " (past end of file)\n";
8874 else
8875 outs() << "\n";
8876 outs() << " extrefsymoff " << dyst.extrefsymoff;
8877 if (dyst.extrefsymoff > object_size)
8878 outs() << " (past end of file)\n";
8879 else
8880 outs() << "\n";
8881 outs() << " nextrefsyms " << dyst.nextrefsyms;
8882 big_size = dyst.nextrefsyms;
8883 big_size *= sizeof(struct MachO::dylib_reference);
8884 big_size += dyst.extrefsymoff;
8885 if (big_size > object_size)
8886 outs() << " (past end of file)\n";
8887 else
8888 outs() << "\n";
8889 outs() << " indirectsymoff " << dyst.indirectsymoff;
8890 if (dyst.indirectsymoff > object_size)
8891 outs() << " (past end of file)\n";
8892 else
8893 outs() << "\n";
8894 outs() << " nindirectsyms " << dyst.nindirectsyms;
8895 big_size = dyst.nindirectsyms;
8896 big_size *= sizeof(uint32_t);
8897 big_size += dyst.indirectsymoff;
8898 if (big_size > object_size)
8899 outs() << " (past end of file)\n";
8900 else
8901 outs() << "\n";
8902 outs() << " extreloff " << dyst.extreloff;
8903 if (dyst.extreloff > object_size)
8904 outs() << " (past end of file)\n";
8905 else
8906 outs() << "\n";
8907 outs() << " nextrel " << dyst.nextrel;
8908 big_size = dyst.nextrel;
8909 big_size *= sizeof(struct MachO::relocation_info);
8910 big_size += dyst.extreloff;
8911 if (big_size > object_size)
8912 outs() << " (past end of file)\n";
8913 else
8914 outs() << "\n";
8915 outs() << " locreloff " << dyst.locreloff;
8916 if (dyst.locreloff > object_size)
8917 outs() << " (past end of file)\n";
8918 else
8919 outs() << "\n";
8920 outs() << " nlocrel " << dyst.nlocrel;
8921 big_size = dyst.nlocrel;
8922 big_size *= sizeof(struct MachO::relocation_info);
8923 big_size += dyst.locreloff;
8924 if (big_size > object_size)
8925 outs() << " (past end of file)\n";
8926 else
8927 outs() << "\n";
8928}
8929
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008930static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8931 uint32_t object_size) {
8932 if (dc.cmd == MachO::LC_DYLD_INFO)
8933 outs() << " cmd LC_DYLD_INFO\n";
8934 else
8935 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8936 outs() << " cmdsize " << dc.cmdsize;
8937 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8938 outs() << " Incorrect size\n";
8939 else
8940 outs() << "\n";
8941 outs() << " rebase_off " << dc.rebase_off;
8942 if (dc.rebase_off > object_size)
8943 outs() << " (past end of file)\n";
8944 else
8945 outs() << "\n";
8946 outs() << " rebase_size " << dc.rebase_size;
8947 uint64_t big_size;
8948 big_size = dc.rebase_off;
8949 big_size += dc.rebase_size;
8950 if (big_size > object_size)
8951 outs() << " (past end of file)\n";
8952 else
8953 outs() << "\n";
8954 outs() << " bind_off " << dc.bind_off;
8955 if (dc.bind_off > object_size)
8956 outs() << " (past end of file)\n";
8957 else
8958 outs() << "\n";
8959 outs() << " bind_size " << dc.bind_size;
8960 big_size = dc.bind_off;
8961 big_size += dc.bind_size;
8962 if (big_size > object_size)
8963 outs() << " (past end of file)\n";
8964 else
8965 outs() << "\n";
8966 outs() << " weak_bind_off " << dc.weak_bind_off;
8967 if (dc.weak_bind_off > object_size)
8968 outs() << " (past end of file)\n";
8969 else
8970 outs() << "\n";
8971 outs() << " weak_bind_size " << dc.weak_bind_size;
8972 big_size = dc.weak_bind_off;
8973 big_size += dc.weak_bind_size;
8974 if (big_size > object_size)
8975 outs() << " (past end of file)\n";
8976 else
8977 outs() << "\n";
8978 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8979 if (dc.lazy_bind_off > object_size)
8980 outs() << " (past end of file)\n";
8981 else
8982 outs() << "\n";
8983 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8984 big_size = dc.lazy_bind_off;
8985 big_size += dc.lazy_bind_size;
8986 if (big_size > object_size)
8987 outs() << " (past end of file)\n";
8988 else
8989 outs() << "\n";
8990 outs() << " export_off " << dc.export_off;
8991 if (dc.export_off > object_size)
8992 outs() << " (past end of file)\n";
8993 else
8994 outs() << "\n";
8995 outs() << " export_size " << dc.export_size;
8996 big_size = dc.export_off;
8997 big_size += dc.export_size;
8998 if (big_size > object_size)
8999 outs() << " (past end of file)\n";
9000 else
9001 outs() << "\n";
9002}
9003
9004static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9005 const char *Ptr) {
9006 if (dyld.cmd == MachO::LC_ID_DYLINKER)
9007 outs() << " cmd LC_ID_DYLINKER\n";
9008 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9009 outs() << " cmd LC_LOAD_DYLINKER\n";
9010 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9011 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
9012 else
9013 outs() << " cmd ?(" << dyld.cmd << ")\n";
9014 outs() << " cmdsize " << dyld.cmdsize;
9015 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9016 outs() << " Incorrect size\n";
9017 else
9018 outs() << "\n";
9019 if (dyld.name >= dyld.cmdsize)
9020 outs() << " name ?(bad offset " << dyld.name << ")\n";
9021 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009022 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009023 outs() << " name " << P << " (offset " << dyld.name << ")\n";
9024 }
9025}
9026
9027static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9028 outs() << " cmd LC_UUID\n";
9029 outs() << " cmdsize " << uuid.cmdsize;
9030 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9031 outs() << " Incorrect size\n";
9032 else
9033 outs() << "\n";
9034 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00009035 for (int i = 0; i < 16; ++i) {
9036 outs() << format("%02" PRIX32, uuid.uuid[i]);
9037 if (i == 3 || i == 5 || i == 7 || i == 9)
9038 outs() << "-";
9039 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009040 outs() << "\n";
9041}
9042
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009043static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009044 outs() << " cmd LC_RPATH\n";
9045 outs() << " cmdsize " << rpath.cmdsize;
9046 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9047 outs() << " Incorrect size\n";
9048 else
9049 outs() << "\n";
9050 if (rpath.path >= rpath.cmdsize)
9051 outs() << " path ?(bad offset " << rpath.path << ")\n";
9052 else {
9053 const char *P = (const char *)(Ptr) + rpath.path;
9054 outs() << " path " << P << " (offset " << rpath.path << ")\n";
9055 }
9056}
9057
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009058static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00009059 StringRef LoadCmdName;
9060 switch (vd.cmd) {
9061 case MachO::LC_VERSION_MIN_MACOSX:
9062 LoadCmdName = "LC_VERSION_MIN_MACOSX";
9063 break;
9064 case MachO::LC_VERSION_MIN_IPHONEOS:
9065 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9066 break;
9067 case MachO::LC_VERSION_MIN_TVOS:
9068 LoadCmdName = "LC_VERSION_MIN_TVOS";
9069 break;
9070 case MachO::LC_VERSION_MIN_WATCHOS:
9071 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9072 break;
9073 default:
9074 llvm_unreachable("Unknown version min load command");
9075 }
9076
9077 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009078 outs() << " cmdsize " << vd.cmdsize;
9079 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9080 outs() << " Incorrect size\n";
9081 else
9082 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00009083 outs() << " version "
9084 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9085 << MachOObjectFile::getVersionMinMinor(vd, false);
9086 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9087 if (Update != 0)
9088 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009089 outs() << "\n";
9090 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00009091 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009092 else {
Davide Italiano56baef32015-08-26 12:26:11 +00009093 outs() << " sdk "
9094 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9095 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009096 }
Davide Italiano56baef32015-08-26 12:26:11 +00009097 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9098 if (Update != 0)
9099 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009100 outs() << "\n";
9101}
9102
Kevin Enderbya4579c42017-01-19 17:36:31 +00009103static void PrintNoteLoadCommand(MachO::note_command Nt) {
9104 outs() << " cmd LC_NOTE\n";
9105 outs() << " cmdsize " << Nt.cmdsize;
9106 if (Nt.cmdsize != sizeof(struct MachO::note_command))
9107 outs() << " Incorrect size\n";
9108 else
9109 outs() << "\n";
9110 const char *d = Nt.data_owner;
9111 outs() << "data_owner " << format("%.16s\n", d);
9112 outs() << " offset " << Nt.offset << "\n";
9113 outs() << " size " << Nt.size << "\n";
9114}
9115
Steven Wu5b54a422017-01-23 20:07:55 +00009116static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9117 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9118 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
9119 << "\n";
9120}
9121
9122static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9123 MachO::build_version_command bd) {
9124 outs() << " cmd LC_BUILD_VERSION\n";
9125 outs() << " cmdsize " << bd.cmdsize;
9126 if (bd.cmdsize !=
9127 sizeof(struct MachO::build_version_command) +
9128 bd.ntools * sizeof(struct MachO::build_tool_version))
9129 outs() << " Incorrect size\n";
9130 else
9131 outs() << "\n";
9132 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9133 << "\n";
9134 if (bd.sdk)
9135 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
9136 << "\n";
9137 else
9138 outs() << " sdk n/a\n";
9139 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
9140 << "\n";
9141 outs() << " ntools " << bd.ntools << "\n";
9142 for (unsigned i = 0; i < bd.ntools; ++i) {
9143 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9144 PrintBuildToolVersion(bv);
9145 }
9146}
9147
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009148static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9149 outs() << " cmd LC_SOURCE_VERSION\n";
9150 outs() << " cmdsize " << sd.cmdsize;
9151 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9152 outs() << " Incorrect size\n";
9153 else
9154 outs() << "\n";
9155 uint64_t a = (sd.version >> 40) & 0xffffff;
9156 uint64_t b = (sd.version >> 30) & 0x3ff;
9157 uint64_t c = (sd.version >> 20) & 0x3ff;
9158 uint64_t d = (sd.version >> 10) & 0x3ff;
9159 uint64_t e = sd.version & 0x3ff;
9160 outs() << " version " << a << "." << b;
9161 if (e != 0)
9162 outs() << "." << c << "." << d << "." << e;
9163 else if (d != 0)
9164 outs() << "." << c << "." << d;
9165 else if (c != 0)
9166 outs() << "." << c;
9167 outs() << "\n";
9168}
9169
9170static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9171 outs() << " cmd LC_MAIN\n";
9172 outs() << " cmdsize " << ep.cmdsize;
9173 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9174 outs() << " Incorrect size\n";
9175 else
9176 outs() << "\n";
9177 outs() << " entryoff " << ep.entryoff << "\n";
9178 outs() << " stacksize " << ep.stacksize << "\n";
9179}
9180
Kevin Enderby0804f4672014-12-16 23:25:52 +00009181static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9182 uint32_t object_size) {
9183 outs() << " cmd LC_ENCRYPTION_INFO\n";
9184 outs() << " cmdsize " << ec.cmdsize;
9185 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9186 outs() << " Incorrect size\n";
9187 else
9188 outs() << "\n";
9189 outs() << " cryptoff " << ec.cryptoff;
9190 if (ec.cryptoff > object_size)
9191 outs() << " (past end of file)\n";
9192 else
9193 outs() << "\n";
9194 outs() << " cryptsize " << ec.cryptsize;
9195 if (ec.cryptsize > object_size)
9196 outs() << " (past end of file)\n";
9197 else
9198 outs() << "\n";
9199 outs() << " cryptid " << ec.cryptid << "\n";
9200}
9201
Kevin Enderby57538292014-12-17 01:01:30 +00009202static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009203 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00009204 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
9205 outs() << " cmdsize " << ec.cmdsize;
9206 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9207 outs() << " Incorrect size\n";
9208 else
9209 outs() << "\n";
9210 outs() << " cryptoff " << ec.cryptoff;
9211 if (ec.cryptoff > object_size)
9212 outs() << " (past end of file)\n";
9213 else
9214 outs() << "\n";
9215 outs() << " cryptsize " << ec.cryptsize;
9216 if (ec.cryptsize > object_size)
9217 outs() << " (past end of file)\n";
9218 else
9219 outs() << "\n";
9220 outs() << " cryptid " << ec.cryptid << "\n";
9221 outs() << " pad " << ec.pad << "\n";
9222}
9223
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009224static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9225 const char *Ptr) {
9226 outs() << " cmd LC_LINKER_OPTION\n";
9227 outs() << " cmdsize " << lo.cmdsize;
9228 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9229 outs() << " Incorrect size\n";
9230 else
9231 outs() << "\n";
9232 outs() << " count " << lo.count << "\n";
9233 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9234 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9235 uint32_t i = 0;
9236 while (left > 0) {
9237 while (*string == '\0' && left > 0) {
9238 string++;
9239 left--;
9240 }
9241 if (left > 0) {
9242 i++;
9243 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00009244 uint32_t NullPos = StringRef(string, left).find('\0');
9245 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009246 string += len;
9247 left -= len;
9248 }
9249 }
9250 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009251 outs() << " count " << lo.count << " does not match number of strings "
9252 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009253}
9254
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009255static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9256 const char *Ptr) {
9257 outs() << " cmd LC_SUB_FRAMEWORK\n";
9258 outs() << " cmdsize " << sub.cmdsize;
9259 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9260 outs() << " Incorrect size\n";
9261 else
9262 outs() << "\n";
9263 if (sub.umbrella < sub.cmdsize) {
9264 const char *P = Ptr + sub.umbrella;
9265 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9266 } else {
9267 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9268 }
9269}
9270
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009271static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9272 const char *Ptr) {
9273 outs() << " cmd LC_SUB_UMBRELLA\n";
9274 outs() << " cmdsize " << sub.cmdsize;
9275 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9276 outs() << " Incorrect size\n";
9277 else
9278 outs() << "\n";
9279 if (sub.sub_umbrella < sub.cmdsize) {
9280 const char *P = Ptr + sub.sub_umbrella;
9281 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9282 } else {
9283 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9284 }
9285}
9286
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009287static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009288 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009289 outs() << " cmd LC_SUB_LIBRARY\n";
9290 outs() << " cmdsize " << sub.cmdsize;
9291 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9292 outs() << " Incorrect size\n";
9293 else
9294 outs() << "\n";
9295 if (sub.sub_library < sub.cmdsize) {
9296 const char *P = Ptr + sub.sub_library;
9297 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9298 } else {
9299 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9300 }
9301}
9302
Kevin Enderby186eac32014-12-19 21:06:24 +00009303static void PrintSubClientCommand(MachO::sub_client_command sub,
9304 const char *Ptr) {
9305 outs() << " cmd LC_SUB_CLIENT\n";
9306 outs() << " cmdsize " << sub.cmdsize;
9307 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9308 outs() << " Incorrect size\n";
9309 else
9310 outs() << "\n";
9311 if (sub.client < sub.cmdsize) {
9312 const char *P = Ptr + sub.client;
9313 outs() << " client " << P << " (offset " << sub.client << ")\n";
9314 } else {
9315 outs() << " client ?(bad offset " << sub.client << ")\n";
9316 }
9317}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009318
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009319static void PrintRoutinesCommand(MachO::routines_command r) {
9320 outs() << " cmd LC_ROUTINES\n";
9321 outs() << " cmdsize " << r.cmdsize;
9322 if (r.cmdsize != sizeof(struct MachO::routines_command))
9323 outs() << " Incorrect size\n";
9324 else
9325 outs() << "\n";
9326 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9327 outs() << " init_module " << r.init_module << "\n";
9328 outs() << " reserved1 " << r.reserved1 << "\n";
9329 outs() << " reserved2 " << r.reserved2 << "\n";
9330 outs() << " reserved3 " << r.reserved3 << "\n";
9331 outs() << " reserved4 " << r.reserved4 << "\n";
9332 outs() << " reserved5 " << r.reserved5 << "\n";
9333 outs() << " reserved6 " << r.reserved6 << "\n";
9334}
9335
9336static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9337 outs() << " cmd LC_ROUTINES_64\n";
9338 outs() << " cmdsize " << r.cmdsize;
9339 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9340 outs() << " Incorrect size\n";
9341 else
9342 outs() << "\n";
9343 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9344 outs() << " init_module " << r.init_module << "\n";
9345 outs() << " reserved1 " << r.reserved1 << "\n";
9346 outs() << " reserved2 " << r.reserved2 << "\n";
9347 outs() << " reserved3 " << r.reserved3 << "\n";
9348 outs() << " reserved4 " << r.reserved4 << "\n";
9349 outs() << " reserved5 " << r.reserved5 << "\n";
9350 outs() << " reserved6 " << r.reserved6 << "\n";
9351}
9352
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009353static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9354 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9355 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9356 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9357 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9358 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9359 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9360 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9361 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9362 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9363 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9364 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9365 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9366 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9367 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9368 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9369 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9370}
9371
Kevin Enderby48ef5342014-12-23 22:56:39 +00009372static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9373 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9374 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9375 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9376 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9377 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9378 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9379 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9380 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9381 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9382 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9383 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9384 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9385 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9386 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9387 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9388 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9389 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9390 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9391 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9392 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9393 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9394}
9395
Kevin Enderby227df342014-12-23 23:43:59 +00009396static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009397 uint32_t f;
9398 outs() << "\t mmst_reg ";
9399 for (f = 0; f < 10; f++)
9400 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9401 outs() << "\n";
9402 outs() << "\t mmst_rsrv ";
9403 for (f = 0; f < 6; f++)
9404 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9405 outs() << "\n";
9406}
9407
Kevin Enderbyaefb0032014-12-24 00:16:51 +00009408static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009409 uint32_t f;
9410 outs() << "\t xmm_reg ";
9411 for (f = 0; f < 16; f++)
9412 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9413 outs() << "\n";
9414}
9415
9416static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9417 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9418 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9419 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9420 outs() << " denorm " << fpu.fpu_fcw.denorm;
9421 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9422 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9423 outs() << " undfl " << fpu.fpu_fcw.undfl;
9424 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9425 outs() << "\t\t pc ";
9426 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9427 outs() << "FP_PREC_24B ";
9428 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9429 outs() << "FP_PREC_53B ";
9430 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9431 outs() << "FP_PREC_64B ";
9432 else
9433 outs() << fpu.fpu_fcw.pc << " ";
9434 outs() << "rc ";
9435 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9436 outs() << "FP_RND_NEAR ";
9437 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9438 outs() << "FP_RND_DOWN ";
9439 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9440 outs() << "FP_RND_UP ";
9441 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009442 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009443 outs() << "\n";
9444 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9445 outs() << " denorm " << fpu.fpu_fsw.denorm;
9446 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9447 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9448 outs() << " undfl " << fpu.fpu_fsw.undfl;
9449 outs() << " precis " << fpu.fpu_fsw.precis;
9450 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9451 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9452 outs() << " c0 " << fpu.fpu_fsw.c0;
9453 outs() << " c1 " << fpu.fpu_fsw.c1;
9454 outs() << " c2 " << fpu.fpu_fsw.c2;
9455 outs() << " tos " << fpu.fpu_fsw.tos;
9456 outs() << " c3 " << fpu.fpu_fsw.c3;
9457 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9458 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9459 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9460 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9461 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9462 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9463 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9464 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9465 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9466 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9467 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9468 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9469 outs() << "\n";
9470 outs() << "\t fpu_stmm0:\n";
9471 Print_mmst_reg(fpu.fpu_stmm0);
9472 outs() << "\t fpu_stmm1:\n";
9473 Print_mmst_reg(fpu.fpu_stmm1);
9474 outs() << "\t fpu_stmm2:\n";
9475 Print_mmst_reg(fpu.fpu_stmm2);
9476 outs() << "\t fpu_stmm3:\n";
9477 Print_mmst_reg(fpu.fpu_stmm3);
9478 outs() << "\t fpu_stmm4:\n";
9479 Print_mmst_reg(fpu.fpu_stmm4);
9480 outs() << "\t fpu_stmm5:\n";
9481 Print_mmst_reg(fpu.fpu_stmm5);
9482 outs() << "\t fpu_stmm6:\n";
9483 Print_mmst_reg(fpu.fpu_stmm6);
9484 outs() << "\t fpu_stmm7:\n";
9485 Print_mmst_reg(fpu.fpu_stmm7);
9486 outs() << "\t fpu_xmm0:\n";
9487 Print_xmm_reg(fpu.fpu_xmm0);
9488 outs() << "\t fpu_xmm1:\n";
9489 Print_xmm_reg(fpu.fpu_xmm1);
9490 outs() << "\t fpu_xmm2:\n";
9491 Print_xmm_reg(fpu.fpu_xmm2);
9492 outs() << "\t fpu_xmm3:\n";
9493 Print_xmm_reg(fpu.fpu_xmm3);
9494 outs() << "\t fpu_xmm4:\n";
9495 Print_xmm_reg(fpu.fpu_xmm4);
9496 outs() << "\t fpu_xmm5:\n";
9497 Print_xmm_reg(fpu.fpu_xmm5);
9498 outs() << "\t fpu_xmm6:\n";
9499 Print_xmm_reg(fpu.fpu_xmm6);
9500 outs() << "\t fpu_xmm7:\n";
9501 Print_xmm_reg(fpu.fpu_xmm7);
9502 outs() << "\t fpu_xmm8:\n";
9503 Print_xmm_reg(fpu.fpu_xmm8);
9504 outs() << "\t fpu_xmm9:\n";
9505 Print_xmm_reg(fpu.fpu_xmm9);
9506 outs() << "\t fpu_xmm10:\n";
9507 Print_xmm_reg(fpu.fpu_xmm10);
9508 outs() << "\t fpu_xmm11:\n";
9509 Print_xmm_reg(fpu.fpu_xmm11);
9510 outs() << "\t fpu_xmm12:\n";
9511 Print_xmm_reg(fpu.fpu_xmm12);
9512 outs() << "\t fpu_xmm13:\n";
9513 Print_xmm_reg(fpu.fpu_xmm13);
9514 outs() << "\t fpu_xmm14:\n";
9515 Print_xmm_reg(fpu.fpu_xmm14);
9516 outs() << "\t fpu_xmm15:\n";
9517 Print_xmm_reg(fpu.fpu_xmm15);
9518 outs() << "\t fpu_rsrv4:\n";
9519 for (uint32_t f = 0; f < 6; f++) {
9520 outs() << "\t ";
9521 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009522 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009523 outs() << "\n";
9524 }
9525 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9526 outs() << "\n";
9527}
9528
9529static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9530 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9531 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9532 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9533}
9534
Kevin Enderby41c9c002016-10-21 18:22:35 +00009535static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9536 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9537 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9538 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9539 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9540 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9541 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9542 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9543 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9544 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9545 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9546 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9547 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9548 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9549 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9550 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9551 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9552 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9553}
9554
Kevin Enderby7747cb52016-11-03 20:51:28 +00009555static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9556 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9557 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9558 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9559 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9560 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9561 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9562 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9563 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9564 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9565 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9566 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9567 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9568 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9569 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9570 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9571 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9572 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9573 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9574 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9575 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9576 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9577 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9578 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9579 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9580 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9581 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9582 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9583 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9584 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9585 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9586 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9587 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9588 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9589 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9590}
9591
Kevin Enderby48ef5342014-12-23 22:56:39 +00009592static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9593 bool isLittleEndian, uint32_t cputype) {
9594 if (t.cmd == MachO::LC_THREAD)
9595 outs() << " cmd LC_THREAD\n";
9596 else if (t.cmd == MachO::LC_UNIXTHREAD)
9597 outs() << " cmd LC_UNIXTHREAD\n";
9598 else
9599 outs() << " cmd " << t.cmd << " (unknown)\n";
9600 outs() << " cmdsize " << t.cmdsize;
9601 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9602 outs() << " Incorrect size\n";
9603 else
9604 outs() << "\n";
9605
9606 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9607 const char *end = Ptr + t.cmdsize;
9608 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009609 if (cputype == MachO::CPU_TYPE_I386) {
9610 while (begin < end) {
9611 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9612 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9613 begin += sizeof(uint32_t);
9614 } else {
9615 flavor = 0;
9616 begin = end;
9617 }
9618 if (isLittleEndian != sys::IsLittleEndianHost)
9619 sys::swapByteOrder(flavor);
9620 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9621 memcpy((char *)&count, begin, sizeof(uint32_t));
9622 begin += sizeof(uint32_t);
9623 } else {
9624 count = 0;
9625 begin = end;
9626 }
9627 if (isLittleEndian != sys::IsLittleEndianHost)
9628 sys::swapByteOrder(count);
9629 if (flavor == MachO::x86_THREAD_STATE32) {
9630 outs() << " flavor i386_THREAD_STATE\n";
9631 if (count == MachO::x86_THREAD_STATE32_COUNT)
9632 outs() << " count i386_THREAD_STATE_COUNT\n";
9633 else
9634 outs() << " count " << count
9635 << " (not x86_THREAD_STATE32_COUNT)\n";
9636 MachO::x86_thread_state32_t cpu32;
9637 left = end - begin;
9638 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9639 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9640 begin += sizeof(MachO::x86_thread_state32_t);
9641 } else {
9642 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9643 memcpy(&cpu32, begin, left);
9644 begin += left;
9645 }
9646 if (isLittleEndian != sys::IsLittleEndianHost)
9647 swapStruct(cpu32);
9648 Print_x86_thread_state32_t(cpu32);
9649 } else if (flavor == MachO::x86_THREAD_STATE) {
9650 outs() << " flavor x86_THREAD_STATE\n";
9651 if (count == MachO::x86_THREAD_STATE_COUNT)
9652 outs() << " count x86_THREAD_STATE_COUNT\n";
9653 else
9654 outs() << " count " << count
9655 << " (not x86_THREAD_STATE_COUNT)\n";
9656 struct MachO::x86_thread_state_t ts;
9657 left = end - begin;
9658 if (left >= sizeof(MachO::x86_thread_state_t)) {
9659 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9660 begin += sizeof(MachO::x86_thread_state_t);
9661 } else {
9662 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9663 memcpy(&ts, begin, left);
9664 begin += left;
9665 }
9666 if (isLittleEndian != sys::IsLittleEndianHost)
9667 swapStruct(ts);
9668 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9669 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9670 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9671 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9672 else
9673 outs() << "tsh.count " << ts.tsh.count
9674 << " (not x86_THREAD_STATE32_COUNT\n";
9675 Print_x86_thread_state32_t(ts.uts.ts32);
9676 } else {
9677 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9678 << ts.tsh.count << "\n";
9679 }
9680 } else {
9681 outs() << " flavor " << flavor << " (unknown)\n";
9682 outs() << " count " << count << "\n";
9683 outs() << " state (unknown)\n";
9684 begin += count * sizeof(uint32_t);
9685 }
9686 }
9687 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009688 while (begin < end) {
9689 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9690 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9691 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009692 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009693 flavor = 0;
9694 begin = end;
9695 }
9696 if (isLittleEndian != sys::IsLittleEndianHost)
9697 sys::swapByteOrder(flavor);
9698 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9699 memcpy((char *)&count, begin, sizeof(uint32_t));
9700 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009701 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009702 count = 0;
9703 begin = end;
9704 }
9705 if (isLittleEndian != sys::IsLittleEndianHost)
9706 sys::swapByteOrder(count);
9707 if (flavor == MachO::x86_THREAD_STATE64) {
9708 outs() << " flavor x86_THREAD_STATE64\n";
9709 if (count == MachO::x86_THREAD_STATE64_COUNT)
9710 outs() << " count x86_THREAD_STATE64_COUNT\n";
9711 else
9712 outs() << " count " << count
9713 << " (not x86_THREAD_STATE64_COUNT)\n";
9714 MachO::x86_thread_state64_t cpu64;
9715 left = end - begin;
9716 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9717 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9718 begin += sizeof(MachO::x86_thread_state64_t);
9719 } else {
9720 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9721 memcpy(&cpu64, begin, left);
9722 begin += left;
9723 }
9724 if (isLittleEndian != sys::IsLittleEndianHost)
9725 swapStruct(cpu64);
9726 Print_x86_thread_state64_t(cpu64);
9727 } else if (flavor == MachO::x86_THREAD_STATE) {
9728 outs() << " flavor x86_THREAD_STATE\n";
9729 if (count == MachO::x86_THREAD_STATE_COUNT)
9730 outs() << " count x86_THREAD_STATE_COUNT\n";
9731 else
9732 outs() << " count " << count
9733 << " (not x86_THREAD_STATE_COUNT)\n";
9734 struct MachO::x86_thread_state_t ts;
9735 left = end - begin;
9736 if (left >= sizeof(MachO::x86_thread_state_t)) {
9737 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9738 begin += sizeof(MachO::x86_thread_state_t);
9739 } else {
9740 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9741 memcpy(&ts, begin, left);
9742 begin += left;
9743 }
9744 if (isLittleEndian != sys::IsLittleEndianHost)
9745 swapStruct(ts);
9746 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9747 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9748 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9749 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9750 else
9751 outs() << "tsh.count " << ts.tsh.count
9752 << " (not x86_THREAD_STATE64_COUNT\n";
9753 Print_x86_thread_state64_t(ts.uts.ts64);
9754 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009755 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9756 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009757 }
9758 } else if (flavor == MachO::x86_FLOAT_STATE) {
9759 outs() << " flavor x86_FLOAT_STATE\n";
9760 if (count == MachO::x86_FLOAT_STATE_COUNT)
9761 outs() << " count x86_FLOAT_STATE_COUNT\n";
9762 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009763 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009764 struct MachO::x86_float_state_t fs;
9765 left = end - begin;
9766 if (left >= sizeof(MachO::x86_float_state_t)) {
9767 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9768 begin += sizeof(MachO::x86_float_state_t);
9769 } else {
9770 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9771 memcpy(&fs, begin, left);
9772 begin += left;
9773 }
9774 if (isLittleEndian != sys::IsLittleEndianHost)
9775 swapStruct(fs);
9776 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9777 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009778 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009779 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9780 else
9781 outs() << "fsh.count " << fs.fsh.count
9782 << " (not x86_FLOAT_STATE64_COUNT\n";
9783 Print_x86_float_state_t(fs.ufs.fs64);
9784 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009785 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9786 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009787 }
9788 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9789 outs() << " flavor x86_EXCEPTION_STATE\n";
9790 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9791 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9792 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009793 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009794 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9795 struct MachO::x86_exception_state_t es;
9796 left = end - begin;
9797 if (left >= sizeof(MachO::x86_exception_state_t)) {
9798 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9799 begin += sizeof(MachO::x86_exception_state_t);
9800 } else {
9801 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9802 memcpy(&es, begin, left);
9803 begin += left;
9804 }
9805 if (isLittleEndian != sys::IsLittleEndianHost)
9806 swapStruct(es);
9807 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9808 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009809 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009810 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9811 else
9812 outs() << "\t esh.count " << es.esh.count
9813 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9814 Print_x86_exception_state_t(es.ues.es64);
9815 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009816 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9817 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009818 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009819 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9820 outs() << " flavor x86_EXCEPTION_STATE64\n";
9821 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9822 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9823 else
9824 outs() << " count " << count
9825 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9826 struct MachO::x86_exception_state64_t es64;
9827 left = end - begin;
9828 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9829 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9830 begin += sizeof(MachO::x86_exception_state64_t);
9831 } else {
9832 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9833 memcpy(&es64, begin, left);
9834 begin += left;
9835 }
9836 if (isLittleEndian != sys::IsLittleEndianHost)
9837 swapStruct(es64);
9838 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009839 } else {
9840 outs() << " flavor " << flavor << " (unknown)\n";
9841 outs() << " count " << count << "\n";
9842 outs() << " state (unknown)\n";
9843 begin += count * sizeof(uint32_t);
9844 }
9845 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009846 } else if (cputype == MachO::CPU_TYPE_ARM) {
9847 while (begin < end) {
9848 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9849 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9850 begin += sizeof(uint32_t);
9851 } else {
9852 flavor = 0;
9853 begin = end;
9854 }
9855 if (isLittleEndian != sys::IsLittleEndianHost)
9856 sys::swapByteOrder(flavor);
9857 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9858 memcpy((char *)&count, begin, sizeof(uint32_t));
9859 begin += sizeof(uint32_t);
9860 } else {
9861 count = 0;
9862 begin = end;
9863 }
9864 if (isLittleEndian != sys::IsLittleEndianHost)
9865 sys::swapByteOrder(count);
9866 if (flavor == MachO::ARM_THREAD_STATE) {
9867 outs() << " flavor ARM_THREAD_STATE\n";
9868 if (count == MachO::ARM_THREAD_STATE_COUNT)
9869 outs() << " count ARM_THREAD_STATE_COUNT\n";
9870 else
9871 outs() << " count " << count
9872 << " (not ARM_THREAD_STATE_COUNT)\n";
9873 MachO::arm_thread_state32_t cpu32;
9874 left = end - begin;
9875 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9876 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9877 begin += sizeof(MachO::arm_thread_state32_t);
9878 } else {
9879 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9880 memcpy(&cpu32, begin, left);
9881 begin += left;
9882 }
9883 if (isLittleEndian != sys::IsLittleEndianHost)
9884 swapStruct(cpu32);
9885 Print_arm_thread_state32_t(cpu32);
9886 } else {
9887 outs() << " flavor " << flavor << " (unknown)\n";
9888 outs() << " count " << count << "\n";
9889 outs() << " state (unknown)\n";
9890 begin += count * sizeof(uint32_t);
9891 }
9892 }
Tim Northoverff6875a2019-05-14 11:25:44 +00009893 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9894 cputype == MachO::CPU_TYPE_ARM64_32) {
Kevin Enderby7747cb52016-11-03 20:51:28 +00009895 while (begin < end) {
9896 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9897 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9898 begin += sizeof(uint32_t);
9899 } else {
9900 flavor = 0;
9901 begin = end;
9902 }
9903 if (isLittleEndian != sys::IsLittleEndianHost)
9904 sys::swapByteOrder(flavor);
9905 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9906 memcpy((char *)&count, begin, sizeof(uint32_t));
9907 begin += sizeof(uint32_t);
9908 } else {
9909 count = 0;
9910 begin = end;
9911 }
9912 if (isLittleEndian != sys::IsLittleEndianHost)
9913 sys::swapByteOrder(count);
9914 if (flavor == MachO::ARM_THREAD_STATE64) {
9915 outs() << " flavor ARM_THREAD_STATE64\n";
9916 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9917 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9918 else
9919 outs() << " count " << count
9920 << " (not ARM_THREAD_STATE64_COUNT)\n";
9921 MachO::arm_thread_state64_t cpu64;
9922 left = end - begin;
9923 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9924 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9925 begin += sizeof(MachO::arm_thread_state64_t);
9926 } else {
9927 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9928 memcpy(&cpu64, begin, left);
9929 begin += left;
9930 }
9931 if (isLittleEndian != sys::IsLittleEndianHost)
9932 swapStruct(cpu64);
9933 Print_arm_thread_state64_t(cpu64);
9934 } else {
9935 outs() << " flavor " << flavor << " (unknown)\n";
9936 outs() << " count " << count << "\n";
9937 outs() << " state (unknown)\n";
9938 begin += count * sizeof(uint32_t);
9939 }
9940 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009941 } else {
9942 while (begin < end) {
9943 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9944 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9945 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009946 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009947 flavor = 0;
9948 begin = end;
9949 }
9950 if (isLittleEndian != sys::IsLittleEndianHost)
9951 sys::swapByteOrder(flavor);
9952 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9953 memcpy((char *)&count, begin, sizeof(uint32_t));
9954 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009955 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009956 count = 0;
9957 begin = end;
9958 }
9959 if (isLittleEndian != sys::IsLittleEndianHost)
9960 sys::swapByteOrder(count);
9961 outs() << " flavor " << flavor << "\n";
9962 outs() << " count " << count << "\n";
9963 outs() << " state (Unknown cputype/cpusubtype)\n";
9964 begin += count * sizeof(uint32_t);
9965 }
9966 }
9967}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009968
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009969static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9970 if (dl.cmd == MachO::LC_ID_DYLIB)
9971 outs() << " cmd LC_ID_DYLIB\n";
9972 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9973 outs() << " cmd LC_LOAD_DYLIB\n";
9974 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9975 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9976 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9977 outs() << " cmd LC_REEXPORT_DYLIB\n";
9978 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9979 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9980 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9981 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9982 else
9983 outs() << " cmd " << dl.cmd << " (unknown)\n";
9984 outs() << " cmdsize " << dl.cmdsize;
9985 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9986 outs() << " Incorrect size\n";
9987 else
9988 outs() << "\n";
9989 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009990 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009991 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9992 } else {
9993 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9994 }
9995 outs() << " time stamp " << dl.dylib.timestamp << " ";
9996 time_t t = dl.dylib.timestamp;
9997 outs() << ctime(&t);
9998 outs() << " current version ";
9999 if (dl.dylib.current_version == 0xffffffff)
10000 outs() << "n/a\n";
10001 else
10002 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10003 << ((dl.dylib.current_version >> 8) & 0xff) << "."
10004 << (dl.dylib.current_version & 0xff) << "\n";
10005 outs() << "compatibility version ";
10006 if (dl.dylib.compatibility_version == 0xffffffff)
10007 outs() << "n/a\n";
10008 else
10009 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10010 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10011 << (dl.dylib.compatibility_version & 0xff) << "\n";
10012}
10013
10014static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10015 uint32_t object_size) {
10016 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +000010017 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +000010018 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10019 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
10020 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10021 outs() << " cmd LC_FUNCTION_STARTS\n";
10022 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10023 outs() << " cmd LC_DATA_IN_CODE\n";
10024 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10025 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
10026 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10027 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
10028 else
10029 outs() << " cmd " << ld.cmd << " (?)\n";
10030 outs() << " cmdsize " << ld.cmdsize;
10031 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10032 outs() << " Incorrect size\n";
10033 else
10034 outs() << "\n";
10035 outs() << " dataoff " << ld.dataoff;
10036 if (ld.dataoff > object_size)
10037 outs() << " (past end of file)\n";
10038 else
10039 outs() << "\n";
10040 outs() << " datasize " << ld.datasize;
10041 uint64_t big_size = ld.dataoff;
10042 big_size += ld.datasize;
10043 if (big_size > object_size)
10044 outs() << " (past end of file)\n";
10045 else
10046 outs() << "\n";
10047}
10048
Alexey Samsonovd319c4f2015-06-03 22:19:36 +000010049static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10050 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +000010051 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +000010052 unsigned Index = 0;
10053 for (const auto &Command : Obj->load_commands()) {
10054 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +000010055 if (Command.C.cmd == MachO::LC_SEGMENT) {
10056 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10057 const char *sg_segname = SLC.segname;
10058 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10059 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10060 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10061 verbose);
10062 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +000010063 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +000010064 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10065 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10066 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10067 }
10068 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10069 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10070 const char *sg_segname = SLC_64.segname;
10071 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10072 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10073 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10074 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10075 for (unsigned j = 0; j < SLC_64.nsects; j++) {
10076 MachO::section_64 S_64 = Obj->getSection64(Command, j);
10077 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10078 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10079 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10080 sg_segname, filetype, Buf.size(), verbose);
10081 }
10082 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10083 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +000010084 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +000010085 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10086 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10087 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +000010088 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10089 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +000010090 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10091 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10092 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10093 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10094 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10095 Command.C.cmd == MachO::LC_ID_DYLINKER ||
10096 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10097 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10098 PrintDyldLoadCommand(Dyld, Command.Ptr);
10099 } else if (Command.C.cmd == MachO::LC_UUID) {
10100 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10101 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +000010102 } else if (Command.C.cmd == MachO::LC_RPATH) {
10103 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10104 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +000010105 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +000010106 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10107 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10108 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +000010109 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10110 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +000010111 } else if (Command.C.cmd == MachO::LC_NOTE) {
10112 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10113 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +000010114 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10115 MachO::build_version_command Bv =
10116 Obj->getBuildVersionLoadCommand(Command);
10117 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +000010118 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10119 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10120 PrintSourceVersionCommand(Sd);
10121 } else if (Command.C.cmd == MachO::LC_MAIN) {
10122 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10123 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +000010124 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +000010125 MachO::encryption_info_command Ei =
10126 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +000010127 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +000010128 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +000010129 MachO::encryption_info_command_64 Ei =
10130 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +000010131 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +000010132 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +000010133 MachO::linker_option_command Lo =
10134 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +000010135 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +000010136 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10137 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10138 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +000010139 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10140 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10141 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +000010142 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10143 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10144 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +000010145 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10146 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10147 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +000010148 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10149 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10150 PrintRoutinesCommand(Rc);
10151 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10152 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10153 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +000010154 } else if (Command.C.cmd == MachO::LC_THREAD ||
10155 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10156 MachO::thread_command Tc = Obj->getThreadCommand(Command);
10157 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +000010158 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10159 Command.C.cmd == MachO::LC_ID_DYLIB ||
10160 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10161 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10162 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10163 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +000010164 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10165 PrintDylibCommand(Dl, Command.Ptr);
10166 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10167 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10168 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10169 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10170 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10171 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10172 MachO::linkedit_data_command Ld =
10173 Obj->getLinkeditDataLoadCommand(Command);
10174 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +000010175 } else {
10176 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10177 << ")\n";
10178 outs() << " cmdsize " << Command.C.cmdsize << "\n";
10179 // TODO: get and print the raw bytes of the load command.
10180 }
10181 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +000010182 }
10183}
10184
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010185static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +000010186 if (Obj->is64Bit()) {
10187 MachO::mach_header_64 H_64;
10188 H_64 = Obj->getHeader64();
10189 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10190 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10191 } else {
10192 MachO::mach_header H;
10193 H = Obj->getHeader();
10194 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10195 H.sizeofcmds, H.flags, verbose);
10196 }
10197}
10198
Fangrui Song523758e2019-04-15 15:31:42 +000010199void printMachOFileHeader(const object::ObjectFile *Obj) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +000010200 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010201 PrintMachHeader(file, !NonVerbose);
10202}
10203
Fangrui Song523758e2019-04-15 15:31:42 +000010204void printMachOLoadCommands(const object::ObjectFile *Obj) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010205 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +000010206 uint32_t filetype = 0;
10207 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010208 if (file->is64Bit()) {
10209 MachO::mach_header_64 H_64;
10210 H_64 = file->getHeader64();
10211 filetype = H_64.filetype;
10212 cputype = H_64.cputype;
10213 } else {
10214 MachO::mach_header H;
10215 H = file->getHeader();
10216 filetype = H.filetype;
10217 cputype = H.cputype;
10218 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +000010219 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +000010220}
Nick Kledzikd04bc352014-08-30 00:20:14 +000010221
10222//===----------------------------------------------------------------------===//
10223// export trie dumping
10224//===----------------------------------------------------------------------===//
10225
Fangrui Song523758e2019-04-15 15:31:42 +000010226void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010227 uint64_t BaseSegmentAddress = 0;
10228 for (const auto &Command : Obj->load_commands()) {
10229 if (Command.C.cmd == MachO::LC_SEGMENT) {
10230 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10231 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10232 BaseSegmentAddress = Seg.vmaddr;
10233 break;
10234 }
10235 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10236 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10237 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10238 BaseSegmentAddress = Seg.vmaddr;
10239 break;
10240 }
10241 }
10242 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010243 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010244 for (const object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010245 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010246 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10247 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10248 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10249 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10250 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10251 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10252 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10253 if (ReExport)
10254 outs() << "[re-export] ";
10255 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010256 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010257 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010258 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010259 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010260 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +000010261 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010262 if (WeakDef) {
10263 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010264 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010265 }
10266 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010267 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010268 outs() << ", ";
10269 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010270 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010271 }
10272 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010273 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010274 outs() << ", ";
10275 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010276 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010277 }
10278 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010279 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010280 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010281 outs() << format("resolver=0x%08llX", Entry.other());
10282 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010283 }
10284 outs() << "]";
10285 }
10286 if (ReExport) {
10287 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010288 int Ordinal = Entry.other() - 1;
10289 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10290 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +000010291 outs() << " (from " << DylibName << ")";
10292 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010293 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010294 }
10295 outs() << "\n";
10296 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010297 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +000010298 reportError(std::move(Err), Obj->getFileName());
Nick Kledzikd04bc352014-08-30 00:20:14 +000010299}
Nick Kledzikac431442014-09-12 21:34:15 +000010300
Nick Kledzikac431442014-09-12 21:34:15 +000010301//===----------------------------------------------------------------------===//
10302// rebase table dumping
10303//===----------------------------------------------------------------------===//
10304
Fangrui Song523758e2019-04-15 15:31:42 +000010305void printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +000010306 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010307 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010308 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010309 StringRef SegmentName = Entry.segmentName();
10310 StringRef SectionName = Entry.sectionName();
10311 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +000010312
10313 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010314 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10315 SegmentName.str().c_str(), SectionName.str().c_str(),
10316 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +000010317 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010318 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +000010319 reportError(std::move(Err), Obj->getFileName());
Nick Kledzikac431442014-09-12 21:34:15 +000010320}
Nick Kledzik56ebef42014-09-16 01:41:51 +000010321
10322static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10323 StringRef DylibName;
10324 switch (Ordinal) {
10325 case MachO::BIND_SPECIAL_DYLIB_SELF:
10326 return "this-image";
10327 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10328 return "main-executable";
10329 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10330 return "flat-namespace";
10331 default:
Nick Kledzikabd29872014-09-16 22:03:13 +000010332 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010333 std::error_code EC =
10334 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +000010335 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +000010336 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +000010337 return DylibName;
10338 }
Nick Kledzik56ebef42014-09-16 01:41:51 +000010339 }
Nick Kledzikabd29872014-09-16 22:03:13 +000010340 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010341}
10342
10343//===----------------------------------------------------------------------===//
10344// bind table dumping
10345//===----------------------------------------------------------------------===//
10346
Fangrui Song523758e2019-04-15 15:31:42 +000010347void printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010348 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010349 outs() << "segment section address type "
10350 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010351 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010352 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010353 StringRef SegmentName = Entry.segmentName();
10354 StringRef SectionName = Entry.sectionName();
10355 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010356
10357 // Table lines look like:
10358 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010359 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +000010360 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010361 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010362 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010363 << left_justify(SectionName, 18) << " "
10364 << format_hex(Address, 10, true) << " "
10365 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010366 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010367 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010368 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010369 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010370 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +000010371 reportError(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010372}
10373
10374//===----------------------------------------------------------------------===//
10375// lazy bind table dumping
10376//===----------------------------------------------------------------------===//
10377
Fangrui Song523758e2019-04-15 15:31:42 +000010378void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010379 outs() << "segment section address "
10380 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010381 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010382 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010383 StringRef SegmentName = Entry.segmentName();
10384 StringRef SectionName = Entry.sectionName();
10385 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010386
10387 // Table lines look like:
10388 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010389 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010390 << left_justify(SectionName, 18) << " "
10391 << format_hex(Address, 10, true) << " "
10392 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010393 << Entry.symbolName() << "\n";
10394 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010395 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +000010396 reportError(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010397}
10398
Nick Kledzik56ebef42014-09-16 01:41:51 +000010399//===----------------------------------------------------------------------===//
10400// weak bind table dumping
10401//===----------------------------------------------------------------------===//
10402
Fangrui Song523758e2019-04-15 15:31:42 +000010403void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010404 outs() << "segment section address "
10405 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010406 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010407 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010408 // Strong symbols don't have a location to update.
10409 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010410 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010411 << Entry.symbolName() << "\n";
10412 continue;
10413 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010414 StringRef SegmentName = Entry.segmentName();
10415 StringRef SectionName = Entry.sectionName();
10416 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010417
10418 // Table lines look like:
10419 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010420 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010421 << left_justify(SectionName, 18) << " "
10422 << format_hex(Address, 10, true) << " "
10423 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010424 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10425 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010426 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010427 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +000010428 reportError(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010429}
10430
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010431// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10432// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10433// information for that address. If the address is found its binding symbol
10434// name is returned. If not nullptr is returned.
10435static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10436 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010437 if (info->bindtable == nullptr) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +000010438 info->bindtable = std::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010439 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010440 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010441 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010442 StringRef name = Entry.symbolName();
10443 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010444 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010445 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010446 if (Err)
George Rimarf0f38d92019-08-21 11:07:31 +000010447 reportError(std::move(Err), info->O->getFileName());
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010448 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010449 auto name = info->bindtable->lookup(ReferenceValue);
10450 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010451}
Michael Trent1854ecc2017-12-05 07:50:00 +000010452
Fangrui Song523758e2019-04-15 15:31:42 +000010453void printLazyBindTable(ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010454 outs() << "Lazy bind table:\n";
10455 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10456 printMachOLazyBindTable(MachO);
10457 else
10458 WithColor::error()
10459 << "This operation is only currently supported "
10460 "for Mach-O executable files.\n";
10461}
10462
Fangrui Song523758e2019-04-15 15:31:42 +000010463void printWeakBindTable(ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010464 outs() << "Weak bind table:\n";
10465 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10466 printMachOWeakBindTable(MachO);
10467 else
10468 WithColor::error()
10469 << "This operation is only currently supported "
10470 "for Mach-O executable files.\n";
10471}
10472
Fangrui Song523758e2019-04-15 15:31:42 +000010473void printExportsTrie(const ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010474 outs() << "Exports trie:\n";
10475 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10476 printMachOExportsTrie(MachO);
10477 else
10478 WithColor::error()
10479 << "This operation is only currently supported "
10480 "for Mach-O executable files.\n";
10481}
10482
Fangrui Song523758e2019-04-15 15:31:42 +000010483void printRebaseTable(ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010484 outs() << "Rebase table:\n";
10485 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10486 printMachORebaseTable(MachO);
10487 else
10488 WithColor::error()
10489 << "This operation is only currently supported "
10490 "for Mach-O executable files.\n";
10491}
10492
Fangrui Song523758e2019-04-15 15:31:42 +000010493void printBindTable(ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010494 outs() << "Bind table:\n";
10495 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10496 printMachOBindTable(MachO);
10497 else
10498 WithColor::error()
10499 << "This operation is only currently supported "
10500 "for Mach-O executable files.\n";
10501}
Fangrui Song523758e2019-04-15 15:31:42 +000010502} // namespace llvm