blob: 7c8dcb2af4da26243b558d315e351c4467913502 [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000015#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000016#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000017#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ADT/Triple.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000019#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000020#include "llvm/DebugInfo/DWARF/DIContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000021#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000022#include "llvm/MC/MCContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCDisassembler.h"
24#include "llvm/MC/MCInst.h"
25#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#include "llvm/MC/MCInstrDesc.h"
27#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000028#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000030#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000031#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000032#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000035#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000036#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000037#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000039#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/TargetSelect.h"
44#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000045#include <algorithm>
46#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000047#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000048
49#if HAVE_CXXABI_H
50#include <cxxabi.h>
51#endif
52
Benjamin Kramer43a772e2011-09-19 17:56:04 +000053using namespace llvm;
54using namespace object;
55
56static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000057 UseDbg("g",
58 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000059
Kevin Enderbyb28ed012014-10-29 21:28:24 +000060static cl::opt<std::string> DSYMFile("dsym",
61 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000062
Kevin Enderbyb28ed012014-10-29 21:28:24 +000063static cl::opt<bool> FullLeadingAddr("full-leading-addr",
64 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000065
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000066static cl::opt<bool> NoLeadingAddr("no-leading-addr",
67 cl::desc("Print no leading address"));
68
Kevin Enderbybf246f52014-09-24 23:08:22 +000069static cl::opt<bool>
70 PrintImmHex("print-imm-hex",
71 cl::desc("Use hex format for immediate values"));
72
Kevin Enderby13023a12015-01-15 23:19:11 +000073cl::opt<bool> llvm::UniversalHeaders("universal-headers",
74 cl::desc("Print Mach-O universal headers "
75 "(requires -macho)"));
76
Kevin Enderby131d1772015-01-09 19:22:37 +000077cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000078 llvm::ArchiveHeaders("archive-headers",
79 cl::desc("Print archive headers for Mach-O archives "
80 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000081
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000082cl::opt<bool>
83 llvm::IndirectSymbols("indirect-symbols",
84 cl::desc("Print indirect symbol table for Mach-O "
85 "objects (requires -macho)"));
86
Kevin Enderby69fe98d2015-01-23 18:52:17 +000087cl::opt<bool>
88 llvm::DataInCode("data-in-code",
89 cl::desc("Print the data in code table for Mach-O objects "
90 "(requires -macho)"));
91
Kevin Enderby9a509442015-01-27 21:28:24 +000092cl::opt<bool>
93 llvm::LinkOptHints("link-opt-hints",
94 cl::desc("Print the linker optimization hints for "
95 "Mach-O objects (requires -macho)"));
96
Kevin Enderbyf6d25852015-01-31 00:37:11 +000097cl::list<std::string>
98 llvm::DumpSections("section",
99 cl::desc("Prints the specified segment,section for "
100 "Mach-O objects (requires -macho)"));
101
Adrian Prantlc2401dd2015-03-27 17:31:15 +0000102cl::opt<bool> llvm::Raw("raw",
103 cl::desc("Have -section dump the raw binary contents"));
104
Kevin Enderbycd66be52015-03-11 22:06:32 +0000105cl::opt<bool>
106 llvm::InfoPlist("info-plist",
107 cl::desc("Print the info plist section as strings for "
108 "Mach-O objects (requires -macho)"));
109
Kevin Enderbyf0640752015-03-13 17:56:32 +0000110cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000111 llvm::DylibsUsed("dylibs-used",
112 cl::desc("Print the shared libraries used for linked "
113 "Mach-O files (requires -macho)"));
114
115cl::opt<bool>
116 llvm::DylibId("dylib-id",
117 cl::desc("Print the shared library's id for the dylib Mach-O "
118 "file (requires -macho)"));
119
120cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000121 llvm::NonVerbose("non-verbose",
122 cl::desc("Print the info for Mach-O objects in "
123 "non-verbose or numeric form (requires -macho)"));
124
Kevin Enderby0fc11822015-04-01 20:57:01 +0000125cl::opt<bool>
126 llvm::ObjcMetaData("objc-meta-data",
127 cl::desc("Print the Objective-C runtime meta data for "
128 "Mach-O files (requires -macho)"));
129
Kevin Enderby6a221752015-03-17 17:10:57 +0000130cl::opt<std::string> llvm::DisSymName(
131 "dis-symname",
132 cl::desc("disassemble just this symbol's instructions (requires -macho"));
133
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000134static cl::opt<bool> NoSymbolicOperands(
135 "no-symbolic-operands",
136 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
137
138
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000139static cl::list<std::string>
140 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
141 cl::ZeroOrMore);
142bool ArchAll = false;
143
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000144static std::string ThumbTripleName;
145
146static const Target *GetTarget(const MachOObjectFile *MachOObj,
147 const char **McpuDefault,
148 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000149 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000150 if (TripleName.empty()) {
151 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000152 llvm::Triple ThumbTriple = Triple();
153 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000154 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000155 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000156 }
157
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000158 // Get the target specific parser.
159 std::string Error;
160 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000161 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000162 return TheTarget;
163
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000164 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
165 if (*ThumbTarget)
166 return TheTarget;
167
168 errs() << "llvm-objdump: error: unable to get target for '";
169 if (!TheTarget)
170 errs() << TripleName;
171 else
172 errs() << ThumbTripleName;
173 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000174 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000175}
176
Owen Andersond9243c42011-10-17 21:37:35 +0000177struct SymbolSorter {
178 bool operator()(const SymbolRef &A, const SymbolRef &B) {
179 SymbolRef::Type AType, BType;
180 A.getType(AType);
181 B.getType(BType);
182
183 uint64_t AAddr, BAddr;
184 if (AType != SymbolRef::ST_Function)
185 AAddr = 0;
186 else
187 A.getAddress(AAddr);
188 if (BType != SymbolRef::ST_Function)
189 BAddr = 0;
190 else
191 B.getAddress(BAddr);
192 return AAddr < BAddr;
193 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000194};
195
Kevin Enderby273ae012013-06-06 17:20:50 +0000196// Types for the storted data in code table that is built before disassembly
197// and the predicate function to sort them.
198typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
199typedef std::vector<DiceTableEntry> DiceTable;
200typedef DiceTable::iterator dice_table_iterator;
201
Kevin Enderby930fdc72014-11-06 19:00:13 +0000202// This is used to search for a data in code table entry for the PC being
203// disassembled. The j parameter has the PC in j.first. A single data in code
204// table entry can cover many bytes for each of its Kind's. So if the offset,
205// aka the i.first value, of the data in code table entry plus its Length
206// covers the PC being searched for this will return true. If not it will
207// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000208static bool compareDiceTableEntries(const DiceTableEntry &i,
209 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000210 uint16_t Length;
211 i.second.getLength(Length);
212
213 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000214}
215
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000216static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000217 unsigned short Kind) {
218 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000219
220 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000221 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000222 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000223 if (Length >= 4) {
224 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000225 DumpBytes(ArrayRef<uint8_t>(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000226 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000227 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000228 Size = 4;
229 } else if (Length >= 2) {
230 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000231 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000232 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000233 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000234 Size = 2;
235 } else {
236 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000237 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
Kevin Enderby273ae012013-06-06 17:20:50 +0000238 Value = bytes[0];
239 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000240 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000241 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000242 if (Kind == MachO::DICE_KIND_DATA)
243 outs() << "\t@ KIND_DATA\n";
244 else
245 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000246 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000247 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000249 DumpBytes(ArrayRef<uint8_t>(bytes, 1));
Kevin Enderby273ae012013-06-06 17:20:50 +0000250 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000251 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
252 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000253 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000254 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000255 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000256 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000257 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000258 outs() << "\t.short " << format("%5u", Value & 0xffff)
259 << "\t@ KIND_JUMP_TABLE16\n";
260 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000261 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000262 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000263 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
264 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000265 DumpBytes(ArrayRef<uint8_t>(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000266 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 outs() << "\t.long " << Value;
268 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
269 outs() << "\t@ KIND_JUMP_TABLE32\n";
270 else
271 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
272 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000273 break;
274 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000275 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000276}
277
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000278static void getSectionsAndSymbols(const MachO::mach_header Header,
279 MachOObjectFile *MachOObj,
280 std::vector<SectionRef> &Sections,
281 std::vector<SymbolRef> &Symbols,
282 SmallVectorImpl<uint64_t> &FoundFns,
283 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000284 for (const SymbolRef &Symbol : MachOObj->symbols()) {
285 StringRef SymName;
286 Symbol.getName(SymName);
287 if (!SymName.startswith("ltmp"))
288 Symbols.push_back(Symbol);
289 }
Owen Andersond9243c42011-10-17 21:37:35 +0000290
Alexey Samsonov48803e52014-03-13 14:37:36 +0000291 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000292 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000293 Section.getName(SectName);
294 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000295 }
296
Rafael Espindola56f976f2013-04-18 18:08:55 +0000297 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000298 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000299 bool BaseSegmentAddressSet = false;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000300 for (unsigned i = 0;; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000301 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000302 // We found a function starts segment, parse the addresses for later
303 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000304 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000305 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000306
Charles Davis8bdfafd2013-09-01 04:28:48 +0000307 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000308 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
309 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000310 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000311 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000312 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000313 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000314 }
315 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000316
Charles Davis8bdfafd2013-09-01 04:28:48 +0000317 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000318 break;
319 else
320 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000321 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000322}
323
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000324static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
325 uint32_t n, uint32_t count,
326 uint32_t stride, uint64_t addr) {
327 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
328 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
329 if (n > nindirectsyms)
330 outs() << " (entries start past the end of the indirect symbol "
331 "table) (reserved1 field greater than the table size)";
332 else if (n + count > nindirectsyms)
333 outs() << " (entries extends past the end of the indirect symbol "
334 "table)";
335 outs() << "\n";
336 uint32_t cputype = O->getHeader().cputype;
337 if (cputype & MachO::CPU_ARCH_ABI64)
338 outs() << "address index";
339 else
340 outs() << "address index";
341 if (verbose)
342 outs() << " name\n";
343 else
344 outs() << "\n";
345 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
346 if (cputype & MachO::CPU_ARCH_ABI64)
347 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
348 else
349 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
350 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
351 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
352 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
353 outs() << "LOCAL\n";
354 continue;
355 }
356 if (indirect_symbol ==
357 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
358 outs() << "LOCAL ABSOLUTE\n";
359 continue;
360 }
361 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
362 outs() << "ABSOLUTE\n";
363 continue;
364 }
365 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000366 if (verbose) {
367 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
368 if (indirect_symbol < Symtab.nsyms) {
369 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
370 SymbolRef Symbol = *Sym;
371 StringRef SymName;
372 Symbol.getName(SymName);
373 outs() << SymName;
374 } else {
375 outs() << "?";
376 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000377 }
378 outs() << "\n";
379 }
380}
381
382static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
383 uint32_t LoadCommandCount = O->getHeader().ncmds;
384 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
385 for (unsigned I = 0;; ++I) {
386 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
387 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
388 for (unsigned J = 0; J < Seg.nsects; ++J) {
389 MachO::section_64 Sec = O->getSection64(Load, J);
390 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
391 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
392 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
393 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
394 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
395 section_type == MachO::S_SYMBOL_STUBS) {
396 uint32_t stride;
397 if (section_type == MachO::S_SYMBOL_STUBS)
398 stride = Sec.reserved2;
399 else
400 stride = 8;
401 if (stride == 0) {
402 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
403 << Sec.sectname << ") "
404 << "(size of stubs in reserved2 field is zero)\n";
405 continue;
406 }
407 uint32_t count = Sec.size / stride;
408 outs() << "Indirect symbols for (" << Sec.segname << ","
409 << Sec.sectname << ") " << count << " entries";
410 uint32_t n = Sec.reserved1;
411 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
412 }
413 }
414 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
415 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
416 for (unsigned J = 0; J < Seg.nsects; ++J) {
417 MachO::section Sec = O->getSection(Load, J);
418 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
419 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
420 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
421 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
422 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
423 section_type == MachO::S_SYMBOL_STUBS) {
424 uint32_t stride;
425 if (section_type == MachO::S_SYMBOL_STUBS)
426 stride = Sec.reserved2;
427 else
428 stride = 4;
429 if (stride == 0) {
430 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
431 << Sec.sectname << ") "
432 << "(size of stubs in reserved2 field is zero)\n";
433 continue;
434 }
435 uint32_t count = Sec.size / stride;
436 outs() << "Indirect symbols for (" << Sec.segname << ","
437 << Sec.sectname << ") " << count << " entries";
438 uint32_t n = Sec.reserved1;
439 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
440 }
441 }
442 }
443 if (I == LoadCommandCount - 1)
444 break;
445 else
446 Load = O->getNextLoadCommandInfo(Load);
447 }
448}
449
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000450static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
451 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
452 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
453 outs() << "Data in code table (" << nentries << " entries)\n";
454 outs() << "offset length kind\n";
455 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
456 ++DI) {
457 uint32_t Offset;
458 DI->getOffset(Offset);
459 outs() << format("0x%08" PRIx32, Offset) << " ";
460 uint16_t Length;
461 DI->getLength(Length);
462 outs() << format("%6u", Length) << " ";
463 uint16_t Kind;
464 DI->getKind(Kind);
465 if (verbose) {
466 switch (Kind) {
467 case MachO::DICE_KIND_DATA:
468 outs() << "DATA";
469 break;
470 case MachO::DICE_KIND_JUMP_TABLE8:
471 outs() << "JUMP_TABLE8";
472 break;
473 case MachO::DICE_KIND_JUMP_TABLE16:
474 outs() << "JUMP_TABLE16";
475 break;
476 case MachO::DICE_KIND_JUMP_TABLE32:
477 outs() << "JUMP_TABLE32";
478 break;
479 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
480 outs() << "ABS_JUMP_TABLE32";
481 break;
482 default:
483 outs() << format("0x%04" PRIx32, Kind);
484 break;
485 }
486 } else
487 outs() << format("0x%04" PRIx32, Kind);
488 outs() << "\n";
489 }
490}
491
Kevin Enderby9a509442015-01-27 21:28:24 +0000492static void PrintLinkOptHints(MachOObjectFile *O) {
493 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
494 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
495 uint32_t nloh = LohLC.datasize;
496 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
497 for (uint32_t i = 0; i < nloh;) {
498 unsigned n;
499 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
500 i += n;
501 outs() << " identifier " << identifier << " ";
502 if (i >= nloh)
503 return;
504 switch (identifier) {
505 case 1:
506 outs() << "AdrpAdrp\n";
507 break;
508 case 2:
509 outs() << "AdrpLdr\n";
510 break;
511 case 3:
512 outs() << "AdrpAddLdr\n";
513 break;
514 case 4:
515 outs() << "AdrpLdrGotLdr\n";
516 break;
517 case 5:
518 outs() << "AdrpAddStr\n";
519 break;
520 case 6:
521 outs() << "AdrpLdrGotStr\n";
522 break;
523 case 7:
524 outs() << "AdrpAdd\n";
525 break;
526 case 8:
527 outs() << "AdrpLdrGot\n";
528 break;
529 default:
530 outs() << "Unknown identifier value\n";
531 break;
532 }
533 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
534 i += n;
535 outs() << " narguments " << narguments << "\n";
536 if (i >= nloh)
537 return;
538
539 for (uint32_t j = 0; j < narguments; j++) {
540 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
541 i += n;
542 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
543 if (i >= nloh)
544 return;
545 }
546 }
547}
548
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000549static void PrintDylibs(MachOObjectFile *O, bool JustId) {
550 uint32_t LoadCommandCount = O->getHeader().ncmds;
551 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
552 for (unsigned I = 0;; ++I) {
553 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
554 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
555 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
556 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
557 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
558 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
559 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
560 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
561 if (dl.dylib.name < dl.cmdsize) {
562 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
563 if (JustId)
564 outs() << p << "\n";
565 else {
566 outs() << "\t" << p;
567 outs() << " (compatibility version "
568 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
569 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
570 << (dl.dylib.compatibility_version & 0xff) << ",";
571 outs() << " current version "
572 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
573 << ((dl.dylib.current_version >> 8) & 0xff) << "."
574 << (dl.dylib.current_version & 0xff) << ")\n";
575 }
576 } else {
577 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
578 if (Load.C.cmd == MachO::LC_ID_DYLIB)
579 outs() << "LC_ID_DYLIB ";
580 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
581 outs() << "LC_LOAD_DYLIB ";
582 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
583 outs() << "LC_LOAD_WEAK_DYLIB ";
584 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
585 outs() << "LC_LAZY_LOAD_DYLIB ";
586 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
587 outs() << "LC_REEXPORT_DYLIB ";
588 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
589 outs() << "LC_LOAD_UPWARD_DYLIB ";
590 else
591 outs() << "LC_??? ";
592 outs() << "command " << I << "\n";
593 }
594 }
595 if (I == LoadCommandCount - 1)
596 break;
597 else
598 Load = O->getNextLoadCommandInfo(Load);
599 }
600}
601
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000602typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
603
604static void CreateSymbolAddressMap(MachOObjectFile *O,
605 SymbolAddressMap *AddrMap) {
606 // Create a map of symbol addresses to symbol names.
607 for (const SymbolRef &Symbol : O->symbols()) {
608 SymbolRef::Type ST;
609 Symbol.getType(ST);
610 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
611 ST == SymbolRef::ST_Other) {
612 uint64_t Address;
613 Symbol.getAddress(Address);
614 StringRef SymName;
615 Symbol.getName(SymName);
616 (*AddrMap)[Address] = SymName;
617 }
618 }
619}
620
621// GuessSymbolName is passed the address of what might be a symbol and a
622// pointer to the SymbolAddressMap. It returns the name of a symbol
623// with that address or nullptr if no symbol is found with that address.
624static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
625 const char *SymbolName = nullptr;
626 // A DenseMap can't lookup up some values.
627 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
628 StringRef name = AddrMap->lookup(value);
629 if (!name.empty())
630 SymbolName = name.data();
631 }
632 return SymbolName;
633}
634
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000635static void DumpCstringChar(const char c) {
636 char p[2];
637 p[0] = c;
638 p[1] = '\0';
639 outs().write_escaped(p);
640}
641
Kevin Enderby10ba0412015-02-04 21:38:42 +0000642static void DumpCstringSection(MachOObjectFile *O, const char *sect,
643 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000644 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000645 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000646 if (print_addresses) {
647 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000648 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000649 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000650 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000651 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000652 for (; i < sect_size && sect[i] != '\0'; i++)
653 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000654 if (i < sect_size && sect[i] == '\0')
655 outs() << "\n";
656 }
657}
658
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000659static void DumpLiteral4(uint32_t l, float f) {
660 outs() << format("0x%08" PRIx32, l);
661 if ((l & 0x7f800000) != 0x7f800000)
662 outs() << format(" (%.16e)\n", f);
663 else {
664 if (l == 0x7f800000)
665 outs() << " (+Infinity)\n";
666 else if (l == 0xff800000)
667 outs() << " (-Infinity)\n";
668 else if ((l & 0x00400000) == 0x00400000)
669 outs() << " (non-signaling Not-a-Number)\n";
670 else
671 outs() << " (signaling Not-a-Number)\n";
672 }
673}
674
675static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
676 uint32_t sect_size, uint64_t sect_addr,
677 bool print_addresses) {
678 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
679 if (print_addresses) {
680 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000681 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000682 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000683 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000684 }
685 float f;
686 memcpy(&f, sect + i, sizeof(float));
687 if (O->isLittleEndian() != sys::IsLittleEndianHost)
688 sys::swapByteOrder(f);
689 uint32_t l;
690 memcpy(&l, sect + i, sizeof(uint32_t));
691 if (O->isLittleEndian() != sys::IsLittleEndianHost)
692 sys::swapByteOrder(l);
693 DumpLiteral4(l, f);
694 }
695}
696
697static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
698 double d) {
699 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
700 uint32_t Hi, Lo;
701 if (O->isLittleEndian()) {
702 Hi = l1;
703 Lo = l0;
704 } else {
705 Hi = l0;
706 Lo = l1;
707 }
708 // Hi is the high word, so this is equivalent to if(isfinite(d))
709 if ((Hi & 0x7ff00000) != 0x7ff00000)
710 outs() << format(" (%.16e)\n", d);
711 else {
712 if (Hi == 0x7ff00000 && Lo == 0)
713 outs() << " (+Infinity)\n";
714 else if (Hi == 0xfff00000 && Lo == 0)
715 outs() << " (-Infinity)\n";
716 else if ((Hi & 0x00080000) == 0x00080000)
717 outs() << " (non-signaling Not-a-Number)\n";
718 else
719 outs() << " (signaling Not-a-Number)\n";
720 }
721}
722
723static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
724 uint32_t sect_size, uint64_t sect_addr,
725 bool print_addresses) {
726 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
727 if (print_addresses) {
728 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000729 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000730 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000731 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000732 }
733 double d;
734 memcpy(&d, sect + i, sizeof(double));
735 if (O->isLittleEndian() != sys::IsLittleEndianHost)
736 sys::swapByteOrder(d);
737 uint32_t l0, l1;
738 memcpy(&l0, sect + i, sizeof(uint32_t));
739 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
740 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
741 sys::swapByteOrder(l0);
742 sys::swapByteOrder(l1);
743 }
744 DumpLiteral8(O, l0, l1, d);
745 }
746}
747
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000748static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
749 outs() << format("0x%08" PRIx32, l0) << " ";
750 outs() << format("0x%08" PRIx32, l1) << " ";
751 outs() << format("0x%08" PRIx32, l2) << " ";
752 outs() << format("0x%08" PRIx32, l3) << "\n";
753}
754
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000755static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
756 uint32_t sect_size, uint64_t sect_addr,
757 bool print_addresses) {
758 for (uint32_t i = 0; i < sect_size; i += 16) {
759 if (print_addresses) {
760 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000761 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000762 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000763 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000764 }
765 uint32_t l0, l1, l2, l3;
766 memcpy(&l0, sect + i, sizeof(uint32_t));
767 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
768 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
769 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
770 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
771 sys::swapByteOrder(l0);
772 sys::swapByteOrder(l1);
773 sys::swapByteOrder(l2);
774 sys::swapByteOrder(l3);
775 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000776 DumpLiteral16(l0, l1, l2, l3);
777 }
778}
779
780static void DumpLiteralPointerSection(MachOObjectFile *O,
781 const SectionRef &Section,
782 const char *sect, uint32_t sect_size,
783 uint64_t sect_addr,
784 bool print_addresses) {
785 // Collect the literal sections in this Mach-O file.
786 std::vector<SectionRef> LiteralSections;
787 for (const SectionRef &Section : O->sections()) {
788 DataRefImpl Ref = Section.getRawDataRefImpl();
789 uint32_t section_type;
790 if (O->is64Bit()) {
791 const MachO::section_64 Sec = O->getSection64(Ref);
792 section_type = Sec.flags & MachO::SECTION_TYPE;
793 } else {
794 const MachO::section Sec = O->getSection(Ref);
795 section_type = Sec.flags & MachO::SECTION_TYPE;
796 }
797 if (section_type == MachO::S_CSTRING_LITERALS ||
798 section_type == MachO::S_4BYTE_LITERALS ||
799 section_type == MachO::S_8BYTE_LITERALS ||
800 section_type == MachO::S_16BYTE_LITERALS)
801 LiteralSections.push_back(Section);
802 }
803
804 // Set the size of the literal pointer.
805 uint32_t lp_size = O->is64Bit() ? 8 : 4;
806
807 // Collect the external relocation symbols for the the literal pointers.
808 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
809 for (const RelocationRef &Reloc : Section.relocations()) {
810 DataRefImpl Rel;
811 MachO::any_relocation_info RE;
812 bool isExtern = false;
813 Rel = Reloc.getRawDataRefImpl();
814 RE = O->getRelocation(Rel);
815 isExtern = O->getPlainRelocationExternal(RE);
816 if (isExtern) {
817 uint64_t RelocOffset;
818 Reloc.getOffset(RelocOffset);
819 symbol_iterator RelocSym = Reloc.getSymbol();
820 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
821 }
822 }
823 array_pod_sort(Relocs.begin(), Relocs.end());
824
825 // Dump each literal pointer.
826 for (uint32_t i = 0; i < sect_size; i += lp_size) {
827 if (print_addresses) {
828 if (O->is64Bit())
829 outs() << format("%016" PRIx64, sect_addr + i) << " ";
830 else
831 outs() << format("%08" PRIx64, sect_addr + i) << " ";
832 }
833 uint64_t lp;
834 if (O->is64Bit()) {
835 memcpy(&lp, sect + i, sizeof(uint64_t));
836 if (O->isLittleEndian() != sys::IsLittleEndianHost)
837 sys::swapByteOrder(lp);
838 } else {
839 uint32_t li;
840 memcpy(&li, sect + i, sizeof(uint32_t));
841 if (O->isLittleEndian() != sys::IsLittleEndianHost)
842 sys::swapByteOrder(li);
843 lp = li;
844 }
845
846 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000847 auto Reloc = std::find_if(
848 Relocs.begin(), Relocs.end(),
849 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
850 if (Reloc != Relocs.end()) {
851 symbol_iterator RelocSym = Reloc->second;
852 StringRef SymName;
853 RelocSym->getName(SymName);
854 outs() << "external relocation entry for symbol:" << SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000855 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000856 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000857
858 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000859 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
860 [&](const SectionRef &R) {
861 return lp >= R.getAddress() &&
862 lp < R.getAddress() + R.getSize();
863 });
864 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000865 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000866 continue;
867 }
868
869 uint64_t SectAddress = Sect->getAddress();
870 uint64_t SectSize = Sect->getSize();
871
872 StringRef SectName;
873 Sect->getName(SectName);
874 DataRefImpl Ref = Sect->getRawDataRefImpl();
875 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
876 outs() << SegmentName << ":" << SectName << ":";
877
878 uint32_t section_type;
879 if (O->is64Bit()) {
880 const MachO::section_64 Sec = O->getSection64(Ref);
881 section_type = Sec.flags & MachO::SECTION_TYPE;
882 } else {
883 const MachO::section Sec = O->getSection(Ref);
884 section_type = Sec.flags & MachO::SECTION_TYPE;
885 }
886
887 StringRef BytesStr;
888 Sect->getContents(BytesStr);
889 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
890
891 switch (section_type) {
892 case MachO::S_CSTRING_LITERALS:
893 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
894 i++) {
895 DumpCstringChar(Contents[i]);
896 }
897 outs() << "\n";
898 break;
899 case MachO::S_4BYTE_LITERALS:
900 float f;
901 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
902 uint32_t l;
903 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
904 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
905 sys::swapByteOrder(f);
906 sys::swapByteOrder(l);
907 }
908 DumpLiteral4(l, f);
909 break;
910 case MachO::S_8BYTE_LITERALS: {
911 double d;
912 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
913 uint32_t l0, l1;
914 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
915 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
916 sizeof(uint32_t));
917 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
918 sys::swapByteOrder(f);
919 sys::swapByteOrder(l0);
920 sys::swapByteOrder(l1);
921 }
922 DumpLiteral8(O, l0, l1, d);
923 break;
924 }
925 case MachO::S_16BYTE_LITERALS: {
926 uint32_t l0, l1, l2, l3;
927 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
928 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
929 sizeof(uint32_t));
930 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
931 sizeof(uint32_t));
932 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
933 sizeof(uint32_t));
934 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
935 sys::swapByteOrder(l0);
936 sys::swapByteOrder(l1);
937 sys::swapByteOrder(l2);
938 sys::swapByteOrder(l3);
939 }
940 DumpLiteral16(l0, l1, l2, l3);
941 break;
942 }
943 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000944 }
945}
946
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000947static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
948 uint32_t sect_size, uint64_t sect_addr,
949 SymbolAddressMap *AddrMap,
950 bool verbose) {
951 uint32_t stride;
952 if (O->is64Bit())
953 stride = sizeof(uint64_t);
954 else
955 stride = sizeof(uint32_t);
956 for (uint32_t i = 0; i < sect_size; i += stride) {
957 const char *SymbolName = nullptr;
958 if (O->is64Bit()) {
959 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
960 uint64_t pointer_value;
961 memcpy(&pointer_value, sect + i, stride);
962 if (O->isLittleEndian() != sys::IsLittleEndianHost)
963 sys::swapByteOrder(pointer_value);
964 outs() << format("0x%016" PRIx64, pointer_value);
965 if (verbose)
966 SymbolName = GuessSymbolName(pointer_value, AddrMap);
967 } else {
968 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
969 uint32_t pointer_value;
970 memcpy(&pointer_value, sect + i, stride);
971 if (O->isLittleEndian() != sys::IsLittleEndianHost)
972 sys::swapByteOrder(pointer_value);
973 outs() << format("0x%08" PRIx32, pointer_value);
974 if (verbose)
975 SymbolName = GuessSymbolName(pointer_value, AddrMap);
976 }
977 if (SymbolName)
978 outs() << " " << SymbolName;
979 outs() << "\n";
980 }
981}
982
983static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
984 uint32_t size, uint64_t addr) {
985 uint32_t cputype = O->getHeader().cputype;
986 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
987 uint32_t j;
988 for (uint32_t i = 0; i < size; i += j, addr += j) {
989 if (O->is64Bit())
990 outs() << format("%016" PRIx64, addr) << "\t";
991 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000992 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000993 for (j = 0; j < 16 && i + j < size; j++) {
994 uint8_t byte_word = *(sect + i + j);
995 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
996 }
997 outs() << "\n";
998 }
999 } else {
1000 uint32_t j;
1001 for (uint32_t i = 0; i < size; i += j, addr += j) {
1002 if (O->is64Bit())
1003 outs() << format("%016" PRIx64, addr) << "\t";
1004 else
1005 outs() << format("%08" PRIx64, sect) << "\t";
1006 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1007 j += sizeof(int32_t)) {
1008 if (i + j + sizeof(int32_t) < size) {
1009 uint32_t long_word;
1010 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1011 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1012 sys::swapByteOrder(long_word);
1013 outs() << format("%08" PRIx32, long_word) << " ";
1014 } else {
1015 for (uint32_t k = 0; i + j + k < size; k++) {
1016 uint8_t byte_word = *(sect + i + j);
1017 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1018 }
1019 }
1020 }
1021 outs() << "\n";
1022 }
1023 }
1024}
1025
Kevin Enderby95df54c2015-02-04 01:01:38 +00001026static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1027 StringRef DisSegName, StringRef DisSectName);
1028
1029static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1030 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001031 SymbolAddressMap AddrMap;
1032 if (verbose)
1033 CreateSymbolAddressMap(O, &AddrMap);
1034
1035 for (unsigned i = 0; i < DumpSections.size(); ++i) {
1036 StringRef DumpSection = DumpSections[i];
1037 std::pair<StringRef, StringRef> DumpSegSectName;
1038 DumpSegSectName = DumpSection.split(',');
1039 StringRef DumpSegName, DumpSectName;
1040 if (DumpSegSectName.second.size()) {
1041 DumpSegName = DumpSegSectName.first;
1042 DumpSectName = DumpSegSectName.second;
1043 } else {
1044 DumpSegName = "";
1045 DumpSectName = DumpSegSectName.first;
1046 }
1047 for (const SectionRef &Section : O->sections()) {
1048 StringRef SectName;
1049 Section.getName(SectName);
1050 DataRefImpl Ref = Section.getRawDataRefImpl();
1051 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1052 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1053 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001054
Kevin Enderby95df54c2015-02-04 01:01:38 +00001055 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001056 if (O->is64Bit()) {
1057 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001058 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001059
1060 } else {
1061 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001062 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001063 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001064 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001065
1066 StringRef BytesStr;
1067 Section.getContents(BytesStr);
1068 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1069 uint32_t sect_size = BytesStr.size();
1070 uint64_t sect_addr = Section.getAddress();
1071
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001072 if (Raw) {
1073 outs().write(BytesStr.data(), BytesStr.size());
1074 continue;
1075 }
1076
1077 outs() << "Contents of (" << SegName << "," << SectName
1078 << ") section\n";
1079
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001080 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001081 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1082 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1083 DisassembleMachO(Filename, O, SegName, SectName);
1084 continue;
1085 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001086 if (SegName == "__TEXT" && SectName == "__info_plist") {
1087 outs() << sect;
1088 continue;
1089 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001090 switch (section_type) {
1091 case MachO::S_REGULAR:
1092 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1093 break;
1094 case MachO::S_ZEROFILL:
1095 outs() << "zerofill section and has no contents in the file\n";
1096 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001097 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001098 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001099 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001101 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001102 break;
1103 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001104 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001105 break;
1106 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001107 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1108 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001109 case MachO::S_LITERAL_POINTERS:
1110 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001111 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001112 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001113 case MachO::S_MOD_INIT_FUNC_POINTERS:
1114 case MachO::S_MOD_TERM_FUNC_POINTERS:
1115 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1116 verbose);
1117 break;
1118 default:
1119 outs() << "Unknown section type ("
1120 << format("0x%08" PRIx32, section_type) << ")\n";
1121 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1122 break;
1123 }
1124 } else {
1125 if (section_type == MachO::S_ZEROFILL)
1126 outs() << "zerofill section and has no contents in the file\n";
1127 else
1128 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1129 }
1130 }
1131 }
1132 }
1133}
1134
Kevin Enderbycd66be52015-03-11 22:06:32 +00001135static void DumpInfoPlistSectionContents(StringRef Filename,
1136 MachOObjectFile *O) {
1137 for (const SectionRef &Section : O->sections()) {
1138 StringRef SectName;
1139 Section.getName(SectName);
1140 DataRefImpl Ref = Section.getRawDataRefImpl();
1141 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1142 if (SegName == "__TEXT" && SectName == "__info_plist") {
1143 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1144 StringRef BytesStr;
1145 Section.getContents(BytesStr);
1146 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1147 outs() << sect;
1148 return;
1149 }
1150 }
1151}
1152
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001153// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1154// and if it is and there is a list of architecture flags is specified then
1155// check to make sure this Mach-O file is one of those architectures or all
1156// architectures were specified. If not then an error is generated and this
1157// routine returns false. Else it returns true.
1158static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1159 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1160 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1161 bool ArchFound = false;
1162 MachO::mach_header H;
1163 MachO::mach_header_64 H_64;
1164 Triple T;
1165 if (MachO->is64Bit()) {
1166 H_64 = MachO->MachOObjectFile::getHeader64();
1167 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1168 } else {
1169 H = MachO->MachOObjectFile::getHeader();
1170 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1171 }
1172 unsigned i;
1173 for (i = 0; i < ArchFlags.size(); ++i) {
1174 if (ArchFlags[i] == T.getArchName())
1175 ArchFound = true;
1176 break;
1177 }
1178 if (!ArchFound) {
1179 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1180 << "architecture: " + ArchFlags[i] + "\n";
1181 return false;
1182 }
1183 }
1184 return true;
1185}
1186
Kevin Enderby0fc11822015-04-01 20:57:01 +00001187static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1188
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001189// ProcessMachO() is passed a single opened Mach-O file, which may be an
1190// archive member and or in a slice of a universal file. It prints the
1191// the file name and header info and then processes it according to the
1192// command line options.
1193static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1194 StringRef ArchiveMemberName = StringRef(),
1195 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001196 // If we are doing some processing here on the Mach-O file print the header
1197 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001198 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001199 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001200 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Kevin Enderby0fc11822015-04-01 20:57:01 +00001201 DylibsUsed || DylibId || ObjcMetaData ||
1202 (DumpSections.size() != 0 && !Raw)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001203 outs() << Filename;
1204 if (!ArchiveMemberName.empty())
1205 outs() << '(' << ArchiveMemberName << ')';
1206 if (!ArchitectureName.empty())
1207 outs() << " (architecture " << ArchitectureName << ")";
1208 outs() << ":\n";
1209 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001210
1211 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001212 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001213 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001214 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001215 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001216 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001217 if (LinkOptHints)
1218 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001219 if (Relocations)
1220 PrintRelocations(MachOOF);
1221 if (SectionHeaders)
1222 PrintSectionHeaders(MachOOF);
1223 if (SectionContents)
1224 PrintSectionContents(MachOOF);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001225 if (DumpSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001226 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001227 if (InfoPlist)
1228 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001229 if (DylibsUsed)
1230 PrintDylibs(MachOOF, false);
1231 if (DylibId)
1232 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001233 if (SymbolTable)
1234 PrintSymbolTable(MachOOF);
1235 if (UnwindInfo)
1236 printMachOUnwindInfo(MachOOF);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001237 if (PrivateHeaders)
1238 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001239 if (ObjcMetaData)
1240 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001241 if (ExportsTrie)
1242 printExportsTrie(MachOOF);
1243 if (Rebase)
1244 printRebaseTable(MachOOF);
1245 if (Bind)
1246 printBindTable(MachOOF);
1247 if (LazyBind)
1248 printLazyBindTable(MachOOF);
1249 if (WeakBind)
1250 printWeakBindTable(MachOOF);
1251}
1252
Kevin Enderby131d1772015-01-09 19:22:37 +00001253// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1254static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1255 outs() << " cputype (" << cputype << ")\n";
1256 outs() << " cpusubtype (" << cpusubtype << ")\n";
1257}
1258
1259// printCPUType() helps print_fat_headers by printing the cputype and
1260// pusubtype (symbolically for the one's it knows about).
1261static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1262 switch (cputype) {
1263 case MachO::CPU_TYPE_I386:
1264 switch (cpusubtype) {
1265 case MachO::CPU_SUBTYPE_I386_ALL:
1266 outs() << " cputype CPU_TYPE_I386\n";
1267 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1268 break;
1269 default:
1270 printUnknownCPUType(cputype, cpusubtype);
1271 break;
1272 }
1273 break;
1274 case MachO::CPU_TYPE_X86_64:
1275 switch (cpusubtype) {
1276 case MachO::CPU_SUBTYPE_X86_64_ALL:
1277 outs() << " cputype CPU_TYPE_X86_64\n";
1278 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1279 break;
1280 case MachO::CPU_SUBTYPE_X86_64_H:
1281 outs() << " cputype CPU_TYPE_X86_64\n";
1282 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1283 break;
1284 default:
1285 printUnknownCPUType(cputype, cpusubtype);
1286 break;
1287 }
1288 break;
1289 case MachO::CPU_TYPE_ARM:
1290 switch (cpusubtype) {
1291 case MachO::CPU_SUBTYPE_ARM_ALL:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1294 break;
1295 case MachO::CPU_SUBTYPE_ARM_V4T:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1298 break;
1299 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1302 break;
1303 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1304 outs() << " cputype CPU_TYPE_ARM\n";
1305 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1306 break;
1307 case MachO::CPU_SUBTYPE_ARM_V6:
1308 outs() << " cputype CPU_TYPE_ARM\n";
1309 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1310 break;
1311 case MachO::CPU_SUBTYPE_ARM_V6M:
1312 outs() << " cputype CPU_TYPE_ARM\n";
1313 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1314 break;
1315 case MachO::CPU_SUBTYPE_ARM_V7:
1316 outs() << " cputype CPU_TYPE_ARM\n";
1317 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1318 break;
1319 case MachO::CPU_SUBTYPE_ARM_V7EM:
1320 outs() << " cputype CPU_TYPE_ARM\n";
1321 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1322 break;
1323 case MachO::CPU_SUBTYPE_ARM_V7K:
1324 outs() << " cputype CPU_TYPE_ARM\n";
1325 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1326 break;
1327 case MachO::CPU_SUBTYPE_ARM_V7M:
1328 outs() << " cputype CPU_TYPE_ARM\n";
1329 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1330 break;
1331 case MachO::CPU_SUBTYPE_ARM_V7S:
1332 outs() << " cputype CPU_TYPE_ARM\n";
1333 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1334 break;
1335 default:
1336 printUnknownCPUType(cputype, cpusubtype);
1337 break;
1338 }
1339 break;
1340 case MachO::CPU_TYPE_ARM64:
1341 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1342 case MachO::CPU_SUBTYPE_ARM64_ALL:
1343 outs() << " cputype CPU_TYPE_ARM64\n";
1344 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1345 break;
1346 default:
1347 printUnknownCPUType(cputype, cpusubtype);
1348 break;
1349 }
1350 break;
1351 default:
1352 printUnknownCPUType(cputype, cpusubtype);
1353 break;
1354 }
1355}
1356
1357static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1358 bool verbose) {
1359 outs() << "Fat headers\n";
1360 if (verbose)
1361 outs() << "fat_magic FAT_MAGIC\n";
1362 else
1363 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1364
1365 uint32_t nfat_arch = UB->getNumberOfObjects();
1366 StringRef Buf = UB->getData();
1367 uint64_t size = Buf.size();
1368 uint64_t big_size = sizeof(struct MachO::fat_header) +
1369 nfat_arch * sizeof(struct MachO::fat_arch);
1370 outs() << "nfat_arch " << UB->getNumberOfObjects();
1371 if (nfat_arch == 0)
1372 outs() << " (malformed, contains zero architecture types)\n";
1373 else if (big_size > size)
1374 outs() << " (malformed, architectures past end of file)\n";
1375 else
1376 outs() << "\n";
1377
1378 for (uint32_t i = 0; i < nfat_arch; ++i) {
1379 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1380 uint32_t cputype = OFA.getCPUType();
1381 uint32_t cpusubtype = OFA.getCPUSubType();
1382 outs() << "architecture ";
1383 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1384 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1385 uint32_t other_cputype = other_OFA.getCPUType();
1386 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001387 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001388 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001389 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001390 outs() << "(illegal duplicate architecture) ";
1391 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001392 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001393 }
1394 if (verbose) {
1395 outs() << OFA.getArchTypeName() << "\n";
1396 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1397 } else {
1398 outs() << i << "\n";
1399 outs() << " cputype " << cputype << "\n";
1400 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1401 << "\n";
1402 }
1403 if (verbose &&
1404 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1405 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1406 else
1407 outs() << " capabilities "
1408 << format("0x%" PRIx32,
1409 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1410 outs() << " offset " << OFA.getOffset();
1411 if (OFA.getOffset() > size)
1412 outs() << " (past end of file)";
1413 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1414 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1415 outs() << "\n";
1416 outs() << " size " << OFA.getSize();
1417 big_size = OFA.getOffset() + OFA.getSize();
1418 if (big_size > size)
1419 outs() << " (past end of file)";
1420 outs() << "\n";
1421 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1422 << ")\n";
1423 }
1424}
1425
Kevin Enderby13023a12015-01-15 23:19:11 +00001426static void printArchiveChild(Archive::Child &C, bool verbose,
1427 bool print_offset) {
1428 if (print_offset)
1429 outs() << C.getChildOffset() << "\t";
1430 sys::fs::perms Mode = C.getAccessMode();
1431 if (verbose) {
1432 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1433 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1434 outs() << "-";
1435 if (Mode & sys::fs::owner_read)
1436 outs() << "r";
1437 else
1438 outs() << "-";
1439 if (Mode & sys::fs::owner_write)
1440 outs() << "w";
1441 else
1442 outs() << "-";
1443 if (Mode & sys::fs::owner_exe)
1444 outs() << "x";
1445 else
1446 outs() << "-";
1447 if (Mode & sys::fs::group_read)
1448 outs() << "r";
1449 else
1450 outs() << "-";
1451 if (Mode & sys::fs::group_write)
1452 outs() << "w";
1453 else
1454 outs() << "-";
1455 if (Mode & sys::fs::group_exe)
1456 outs() << "x";
1457 else
1458 outs() << "-";
1459 if (Mode & sys::fs::others_read)
1460 outs() << "r";
1461 else
1462 outs() << "-";
1463 if (Mode & sys::fs::others_write)
1464 outs() << "w";
1465 else
1466 outs() << "-";
1467 if (Mode & sys::fs::others_exe)
1468 outs() << "x";
1469 else
1470 outs() << "-";
1471 } else {
1472 outs() << format("0%o ", Mode);
1473 }
1474
1475 unsigned UID = C.getUID();
1476 outs() << format("%3d/", UID);
1477 unsigned GID = C.getGID();
1478 outs() << format("%-3d ", GID);
Kevin Enderbyc12718932015-01-16 22:10:36 +00001479 uint64_t Size = C.getRawSize();
Kevin Enderby479ee612015-01-23 21:02:44 +00001480 outs() << format("%5" PRId64, Size) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001481
1482 StringRef RawLastModified = C.getRawLastModified();
1483 if (verbose) {
1484 unsigned Seconds;
1485 if (RawLastModified.getAsInteger(10, Seconds))
1486 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1487 else {
1488 // Since cime(3) returns a 26 character string of the form:
1489 // "Sun Sep 16 01:03:52 1973\n\0"
1490 // just print 24 characters.
1491 time_t t = Seconds;
1492 outs() << format("%.24s ", ctime(&t));
1493 }
1494 } else {
1495 outs() << RawLastModified << " ";
1496 }
1497
1498 if (verbose) {
1499 ErrorOr<StringRef> NameOrErr = C.getName();
1500 if (NameOrErr.getError()) {
1501 StringRef RawName = C.getRawName();
1502 outs() << RawName << "\n";
1503 } else {
1504 StringRef Name = NameOrErr.get();
1505 outs() << Name << "\n";
1506 }
1507 } else {
1508 StringRef RawName = C.getRawName();
1509 outs() << RawName << "\n";
1510 }
1511}
1512
1513static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1514 if (A->hasSymbolTable()) {
1515 Archive::child_iterator S = A->getSymbolTableChild();
1516 Archive::Child C = *S;
1517 printArchiveChild(C, verbose, print_offset);
1518 }
1519 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1520 ++I) {
1521 Archive::Child C = *I;
1522 printArchiveChild(C, verbose, print_offset);
1523 }
1524}
1525
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001526// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1527// -arch flags selecting just those slices as specified by them and also parses
1528// archive files. Then for each individual Mach-O file ProcessMachO() is
1529// called to process the file based on the command line options.
1530void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001531 // Check for -arch all and verifiy the -arch flags are valid.
1532 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1533 if (ArchFlags[i] == "all") {
1534 ArchAll = true;
1535 } else {
1536 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1537 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1538 "'for the -arch option\n";
1539 return;
1540 }
1541 }
1542 }
1543
1544 // Attempt to open the binary.
1545 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1546 if (std::error_code EC = BinaryOrErr.getError()) {
1547 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +00001548 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001549 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001550 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001551
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001552 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1553 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001554 if (ArchiveHeaders)
1555 printArchiveHeaders(A, true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001556 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1557 I != E; ++I) {
1558 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1559 if (ChildOrErr.getError())
1560 continue;
1561 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1562 if (!checkMachOAndArchFlags(O, Filename))
1563 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001564 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001565 }
1566 }
1567 return;
1568 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001569 if (UniversalHeaders) {
1570 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001571 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001572 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001573 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1574 // If we have a list of architecture flags specified dump only those.
1575 if (!ArchAll && ArchFlags.size() != 0) {
1576 // Look for a slice in the universal binary that matches each ArchFlag.
1577 bool ArchFound;
1578 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1579 ArchFound = false;
1580 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1581 E = UB->end_objects();
1582 I != E; ++I) {
1583 if (ArchFlags[i] == I->getArchTypeName()) {
1584 ArchFound = true;
1585 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1586 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001587 std::string ArchitectureName = "";
1588 if (ArchFlags.size() > 1)
1589 ArchitectureName = I->getArchTypeName();
1590 if (ObjOrErr) {
1591 ObjectFile &O = *ObjOrErr.get();
1592 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001593 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001594 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1595 I->getAsArchive()) {
1596 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001597 outs() << "Archive : " << Filename;
1598 if (!ArchitectureName.empty())
1599 outs() << " (architecture " << ArchitectureName << ")";
1600 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001601 if (ArchiveHeaders)
1602 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001603 for (Archive::child_iterator AI = A->child_begin(),
1604 AE = A->child_end();
1605 AI != AE; ++AI) {
1606 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1607 if (ChildOrErr.getError())
1608 continue;
1609 if (MachOObjectFile *O =
1610 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001611 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001612 }
1613 }
1614 }
1615 }
1616 if (!ArchFound) {
1617 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1618 << "architecture: " + ArchFlags[i] + "\n";
1619 return;
1620 }
1621 }
1622 return;
1623 }
1624 // No architecture flags were specified so if this contains a slice that
1625 // matches the host architecture dump only that.
1626 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001627 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1628 E = UB->end_objects();
1629 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001630 if (MachOObjectFile::getHostArch().getArchName() ==
1631 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001632 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001633 std::string ArchiveName;
1634 ArchiveName.clear();
1635 if (ObjOrErr) {
1636 ObjectFile &O = *ObjOrErr.get();
1637 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001638 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001639 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1640 I->getAsArchive()) {
1641 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001642 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001643 if (ArchiveHeaders)
1644 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001645 for (Archive::child_iterator AI = A->child_begin(),
1646 AE = A->child_end();
1647 AI != AE; ++AI) {
1648 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1649 if (ChildOrErr.getError())
1650 continue;
1651 if (MachOObjectFile *O =
1652 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001653 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001654 }
1655 }
1656 return;
1657 }
1658 }
1659 }
1660 // Either all architectures have been specified or none have been specified
1661 // and this does not contain the host architecture so dump all the slices.
1662 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1663 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1664 E = UB->end_objects();
1665 I != E; ++I) {
1666 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001667 std::string ArchitectureName = "";
1668 if (moreThanOneArch)
1669 ArchitectureName = I->getArchTypeName();
1670 if (ObjOrErr) {
1671 ObjectFile &Obj = *ObjOrErr.get();
1672 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001673 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001674 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1675 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001676 outs() << "Archive : " << Filename;
1677 if (!ArchitectureName.empty())
1678 outs() << " (architecture " << ArchitectureName << ")";
1679 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001680 if (ArchiveHeaders)
1681 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001682 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1683 AI != AE; ++AI) {
1684 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1685 if (ChildOrErr.getError())
1686 continue;
1687 if (MachOObjectFile *O =
1688 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1689 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001690 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1691 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001692 }
1693 }
1694 }
1695 }
1696 return;
1697 }
1698 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1699 if (!checkMachOAndArchFlags(O, Filename))
1700 return;
1701 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001702 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001703 } else
1704 errs() << "llvm-objdump: '" << Filename << "': "
1705 << "Object is not a Mach-O file type.\n";
1706 } else
1707 errs() << "llvm-objdump: '" << Filename << "': "
1708 << "Unrecognized file type.\n";
Rafael Espindola9b709252013-04-13 01:45:40 +00001709}
1710
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001711typedef std::pair<uint64_t, const char *> BindInfoEntry;
1712typedef std::vector<BindInfoEntry> BindTable;
1713typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001714
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001715// The block of info used by the Symbolizer call backs.
1716struct DisassembleInfo {
1717 bool verbose;
1718 MachOObjectFile *O;
1719 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001720 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001721 std::vector<SectionRef> *Sections;
1722 const char *class_name;
1723 const char *selector_name;
1724 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001725 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001726 uint64_t adrp_addr;
1727 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001728 BindTable *bindtable;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001729};
1730
1731// SymbolizerGetOpInfo() is the operand information call back function.
1732// This is called to get the symbolic information for operand(s) of an
1733// instruction when it is being done. This routine does this from
1734// the relocation information, symbol table, etc. That block of information
1735// is a pointer to the struct DisassembleInfo that was passed when the
1736// disassembler context was created and passed to back to here when
1737// called back by the disassembler for instruction operands that could have
1738// relocation information. The address of the instruction containing operand is
1739// at the Pc parameter. The immediate value the operand has is passed in
1740// op_info->Value and is at Offset past the start of the instruction and has a
1741// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1742// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1743// names and addends of the symbolic expression to add for the operand. The
1744// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1745// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001746static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1747 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001748 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1749 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001750 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001751
1752 // Make sure all fields returned are zero if we don't set them.
1753 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1754 op_info->Value = value;
1755
1756 // If the TagType is not the value 1 which it code knows about or if no
1757 // verbose symbolic information is wanted then just return 0, indicating no
1758 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001759 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001760 return 0;
1761
1762 unsigned int Arch = info->O->getArch();
1763 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001764 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1765 return 0;
1766 // First search the section's relocation entries (if any) for an entry
1767 // for this section offset.
1768 uint32_t sect_addr = info->S.getAddress();
1769 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1770 bool reloc_found = false;
1771 DataRefImpl Rel;
1772 MachO::any_relocation_info RE;
1773 bool isExtern = false;
1774 SymbolRef Symbol;
1775 bool r_scattered = false;
1776 uint32_t r_value, pair_r_value, r_type;
1777 for (const RelocationRef &Reloc : info->S.relocations()) {
1778 uint64_t RelocOffset;
1779 Reloc.getOffset(RelocOffset);
1780 if (RelocOffset == sect_offset) {
1781 Rel = Reloc.getRawDataRefImpl();
1782 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001783 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001784 r_scattered = info->O->isRelocationScattered(RE);
1785 if (r_scattered) {
1786 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001787 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1788 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1789 DataRefImpl RelNext = Rel;
1790 info->O->moveRelocationNext(RelNext);
1791 MachO::any_relocation_info RENext;
1792 RENext = info->O->getRelocation(RelNext);
1793 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001794 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001795 else
1796 return 0;
1797 }
1798 } else {
1799 isExtern = info->O->getPlainRelocationExternal(RE);
1800 if (isExtern) {
1801 symbol_iterator RelocSym = Reloc.getSymbol();
1802 Symbol = *RelocSym;
1803 }
1804 }
1805 reloc_found = true;
1806 break;
1807 }
1808 }
1809 if (reloc_found && isExtern) {
1810 StringRef SymName;
1811 Symbol.getName(SymName);
1812 const char *name = SymName.data();
1813 op_info->AddSymbol.Present = 1;
1814 op_info->AddSymbol.Name = name;
1815 // For i386 extern relocation entries the value in the instruction is
1816 // the offset from the symbol, and value is already set in op_info->Value.
1817 return 1;
1818 }
1819 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1820 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001821 const char *add = GuessSymbolName(r_value, info->AddrMap);
1822 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001823 uint32_t offset = value - (r_value - pair_r_value);
1824 op_info->AddSymbol.Present = 1;
1825 if (add != nullptr)
1826 op_info->AddSymbol.Name = add;
1827 else
1828 op_info->AddSymbol.Value = r_value;
1829 op_info->SubtractSymbol.Present = 1;
1830 if (sub != nullptr)
1831 op_info->SubtractSymbol.Name = sub;
1832 else
1833 op_info->SubtractSymbol.Value = pair_r_value;
1834 op_info->Value = offset;
1835 return 1;
1836 }
1837 // TODO:
1838 // Second search the external relocation entries of a fully linked image
1839 // (if any) for an entry that matches this segment offset.
1840 // uint32_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001841 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001842 }
1843 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001844 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1845 return 0;
1846 // First search the section's relocation entries (if any) for an entry
1847 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001848 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001849 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1850 bool reloc_found = false;
1851 DataRefImpl Rel;
1852 MachO::any_relocation_info RE;
1853 bool isExtern = false;
1854 SymbolRef Symbol;
1855 for (const RelocationRef &Reloc : info->S.relocations()) {
1856 uint64_t RelocOffset;
1857 Reloc.getOffset(RelocOffset);
1858 if (RelocOffset == sect_offset) {
1859 Rel = Reloc.getRawDataRefImpl();
1860 RE = info->O->getRelocation(Rel);
1861 // NOTE: Scattered relocations don't exist on x86_64.
1862 isExtern = info->O->getPlainRelocationExternal(RE);
1863 if (isExtern) {
1864 symbol_iterator RelocSym = Reloc.getSymbol();
1865 Symbol = *RelocSym;
1866 }
1867 reloc_found = true;
1868 break;
1869 }
1870 }
1871 if (reloc_found && isExtern) {
1872 // The Value passed in will be adjusted by the Pc if the instruction
1873 // adds the Pc. But for x86_64 external relocation entries the Value
1874 // is the offset from the external symbol.
1875 if (info->O->getAnyRelocationPCRel(RE))
1876 op_info->Value -= Pc + Offset + Size;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001877 StringRef SymName;
1878 Symbol.getName(SymName);
1879 const char *name = SymName.data();
1880 unsigned Type = info->O->getAnyRelocationType(RE);
1881 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1882 DataRefImpl RelNext = Rel;
1883 info->O->moveRelocationNext(RelNext);
1884 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1885 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1886 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1887 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1888 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1889 op_info->SubtractSymbol.Present = 1;
1890 op_info->SubtractSymbol.Name = name;
1891 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1892 Symbol = *RelocSymNext;
1893 StringRef SymNameNext;
1894 Symbol.getName(SymNameNext);
1895 name = SymNameNext.data();
1896 }
1897 }
1898 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1899 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1900 op_info->AddSymbol.Present = 1;
1901 op_info->AddSymbol.Name = name;
1902 return 1;
1903 }
1904 // TODO:
1905 // Second search the external relocation entries of a fully linked image
1906 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001907 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001908 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001909 }
1910 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001911 if (Offset != 0 || (Size != 4 && Size != 2))
1912 return 0;
1913 // First search the section's relocation entries (if any) for an entry
1914 // for this section offset.
1915 uint32_t sect_addr = info->S.getAddress();
1916 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001917 DataRefImpl Rel;
1918 MachO::any_relocation_info RE;
1919 bool isExtern = false;
1920 SymbolRef Symbol;
1921 bool r_scattered = false;
1922 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001923 auto Reloc =
1924 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1925 [&](const RelocationRef &Reloc) {
1926 uint64_t RelocOffset;
1927 Reloc.getOffset(RelocOffset);
1928 return RelocOffset == sect_offset;
1929 });
1930
1931 if (Reloc == info->S.relocations().end())
1932 return 0;
1933
1934 Rel = Reloc->getRawDataRefImpl();
1935 RE = info->O->getRelocation(Rel);
1936 r_length = info->O->getAnyRelocationLength(RE);
1937 r_scattered = info->O->isRelocationScattered(RE);
1938 if (r_scattered) {
1939 r_value = info->O->getScatteredRelocationValue(RE);
1940 r_type = info->O->getScatteredRelocationType(RE);
1941 } else {
1942 r_type = info->O->getAnyRelocationType(RE);
1943 isExtern = info->O->getPlainRelocationExternal(RE);
1944 if (isExtern) {
1945 symbol_iterator RelocSym = Reloc->getSymbol();
1946 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001947 }
1948 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001949 if (r_type == MachO::ARM_RELOC_HALF ||
1950 r_type == MachO::ARM_RELOC_SECTDIFF ||
1951 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1952 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1953 DataRefImpl RelNext = Rel;
1954 info->O->moveRelocationNext(RelNext);
1955 MachO::any_relocation_info RENext;
1956 RENext = info->O->getRelocation(RelNext);
1957 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1958 if (info->O->isRelocationScattered(RENext))
1959 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1960 }
1961
1962 if (isExtern) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001963 StringRef SymName;
1964 Symbol.getName(SymName);
1965 const char *name = SymName.data();
1966 op_info->AddSymbol.Present = 1;
1967 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001968 switch (r_type) {
1969 case MachO::ARM_RELOC_HALF:
1970 if ((r_length & 0x1) == 1) {
1971 op_info->Value = value << 16 | other_half;
1972 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1973 } else {
1974 op_info->Value = other_half << 16 | value;
1975 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001976 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001977 break;
1978 default:
1979 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001980 }
1981 return 1;
1982 }
1983 // If we have a branch that is not an external relocation entry then
1984 // return 0 so the code in tryAddingSymbolicOperand() can use the
1985 // SymbolLookUp call back with the branch target address to look up the
1986 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00001987 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1988 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001989 return 0;
1990
1991 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001992 if (r_type == MachO::ARM_RELOC_HALF ||
1993 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1994 if ((r_length & 0x1) == 1)
1995 value = value << 16 | other_half;
1996 else
1997 value = other_half << 16 | value;
1998 }
1999 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2000 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2001 offset = value - r_value;
2002 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002003 }
2004
David Blaikie33dd45d02015-03-23 18:39:02 +00002005 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002006 if ((r_length & 0x1) == 1)
2007 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2008 else
2009 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002010 const char *add = GuessSymbolName(r_value, info->AddrMap);
2011 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002012 int32_t offset = value - (r_value - pair_r_value);
2013 op_info->AddSymbol.Present = 1;
2014 if (add != nullptr)
2015 op_info->AddSymbol.Name = add;
2016 else
2017 op_info->AddSymbol.Value = r_value;
2018 op_info->SubtractSymbol.Present = 1;
2019 if (sub != nullptr)
2020 op_info->SubtractSymbol.Name = sub;
2021 else
2022 op_info->SubtractSymbol.Value = pair_r_value;
2023 op_info->Value = offset;
2024 return 1;
2025 }
2026
Kevin Enderby930fdc72014-11-06 19:00:13 +00002027 op_info->AddSymbol.Present = 1;
2028 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002029 if (r_type == MachO::ARM_RELOC_HALF) {
2030 if ((r_length & 0x1) == 1)
2031 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2032 else
2033 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002034 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002035 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002036 if (add != nullptr) {
2037 op_info->AddSymbol.Name = add;
2038 return 1;
2039 }
2040 op_info->AddSymbol.Value = value;
2041 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002042 }
2043 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002044 if (Offset != 0 || Size != 4)
2045 return 0;
2046 // First search the section's relocation entries (if any) for an entry
2047 // for this section offset.
2048 uint64_t sect_addr = info->S.getAddress();
2049 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002050 auto Reloc =
2051 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2052 [&](const RelocationRef &Reloc) {
2053 uint64_t RelocOffset;
2054 Reloc.getOffset(RelocOffset);
2055 return RelocOffset == sect_offset;
2056 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002057
David Blaikie33dd45d02015-03-23 18:39:02 +00002058 if (Reloc == info->S.relocations().end())
2059 return 0;
2060
2061 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2062 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2063 uint32_t r_type = info->O->getAnyRelocationType(RE);
2064 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2065 DataRefImpl RelNext = Rel;
2066 info->O->moveRelocationNext(RelNext);
2067 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2068 if (value == 0) {
2069 value = info->O->getPlainRelocationSymbolNum(RENext);
2070 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002071 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002072 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002073 // NOTE: Scattered relocations don't exist on arm64.
2074 if (!info->O->getPlainRelocationExternal(RE))
2075 return 0;
2076 StringRef SymName;
2077 Reloc->getSymbol()->getName(SymName);
2078 const char *name = SymName.data();
2079 op_info->AddSymbol.Present = 1;
2080 op_info->AddSymbol.Name = name;
2081
2082 switch (r_type) {
2083 case MachO::ARM64_RELOC_PAGE21:
2084 /* @page */
2085 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2086 break;
2087 case MachO::ARM64_RELOC_PAGEOFF12:
2088 /* @pageoff */
2089 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2090 break;
2091 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2092 /* @gotpage */
2093 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2094 break;
2095 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2096 /* @gotpageoff */
2097 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2098 break;
2099 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2100 /* @tvlppage is not implemented in llvm-mc */
2101 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2102 break;
2103 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2104 /* @tvlppageoff is not implemented in llvm-mc */
2105 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2106 break;
2107 default:
2108 case MachO::ARM64_RELOC_BRANCH26:
2109 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2110 break;
2111 }
2112 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002113 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002114 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002115}
2116
Kevin Enderbybf246f52014-09-24 23:08:22 +00002117// GuessCstringPointer is passed the address of what might be a pointer to a
2118// literal string in a cstring section. If that address is in a cstring section
2119// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002120static const char *GuessCstringPointer(uint64_t ReferenceValue,
2121 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002122 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2123 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2124 for (unsigned I = 0;; ++I) {
2125 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2126 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2127 for (unsigned J = 0; J < Seg.nsects; ++J) {
2128 MachO::section_64 Sec = info->O->getSection64(Load, J);
2129 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2130 if (section_type == MachO::S_CSTRING_LITERALS &&
2131 ReferenceValue >= Sec.addr &&
2132 ReferenceValue < Sec.addr + Sec.size) {
2133 uint64_t sect_offset = ReferenceValue - Sec.addr;
2134 uint64_t object_offset = Sec.offset + sect_offset;
2135 StringRef MachOContents = info->O->getData();
2136 uint64_t object_size = MachOContents.size();
2137 const char *object_addr = (const char *)MachOContents.data();
2138 if (object_offset < object_size) {
2139 const char *name = object_addr + object_offset;
2140 return name;
2141 } else {
2142 return nullptr;
2143 }
2144 }
2145 }
2146 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2147 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2148 for (unsigned J = 0; J < Seg.nsects; ++J) {
2149 MachO::section Sec = info->O->getSection(Load, J);
2150 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2151 if (section_type == MachO::S_CSTRING_LITERALS &&
2152 ReferenceValue >= Sec.addr &&
2153 ReferenceValue < Sec.addr + Sec.size) {
2154 uint64_t sect_offset = ReferenceValue - Sec.addr;
2155 uint64_t object_offset = Sec.offset + sect_offset;
2156 StringRef MachOContents = info->O->getData();
2157 uint64_t object_size = MachOContents.size();
2158 const char *object_addr = (const char *)MachOContents.data();
2159 if (object_offset < object_size) {
2160 const char *name = object_addr + object_offset;
2161 return name;
2162 } else {
2163 return nullptr;
2164 }
2165 }
2166 }
2167 }
2168 if (I == LoadCommandCount - 1)
2169 break;
2170 else
2171 Load = info->O->getNextLoadCommandInfo(Load);
2172 }
2173 return nullptr;
2174}
2175
Kevin Enderby85974882014-09-26 22:20:44 +00002176// GuessIndirectSymbol returns the name of the indirect symbol for the
2177// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2178// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2179// symbol name being referenced by the stub or pointer.
2180static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2181 struct DisassembleInfo *info) {
2182 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2183 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2184 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2185 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2186 for (unsigned I = 0;; ++I) {
2187 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2188 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2189 for (unsigned J = 0; J < Seg.nsects; ++J) {
2190 MachO::section_64 Sec = info->O->getSection64(Load, J);
2191 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2192 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2193 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2194 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2195 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2196 section_type == MachO::S_SYMBOL_STUBS) &&
2197 ReferenceValue >= Sec.addr &&
2198 ReferenceValue < Sec.addr + Sec.size) {
2199 uint32_t stride;
2200 if (section_type == MachO::S_SYMBOL_STUBS)
2201 stride = Sec.reserved2;
2202 else
2203 stride = 8;
2204 if (stride == 0)
2205 return nullptr;
2206 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2207 if (index < Dysymtab.nindirectsyms) {
2208 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002209 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002210 if (indirect_symbol < Symtab.nsyms) {
2211 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2212 SymbolRef Symbol = *Sym;
2213 StringRef SymName;
2214 Symbol.getName(SymName);
2215 const char *name = SymName.data();
2216 return name;
2217 }
2218 }
2219 }
2220 }
2221 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2222 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2223 for (unsigned J = 0; J < Seg.nsects; ++J) {
2224 MachO::section Sec = info->O->getSection(Load, J);
2225 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2226 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2227 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2228 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2229 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2230 section_type == MachO::S_SYMBOL_STUBS) &&
2231 ReferenceValue >= Sec.addr &&
2232 ReferenceValue < Sec.addr + Sec.size) {
2233 uint32_t stride;
2234 if (section_type == MachO::S_SYMBOL_STUBS)
2235 stride = Sec.reserved2;
2236 else
2237 stride = 4;
2238 if (stride == 0)
2239 return nullptr;
2240 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2241 if (index < Dysymtab.nindirectsyms) {
2242 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002243 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002244 if (indirect_symbol < Symtab.nsyms) {
2245 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2246 SymbolRef Symbol = *Sym;
2247 StringRef SymName;
2248 Symbol.getName(SymName);
2249 const char *name = SymName.data();
2250 return name;
2251 }
2252 }
2253 }
2254 }
2255 }
2256 if (I == LoadCommandCount - 1)
2257 break;
2258 else
2259 Load = info->O->getNextLoadCommandInfo(Load);
2260 }
2261 return nullptr;
2262}
2263
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002264// method_reference() is called passing it the ReferenceName that might be
2265// a reference it to an Objective-C method call. If so then it allocates and
2266// assembles a method call string with the values last seen and saved in
2267// the DisassembleInfo's class_name and selector_name fields. This is saved
2268// into the method field of the info and any previous string is free'ed.
2269// Then the class_name field in the info is set to nullptr. The method call
2270// string is set into ReferenceName and ReferenceType is set to
2271// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2272// then both ReferenceType and ReferenceName are left unchanged.
2273static void method_reference(struct DisassembleInfo *info,
2274 uint64_t *ReferenceType,
2275 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002276 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002277 if (*ReferenceName != nullptr) {
2278 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002279 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002280 if (info->method != nullptr)
2281 free(info->method);
2282 if (info->class_name != nullptr) {
2283 info->method = (char *)malloc(5 + strlen(info->class_name) +
2284 strlen(info->selector_name));
2285 if (info->method != nullptr) {
2286 strcpy(info->method, "+[");
2287 strcat(info->method, info->class_name);
2288 strcat(info->method, " ");
2289 strcat(info->method, info->selector_name);
2290 strcat(info->method, "]");
2291 *ReferenceName = info->method;
2292 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2293 }
2294 } else {
2295 info->method = (char *)malloc(9 + strlen(info->selector_name));
2296 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002297 if (Arch == Triple::x86_64)
2298 strcpy(info->method, "-[%rdi ");
2299 else if (Arch == Triple::aarch64)
2300 strcpy(info->method, "-[x0 ");
2301 else
2302 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002303 strcat(info->method, info->selector_name);
2304 strcat(info->method, "]");
2305 *ReferenceName = info->method;
2306 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2307 }
2308 }
2309 info->class_name = nullptr;
2310 }
2311 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002312 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002313 if (info->method != nullptr)
2314 free(info->method);
2315 info->method = (char *)malloc(17 + strlen(info->selector_name));
2316 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002317 if (Arch == Triple::x86_64)
2318 strcpy(info->method, "-[[%rdi super] ");
2319 else if (Arch == Triple::aarch64)
2320 strcpy(info->method, "-[[x0 super] ");
2321 else
2322 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002323 strcat(info->method, info->selector_name);
2324 strcat(info->method, "]");
2325 *ReferenceName = info->method;
2326 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2327 }
2328 info->class_name = nullptr;
2329 }
2330 }
2331 }
2332}
2333
2334// GuessPointerPointer() is passed the address of what might be a pointer to
2335// a reference to an Objective-C class, selector, message ref or cfstring.
2336// If so the value of the pointer is returned and one of the booleans are set
2337// to true. If not zero is returned and all the booleans are set to false.
2338static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2339 struct DisassembleInfo *info,
2340 bool &classref, bool &selref, bool &msgref,
2341 bool &cfstring) {
2342 classref = false;
2343 selref = false;
2344 msgref = false;
2345 cfstring = false;
2346 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2347 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2348 for (unsigned I = 0;; ++I) {
2349 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2350 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2351 for (unsigned J = 0; J < Seg.nsects; ++J) {
2352 MachO::section_64 Sec = info->O->getSection64(Load, J);
2353 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2354 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2355 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2356 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2357 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2358 ReferenceValue >= Sec.addr &&
2359 ReferenceValue < Sec.addr + Sec.size) {
2360 uint64_t sect_offset = ReferenceValue - Sec.addr;
2361 uint64_t object_offset = Sec.offset + sect_offset;
2362 StringRef MachOContents = info->O->getData();
2363 uint64_t object_size = MachOContents.size();
2364 const char *object_addr = (const char *)MachOContents.data();
2365 if (object_offset < object_size) {
2366 uint64_t pointer_value;
2367 memcpy(&pointer_value, object_addr + object_offset,
2368 sizeof(uint64_t));
2369 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2370 sys::swapByteOrder(pointer_value);
2371 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2372 selref = true;
2373 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2374 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2375 classref = true;
2376 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2377 ReferenceValue + 8 < Sec.addr + Sec.size) {
2378 msgref = true;
2379 memcpy(&pointer_value, object_addr + object_offset + 8,
2380 sizeof(uint64_t));
2381 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2382 sys::swapByteOrder(pointer_value);
2383 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2384 cfstring = true;
2385 return pointer_value;
2386 } else {
2387 return 0;
2388 }
2389 }
2390 }
2391 }
2392 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2393 if (I == LoadCommandCount - 1)
2394 break;
2395 else
2396 Load = info->O->getNextLoadCommandInfo(Load);
2397 }
2398 return 0;
2399}
2400
2401// get_pointer_64 returns a pointer to the bytes in the object file at the
2402// Address from a section in the Mach-O file. And indirectly returns the
2403// offset into the section, number of bytes left in the section past the offset
2404// and which section is was being referenced. If the Address is not in a
2405// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002406static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2407 uint32_t &left, SectionRef &S,
2408 DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002409 offset = 0;
2410 left = 0;
2411 S = SectionRef();
2412 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2413 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2414 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2415 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2416 S = (*(info->Sections))[SectIdx];
2417 offset = Address - SectAddress;
2418 left = SectSize - offset;
2419 StringRef SectContents;
2420 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2421 return SectContents.data() + offset;
2422 }
2423 }
2424 return nullptr;
2425}
2426
2427// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2428// the symbol indirectly through n_value. Based on the relocation information
2429// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002430// If no relocation information is found and a non-zero ReferenceValue for the
2431// symbol is passed, look up that address in the info's AddrMap.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002432static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
Kevin Enderby0fc11822015-04-01 20:57:01 +00002433 DisassembleInfo *info, uint64_t &n_value,
2434 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002435 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002436 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002437 return nullptr;
2438
2439 // See if there is an external relocation entry at the sect_offset.
2440 bool reloc_found = false;
2441 DataRefImpl Rel;
2442 MachO::any_relocation_info RE;
2443 bool isExtern = false;
2444 SymbolRef Symbol;
2445 for (const RelocationRef &Reloc : S.relocations()) {
2446 uint64_t RelocOffset;
2447 Reloc.getOffset(RelocOffset);
2448 if (RelocOffset == sect_offset) {
2449 Rel = Reloc.getRawDataRefImpl();
2450 RE = info->O->getRelocation(Rel);
2451 if (info->O->isRelocationScattered(RE))
2452 continue;
2453 isExtern = info->O->getPlainRelocationExternal(RE);
2454 if (isExtern) {
2455 symbol_iterator RelocSym = Reloc.getSymbol();
2456 Symbol = *RelocSym;
2457 }
2458 reloc_found = true;
2459 break;
2460 }
2461 }
2462 // If there is an external relocation entry for a symbol in this section
2463 // at this section_offset then use that symbol's value for the n_value
2464 // and return its name.
2465 const char *SymbolName = nullptr;
2466 if (reloc_found && isExtern) {
2467 Symbol.getAddress(n_value);
Kevin Enderby0fc11822015-04-01 20:57:01 +00002468 if (n_value == UnknownAddressOrSize)
2469 n_value = 0;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002470 StringRef name;
2471 Symbol.getName(name);
2472 if (!name.empty()) {
2473 SymbolName = name.data();
2474 return SymbolName;
2475 }
2476 }
2477
2478 // TODO: For fully linked images, look through the external relocation
2479 // entries off the dynamic symtab command. For these the r_offset is from the
2480 // start of the first writeable segment in the Mach-O file. So the offset
2481 // to this section from that segment is passed to this routine by the caller,
2482 // as the database_offset. Which is the difference of the section's starting
2483 // address and the first writable segment.
2484 //
2485 // NOTE: need add passing the database_offset to this routine.
2486
Kevin Enderby0fc11822015-04-01 20:57:01 +00002487 // We did not find an external relocation entry so look up the ReferenceValue
2488 // as an address of a symbol and if found return that symbol's name.
2489 if (ReferenceValue != 0)
2490 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002491
2492 return SymbolName;
2493}
2494
2495// These are structs in the Objective-C meta data and read to produce the
2496// comments for disassembly. While these are part of the ABI they are no
2497// public defintions. So the are here not in include/llvm/Support/MachO.h .
2498
2499// The cfstring object in a 64-bit Mach-O file.
2500struct cfstring64_t {
2501 uint64_t isa; // class64_t * (64-bit pointer)
2502 uint64_t flags; // flag bits
2503 uint64_t characters; // char * (64-bit pointer)
2504 uint64_t length; // number of non-NULL characters in above
2505};
2506
2507// The class object in a 64-bit Mach-O file.
2508struct class64_t {
2509 uint64_t isa; // class64_t * (64-bit pointer)
2510 uint64_t superclass; // class64_t * (64-bit pointer)
2511 uint64_t cache; // Cache (64-bit pointer)
2512 uint64_t vtable; // IMP * (64-bit pointer)
2513 uint64_t data; // class_ro64_t * (64-bit pointer)
2514};
2515
2516struct class_ro64_t {
2517 uint32_t flags;
2518 uint32_t instanceStart;
2519 uint32_t instanceSize;
2520 uint32_t reserved;
2521 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2522 uint64_t name; // const char * (64-bit pointer)
2523 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2524 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2525 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2526 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2527 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2528};
2529
Kevin Enderby0fc11822015-04-01 20:57:01 +00002530/* Values for class_ro64_t->flags */
2531#define RO_META (1 << 0)
2532#define RO_ROOT (1 << 1)
2533#define RO_HAS_CXX_STRUCTORS (1 << 2)
2534
2535struct method_list64_t {
2536 uint32_t entsize;
2537 uint32_t count;
2538 /* struct method64_t first; These structures follow inline */
2539};
2540
2541struct method64_t {
2542 uint64_t name; /* SEL (64-bit pointer) */
2543 uint64_t types; /* const char * (64-bit pointer) */
2544 uint64_t imp; /* IMP (64-bit pointer) */
2545};
2546
2547struct protocol_list64_t {
2548 uint64_t count; /* uintptr_t (a 64-bit value) */
2549 /* struct protocol64_t * list[0]; These pointers follow inline */
2550};
2551
2552struct protocol64_t {
2553 uint64_t isa; /* id * (64-bit pointer) */
2554 uint64_t name; /* const char * (64-bit pointer) */
2555 uint64_t protocols; /* struct protocol_list64_t *
2556 (64-bit pointer) */
2557 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2558 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2559 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2560 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2561 uint64_t instanceProperties; /* struct objc_property_list *
2562 (64-bit pointer) */
2563};
2564
2565struct ivar_list64_t {
2566 uint32_t entsize;
2567 uint32_t count;
2568 /* struct ivar_t first; These structures follow inline */
2569};
2570
2571struct ivar64_t {
2572 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2573 uint64_t name; /* const char * (64-bit pointer) */
2574 uint64_t type; /* const char * (64-bit pointer) */
2575 uint32_t alignment;
2576 uint32_t size;
2577};
2578
2579struct objc_property_list64 {
2580 uint32_t entsize;
2581 uint32_t count;
2582 /* struct objc_property first; These structures follow inline */
2583};
2584
2585struct objc_property64 {
2586 uint64_t name; /* const char * (64-bit pointer) */
2587 uint64_t attributes; /* const char * (64-bit pointer) */
2588};
2589
2590struct category64_t {
2591 uint64_t name; /* const char * (64-bit pointer) */
2592 uint64_t cls; /* struct class_t * (64-bit pointer) */
2593 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2594 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2595 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2596 uint64_t instanceProperties; /* struct objc_property_list *
2597 (64-bit pointer) */
2598};
2599
2600struct objc_image_info64 {
2601 uint32_t version;
2602 uint32_t flags;
2603};
2604/* masks for objc_image_info.flags */
2605#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2606#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2607
2608struct message_ref64 {
2609 uint64_t imp; /* IMP (64-bit pointer) */
2610 uint64_t sel; /* SEL (64-bit pointer) */
2611};
2612
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002613inline void swapStruct(struct cfstring64_t &cfs) {
2614 sys::swapByteOrder(cfs.isa);
2615 sys::swapByteOrder(cfs.flags);
2616 sys::swapByteOrder(cfs.characters);
2617 sys::swapByteOrder(cfs.length);
2618}
2619
2620inline void swapStruct(struct class64_t &c) {
2621 sys::swapByteOrder(c.isa);
2622 sys::swapByteOrder(c.superclass);
2623 sys::swapByteOrder(c.cache);
2624 sys::swapByteOrder(c.vtable);
2625 sys::swapByteOrder(c.data);
2626}
2627
2628inline void swapStruct(struct class_ro64_t &cro) {
2629 sys::swapByteOrder(cro.flags);
2630 sys::swapByteOrder(cro.instanceStart);
2631 sys::swapByteOrder(cro.instanceSize);
2632 sys::swapByteOrder(cro.reserved);
2633 sys::swapByteOrder(cro.ivarLayout);
2634 sys::swapByteOrder(cro.name);
2635 sys::swapByteOrder(cro.baseMethods);
2636 sys::swapByteOrder(cro.baseProtocols);
2637 sys::swapByteOrder(cro.ivars);
2638 sys::swapByteOrder(cro.weakIvarLayout);
2639 sys::swapByteOrder(cro.baseProperties);
2640}
2641
Kevin Enderby0fc11822015-04-01 20:57:01 +00002642inline void swapStruct(struct method_list64_t &ml) {
2643 sys::swapByteOrder(ml.entsize);
2644 sys::swapByteOrder(ml.count);
2645}
2646
2647inline void swapStruct(struct method64_t &m) {
2648 sys::swapByteOrder(m.name);
2649 sys::swapByteOrder(m.types);
2650 sys::swapByteOrder(m.imp);
2651}
2652
2653inline void swapStruct(struct protocol_list64_t &pl) {
2654 sys::swapByteOrder(pl.count);
2655}
2656
2657inline void swapStruct(struct protocol64_t &p) {
2658 sys::swapByteOrder(p.isa);
2659 sys::swapByteOrder(p.name);
2660 sys::swapByteOrder(p.protocols);
2661 sys::swapByteOrder(p.instanceMethods);
2662 sys::swapByteOrder(p.classMethods);
2663 sys::swapByteOrder(p.optionalInstanceMethods);
2664 sys::swapByteOrder(p.optionalClassMethods);
2665 sys::swapByteOrder(p.instanceProperties);
2666}
2667
2668inline void swapStruct(struct ivar_list64_t &il) {
2669 sys::swapByteOrder(il.entsize);
2670 sys::swapByteOrder(il.count);
2671}
2672
2673inline void swapStruct(struct ivar64_t &i) {
2674 sys::swapByteOrder(i.offset);
2675 sys::swapByteOrder(i.name);
2676 sys::swapByteOrder(i.type);
2677 sys::swapByteOrder(i.alignment);
2678 sys::swapByteOrder(i.size);
2679}
2680
2681inline void swapStruct(struct objc_property_list64 &pl) {
2682 sys::swapByteOrder(pl.entsize);
2683 sys::swapByteOrder(pl.count);
2684}
2685
2686inline void swapStruct(struct objc_property64 &op) {
2687 sys::swapByteOrder(op.name);
2688 sys::swapByteOrder(op.attributes);
2689}
2690
2691inline void swapStruct(struct category64_t &c) {
2692 sys::swapByteOrder(c.name);
2693 sys::swapByteOrder(c.cls);
2694 sys::swapByteOrder(c.instanceMethods);
2695 sys::swapByteOrder(c.classMethods);
2696 sys::swapByteOrder(c.protocols);
2697 sys::swapByteOrder(c.instanceProperties);
2698}
2699
2700inline void swapStruct(struct objc_image_info64 &o) {
2701 sys::swapByteOrder(o.version);
2702 sys::swapByteOrder(o.flags);
2703}
2704
2705inline void swapStruct(struct message_ref64 &mr) {
2706 sys::swapByteOrder(mr.imp);
2707 sys::swapByteOrder(mr.sel);
2708}
2709
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002710static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2711 struct DisassembleInfo *info);
2712
2713// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2714// to an Objective-C class and returns the class name. It is also passed the
2715// address of the pointer, so when the pointer is zero as it can be in an .o
2716// file, that is used to look for an external relocation entry with a symbol
2717// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002718static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2719 uint64_t ReferenceValue,
2720 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002721 const char *r;
2722 uint32_t offset, left;
2723 SectionRef S;
2724
2725 // The pointer_value can be 0 in an object file and have a relocation
2726 // entry for the class symbol at the ReferenceValue (the address of the
2727 // pointer).
2728 if (pointer_value == 0) {
2729 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2730 if (r == nullptr || left < sizeof(uint64_t))
2731 return nullptr;
2732 uint64_t n_value;
2733 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2734 if (symbol_name == nullptr)
2735 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00002736 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002737 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2738 return class_name + 2;
2739 else
2740 return nullptr;
2741 }
2742
2743 // The case were the pointer_value is non-zero and points to a class defined
2744 // in this Mach-O file.
2745 r = get_pointer_64(pointer_value, offset, left, S, info);
2746 if (r == nullptr || left < sizeof(struct class64_t))
2747 return nullptr;
2748 struct class64_t c;
2749 memcpy(&c, r, sizeof(struct class64_t));
2750 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2751 swapStruct(c);
2752 if (c.data == 0)
2753 return nullptr;
2754 r = get_pointer_64(c.data, offset, left, S, info);
2755 if (r == nullptr || left < sizeof(struct class_ro64_t))
2756 return nullptr;
2757 struct class_ro64_t cro;
2758 memcpy(&cro, r, sizeof(struct class_ro64_t));
2759 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2760 swapStruct(cro);
2761 if (cro.name == 0)
2762 return nullptr;
2763 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2764 return name;
2765}
2766
2767// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2768// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002769static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2770 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002771 const char *r, *name;
2772 uint32_t offset, left;
2773 SectionRef S;
2774 struct cfstring64_t cfs;
2775 uint64_t cfs_characters;
2776
2777 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2778 if (r == nullptr || left < sizeof(struct cfstring64_t))
2779 return nullptr;
2780 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2781 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2782 swapStruct(cfs);
2783 if (cfs.characters == 0) {
2784 uint64_t n_value;
2785 const char *symbol_name = get_symbol_64(
2786 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2787 if (symbol_name == nullptr)
2788 return nullptr;
2789 cfs_characters = n_value;
2790 } else
2791 cfs_characters = cfs.characters;
2792 name = get_pointer_64(cfs_characters, offset, left, S, info);
2793
2794 return name;
2795}
2796
2797// get_objc2_64bit_selref() is used for disassembly and is passed a the address
2798// of a pointer to an Objective-C selector reference when the pointer value is
2799// zero as in a .o file and is likely to have a external relocation entry with
2800// who's symbol's n_value is the real pointer to the selector name. If that is
2801// the case the real pointer to the selector name is returned else 0 is
2802// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002803static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2804 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002805 uint32_t offset, left;
2806 SectionRef S;
2807
2808 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2809 if (r == nullptr || left < sizeof(uint64_t))
2810 return 0;
2811 uint64_t n_value;
2812 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2813 if (symbol_name == nullptr)
2814 return 0;
2815 return n_value;
2816}
2817
Kevin Enderby0fc11822015-04-01 20:57:01 +00002818static const SectionRef get_section(MachOObjectFile *O, const char *segname,
2819 const char *sectname) {
2820 for (const SectionRef &Section : O->sections()) {
2821 StringRef SectName;
2822 Section.getName(SectName);
2823 DataRefImpl Ref = Section.getRawDataRefImpl();
2824 StringRef SegName = O->getSectionFinalSegmentName(Ref);
2825 if (SegName == segname && SectName == sectname)
2826 return Section;
2827 }
2828 return SectionRef();
2829}
2830
2831static void
2832walk_pointer_list_64(const char *listname, const SectionRef S,
2833 MachOObjectFile *O, struct DisassembleInfo *info,
2834 void (*func)(uint64_t, struct DisassembleInfo *info)) {
2835 if (S == SectionRef())
2836 return;
2837
2838 StringRef SectName;
2839 S.getName(SectName);
2840 DataRefImpl Ref = S.getRawDataRefImpl();
2841 StringRef SegName = O->getSectionFinalSegmentName(Ref);
2842 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
2843
2844 StringRef BytesStr;
2845 S.getContents(BytesStr);
2846 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
2847
2848 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
2849 uint32_t left = S.getSize() - i;
2850 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
2851 uint64_t p = 0;
2852 memcpy(&p, Contents + i, size);
2853 if (i + sizeof(uint64_t) > S.getSize())
2854 outs() << listname << " list pointer extends past end of (" << SegName
2855 << "," << SectName << ") section\n";
2856 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
2857
2858 if (O->isLittleEndian() != sys::IsLittleEndianHost)
2859 sys::swapByteOrder(p);
2860
2861 uint64_t n_value = 0;
2862 const char *name = get_symbol_64(i, S, info, n_value, p);
2863 if (name == nullptr)
2864 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
2865
2866 if (n_value != 0) {
2867 outs() << format("0x%" PRIx64, n_value);
2868 if (p != 0)
2869 outs() << " + " << format("0x%" PRIx64, p);
2870 } else
2871 outs() << format("0x%" PRIx64, p);
2872 if (name != nullptr)
2873 outs() << " " << name;
2874 outs() << "\n";
2875
2876 p += n_value;
2877 if (func)
2878 func(p, info);
2879 }
2880}
2881
2882static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
2883 uint32_t offset, left;
2884 SectionRef S;
2885 const char *layout_map;
2886
2887 if (p == 0)
2888 return;
2889 layout_map = get_pointer_64(p, offset, left, S, info);
2890 if (layout_map != nullptr) {
2891 outs() << " layout map: ";
2892 do {
2893 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
2894 left--;
2895 layout_map++;
2896 } while (*layout_map != '\0' && left != 0);
2897 outs() << "\n";
2898 }
2899}
2900
2901static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
2902 const char *indent) {
2903 struct method_list64_t ml;
2904 struct method64_t m;
2905 const char *r;
2906 uint32_t offset, xoffset, left, i;
2907 SectionRef S, xS;
2908 const char *name, *sym_name;
2909 uint64_t n_value;
2910
2911 r = get_pointer_64(p, offset, left, S, info);
2912 if (r == nullptr)
2913 return;
2914 memset(&ml, '\0', sizeof(struct method_list64_t));
2915 if (left < sizeof(struct method_list64_t)) {
2916 memcpy(&ml, r, left);
2917 outs() << " (method_list_t entends past the end of the section)\n";
2918 } else
2919 memcpy(&ml, r, sizeof(struct method_list64_t));
2920 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2921 swapStruct(ml);
2922 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
2923 outs() << indent << "\t\t count " << ml.count << "\n";
2924
2925 p += sizeof(struct method_list64_t);
2926 offset += sizeof(struct method_list64_t);
2927 for (i = 0; i < ml.count; i++) {
2928 r = get_pointer_64(p, offset, left, S, info);
2929 if (r == nullptr)
2930 return;
2931 memset(&m, '\0', sizeof(struct method64_t));
2932 if (left < sizeof(struct method64_t)) {
2933 memcpy(&ml, r, left);
2934 outs() << indent << " (method_t entends past the end of the section)\n";
2935 } else
2936 memcpy(&m, r, sizeof(struct method64_t));
2937 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2938 swapStruct(m);
2939
2940 outs() << indent << "\t\t name ";
2941 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
2942 info, n_value, m.name);
2943 if (n_value != 0) {
2944 if (info->verbose && sym_name != nullptr)
2945 outs() << sym_name;
2946 else
2947 outs() << format("0x%" PRIx64, n_value);
2948 if (m.name != 0)
2949 outs() << " + " << format("0x%" PRIx64, m.name);
2950 } else
2951 outs() << format("0x%" PRIx64, m.name);
2952 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
2953 if (name != nullptr)
2954 outs() << format(" %.*s", left, name);
2955 outs() << "\n";
2956
2957 outs() << indent << "\t\t types ";
2958 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
2959 info, n_value, m.types);
2960 if (n_value != 0) {
2961 if (info->verbose && sym_name != nullptr)
2962 outs() << sym_name;
2963 else
2964 outs() << format("0x%" PRIx64, n_value);
2965 if (m.types != 0)
2966 outs() << " + " << format("0x%" PRIx64, m.types);
2967 } else
2968 outs() << format("0x%" PRIx64, m.types);
2969 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
2970 if (name != nullptr)
2971 outs() << format(" %.*s", left, name);
2972 outs() << "\n";
2973
2974 outs() << indent << "\t\t imp ";
2975 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
2976 n_value, m.imp);
2977 if (info->verbose && name == nullptr) {
2978 if (n_value != 0) {
2979 outs() << format("0x%" PRIx64, n_value) << " ";
2980 if (m.imp != 0)
2981 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
2982 } else
2983 outs() << format("0x%" PRIx64, m.imp) << " ";
2984 }
2985 if (name != nullptr)
2986 outs() << name;
2987 outs() << "\n";
2988
2989 p += sizeof(struct method64_t);
2990 offset += sizeof(struct method64_t);
2991 }
2992}
2993
2994static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
2995 struct protocol_list64_t pl;
2996 uint64_t q, n_value;
2997 struct protocol64_t pc;
2998 const char *r;
2999 uint32_t offset, xoffset, left, i;
3000 SectionRef S, xS;
3001 const char *name, *sym_name;
3002
3003 r = get_pointer_64(p, offset, left, S, info);
3004 if (r == nullptr)
3005 return;
3006 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3007 if (left < sizeof(struct protocol_list64_t)) {
3008 memcpy(&pl, r, left);
3009 outs() << " (protocol_list_t entends past the end of the section)\n";
3010 } else
3011 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3012 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3013 swapStruct(pl);
3014 outs() << " count " << pl.count << "\n";
3015
3016 p += sizeof(struct protocol_list64_t);
3017 offset += sizeof(struct protocol_list64_t);
3018 for (i = 0; i < pl.count; i++) {
3019 r = get_pointer_64(p, offset, left, S, info);
3020 if (r == nullptr)
3021 return;
3022 q = 0;
3023 if (left < sizeof(uint64_t)) {
3024 memcpy(&q, r, left);
3025 outs() << " (protocol_t * entends past the end of the section)\n";
3026 } else
3027 memcpy(&q, r, sizeof(uint64_t));
3028 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3029 sys::swapByteOrder(q);
3030
3031 outs() << "\t\t list[" << i << "] ";
3032 sym_name = get_symbol_64(offset, S, info, n_value, q);
3033 if (n_value != 0) {
3034 if (info->verbose && sym_name != nullptr)
3035 outs() << sym_name;
3036 else
3037 outs() << format("0x%" PRIx64, n_value);
3038 if (q != 0)
3039 outs() << " + " << format("0x%" PRIx64, q);
3040 } else
3041 outs() << format("0x%" PRIx64, q);
3042 outs() << " (struct protocol_t *)\n";
3043
3044 r = get_pointer_64(q + n_value, offset, left, S, info);
3045 if (r == nullptr)
3046 return;
3047 memset(&pc, '\0', sizeof(struct protocol64_t));
3048 if (left < sizeof(struct protocol64_t)) {
3049 memcpy(&pc, r, left);
3050 outs() << " (protocol_t entends past the end of the section)\n";
3051 } else
3052 memcpy(&pc, r, sizeof(struct protocol64_t));
3053 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3054 swapStruct(pc);
3055
3056 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3057
3058 outs() << "\t\t\t name ";
3059 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3060 info, n_value, pc.name);
3061 if (n_value != 0) {
3062 if (info->verbose && sym_name != nullptr)
3063 outs() << sym_name;
3064 else
3065 outs() << format("0x%" PRIx64, n_value);
3066 if (pc.name != 0)
3067 outs() << " + " << format("0x%" PRIx64, pc.name);
3068 } else
3069 outs() << format("0x%" PRIx64, pc.name);
3070 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3071 if (name != nullptr)
3072 outs() << format(" %.*s", left, name);
3073 outs() << "\n";
3074
3075 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3076
3077 outs() << "\t\t instanceMethods ";
3078 sym_name =
3079 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3080 S, info, n_value, pc.instanceMethods);
3081 if (n_value != 0) {
3082 if (info->verbose && sym_name != nullptr)
3083 outs() << sym_name;
3084 else
3085 outs() << format("0x%" PRIx64, n_value);
3086 if (pc.instanceMethods != 0)
3087 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3088 } else
3089 outs() << format("0x%" PRIx64, pc.instanceMethods);
3090 outs() << " (struct method_list_t *)\n";
3091 if (pc.instanceMethods + n_value != 0)
3092 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3093
3094 outs() << "\t\t classMethods ";
3095 sym_name =
3096 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3097 info, n_value, pc.classMethods);
3098 if (n_value != 0) {
3099 if (info->verbose && sym_name != nullptr)
3100 outs() << sym_name;
3101 else
3102 outs() << format("0x%" PRIx64, n_value);
3103 if (pc.classMethods != 0)
3104 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3105 } else
3106 outs() << format("0x%" PRIx64, pc.classMethods);
3107 outs() << " (struct method_list_t *)\n";
3108 if (pc.classMethods + n_value != 0)
3109 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3110
3111 outs() << "\t optionalInstanceMethods "
3112 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3113 outs() << "\t optionalClassMethods "
3114 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3115 outs() << "\t instanceProperties "
3116 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3117
3118 p += sizeof(uint64_t);
3119 offset += sizeof(uint64_t);
3120 }
3121}
3122
3123static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3124 struct ivar_list64_t il;
3125 struct ivar64_t i;
3126 const char *r;
3127 uint32_t offset, xoffset, left, j;
3128 SectionRef S, xS;
3129 const char *name, *sym_name, *ivar_offset_p;
3130 uint64_t ivar_offset, n_value;
3131
3132 r = get_pointer_64(p, offset, left, S, info);
3133 if (r == nullptr)
3134 return;
3135 memset(&il, '\0', sizeof(struct ivar_list64_t));
3136 if (left < sizeof(struct ivar_list64_t)) {
3137 memcpy(&il, r, left);
3138 outs() << " (ivar_list_t entends past the end of the section)\n";
3139 } else
3140 memcpy(&il, r, sizeof(struct ivar_list64_t));
3141 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3142 swapStruct(il);
3143 outs() << " entsize " << il.entsize << "\n";
3144 outs() << " count " << il.count << "\n";
3145
3146 p += sizeof(struct ivar_list64_t);
3147 offset += sizeof(struct ivar_list64_t);
3148 for (j = 0; j < il.count; j++) {
3149 r = get_pointer_64(p, offset, left, S, info);
3150 if (r == nullptr)
3151 return;
3152 memset(&i, '\0', sizeof(struct ivar64_t));
3153 if (left < sizeof(struct ivar64_t)) {
3154 memcpy(&i, r, left);
3155 outs() << " (ivar_t entends past the end of the section)\n";
3156 } else
3157 memcpy(&i, r, sizeof(struct ivar64_t));
3158 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3159 swapStruct(i);
3160
3161 outs() << "\t\t\t offset ";
3162 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3163 info, n_value, i.offset);
3164 if (n_value != 0) {
3165 if (info->verbose && sym_name != nullptr)
3166 outs() << sym_name;
3167 else
3168 outs() << format("0x%" PRIx64, n_value);
3169 if (i.offset != 0)
3170 outs() << " + " << format("0x%" PRIx64, i.offset);
3171 } else
3172 outs() << format("0x%" PRIx64, i.offset);
3173 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3174 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3175 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3176 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3177 sys::swapByteOrder(ivar_offset);
3178 outs() << " " << ivar_offset << "\n";
3179 } else
3180 outs() << "\n";
3181
3182 outs() << "\t\t\t name ";
3183 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3184 n_value, i.name);
3185 if (n_value != 0) {
3186 if (info->verbose && sym_name != nullptr)
3187 outs() << sym_name;
3188 else
3189 outs() << format("0x%" PRIx64, n_value);
3190 if (i.name != 0)
3191 outs() << " + " << format("0x%" PRIx64, i.name);
3192 } else
3193 outs() << format("0x%" PRIx64, i.name);
3194 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3195 if (name != nullptr)
3196 outs() << format(" %.*s", left, name);
3197 outs() << "\n";
3198
3199 outs() << "\t\t\t type ";
3200 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
3201 n_value, i.name);
3202 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
3203 if (n_value != 0) {
3204 if (info->verbose && sym_name != nullptr)
3205 outs() << sym_name;
3206 else
3207 outs() << format("0x%" PRIx64, n_value);
3208 if (i.type != 0)
3209 outs() << " + " << format("0x%" PRIx64, i.type);
3210 } else
3211 outs() << format("0x%" PRIx64, i.type);
3212 if (name != nullptr)
3213 outs() << format(" %.*s", left, name);
3214 outs() << "\n";
3215
3216 outs() << "\t\t\talignment " << i.alignment << "\n";
3217 outs() << "\t\t\t size " << i.size << "\n";
3218
3219 p += sizeof(struct ivar64_t);
3220 offset += sizeof(struct ivar64_t);
3221 }
3222}
3223
3224static void print_objc_property_list64(uint64_t p,
3225 struct DisassembleInfo *info) {
3226 struct objc_property_list64 opl;
3227 struct objc_property64 op;
3228 const char *r;
3229 uint32_t offset, xoffset, left, j;
3230 SectionRef S, xS;
3231 const char *name, *sym_name;
3232 uint64_t n_value;
3233
3234 r = get_pointer_64(p, offset, left, S, info);
3235 if (r == nullptr)
3236 return;
3237 memset(&opl, '\0', sizeof(struct objc_property_list64));
3238 if (left < sizeof(struct objc_property_list64)) {
3239 memcpy(&opl, r, left);
3240 outs() << " (objc_property_list entends past the end of the section)\n";
3241 } else
3242 memcpy(&opl, r, sizeof(struct objc_property_list64));
3243 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3244 swapStruct(opl);
3245 outs() << " entsize " << opl.entsize << "\n";
3246 outs() << " count " << opl.count << "\n";
3247
3248 p += sizeof(struct objc_property_list64);
3249 offset += sizeof(struct objc_property_list64);
3250 for (j = 0; j < opl.count; j++) {
3251 r = get_pointer_64(p, offset, left, S, info);
3252 if (r == nullptr)
3253 return;
3254 memset(&op, '\0', sizeof(struct objc_property64));
3255 if (left < sizeof(struct objc_property64)) {
3256 memcpy(&op, r, left);
3257 outs() << " (objc_property entends past the end of the section)\n";
3258 } else
3259 memcpy(&op, r, sizeof(struct objc_property64));
3260 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3261 swapStruct(op);
3262
3263 outs() << "\t\t\t name ";
3264 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
3265 info, n_value, op.name);
3266 if (n_value != 0) {
3267 if (info->verbose && sym_name != nullptr)
3268 outs() << sym_name;
3269 else
3270 outs() << format("0x%" PRIx64, n_value);
3271 if (op.name != 0)
3272 outs() << " + " << format("0x%" PRIx64, op.name);
3273 } else
3274 outs() << format("0x%" PRIx64, op.name);
3275 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
3276 if (name != nullptr)
3277 outs() << format(" %.*s", left, name);
3278 outs() << "\n";
3279
3280 outs() << "\t\t\tattributes ";
3281 sym_name =
3282 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
3283 info, n_value, op.attributes);
3284 if (n_value != 0) {
3285 if (info->verbose && sym_name != nullptr)
3286 outs() << sym_name;
3287 else
3288 outs() << format("0x%" PRIx64, n_value);
3289 if (op.attributes != 0)
3290 outs() << " + " << format("0x%" PRIx64, op.attributes);
3291 } else
3292 outs() << format("0x%" PRIx64, op.attributes);
3293 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
3294 if (name != nullptr)
3295 outs() << format(" %.*s", left, name);
3296 outs() << "\n";
3297
3298 p += sizeof(struct objc_property64);
3299 offset += sizeof(struct objc_property64);
3300 }
3301}
3302
3303static void print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
3304 bool &is_meta_class) {
3305 struct class_ro64_t cro;
3306 const char *r;
3307 uint32_t offset, xoffset, left;
3308 SectionRef S, xS;
3309 const char *name, *sym_name;
3310 uint64_t n_value;
3311
3312 r = get_pointer_64(p, offset, left, S, info);
3313 if (r == nullptr || left < sizeof(struct class_ro64_t))
3314 return;
3315 memset(&cro, '\0', sizeof(struct class_ro64_t));
3316 if (left < sizeof(struct class_ro64_t)) {
3317 memcpy(&cro, r, left);
3318 outs() << " (class_ro_t entends past the end of the section)\n";
3319 } else
3320 memcpy(&cro, r, sizeof(struct class_ro64_t));
3321 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3322 swapStruct(cro);
3323 outs() << " flags " << format("0x%" PRIx32, cro.flags);
3324 if (cro.flags & RO_META)
3325 outs() << " RO_META";
3326 if (cro.flags & RO_ROOT)
3327 outs() << " RO_ROOT";
3328 if (cro.flags & RO_HAS_CXX_STRUCTORS)
3329 outs() << " RO_HAS_CXX_STRUCTORS";
3330 outs() << "\n";
3331 outs() << " instanceStart " << cro.instanceStart << "\n";
3332 outs() << " instanceSize " << cro.instanceSize << "\n";
3333 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
3334 << "\n";
3335 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
3336 << "\n";
3337 print_layout_map64(cro.ivarLayout, info);
3338
3339 outs() << " name ";
3340 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
3341 info, n_value, cro.name);
3342 if (n_value != 0) {
3343 if (info->verbose && sym_name != nullptr)
3344 outs() << sym_name;
3345 else
3346 outs() << format("0x%" PRIx64, n_value);
3347 if (cro.name != 0)
3348 outs() << " + " << format("0x%" PRIx64, cro.name);
3349 } else
3350 outs() << format("0x%" PRIx64, cro.name);
3351 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
3352 if (name != nullptr)
3353 outs() << format(" %.*s", left, name);
3354 outs() << "\n";
3355
3356 outs() << " baseMethods ";
3357 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
3358 S, info, n_value, cro.baseMethods);
3359 if (n_value != 0) {
3360 if (info->verbose && sym_name != nullptr)
3361 outs() << sym_name;
3362 else
3363 outs() << format("0x%" PRIx64, n_value);
3364 if (cro.baseMethods != 0)
3365 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
3366 } else
3367 outs() << format("0x%" PRIx64, cro.baseMethods);
3368 outs() << " (struct method_list_t *)\n";
3369 if (cro.baseMethods + n_value != 0)
3370 print_method_list64_t(cro.baseMethods + n_value, info, "");
3371
3372 outs() << " baseProtocols ";
3373 sym_name =
3374 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
3375 info, n_value, cro.baseProtocols);
3376 if (n_value != 0) {
3377 if (info->verbose && sym_name != nullptr)
3378 outs() << sym_name;
3379 else
3380 outs() << format("0x%" PRIx64, n_value);
3381 if (cro.baseProtocols != 0)
3382 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
3383 } else
3384 outs() << format("0x%" PRIx64, cro.baseProtocols);
3385 outs() << "\n";
3386 if (cro.baseProtocols + n_value != 0)
3387 print_protocol_list64_t(cro.baseProtocols + n_value, info);
3388
3389 outs() << " ivars ";
3390 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
3391 info, n_value, cro.baseProtocols);
3392 if (n_value != 0) {
3393 if (info->verbose && sym_name != nullptr)
3394 outs() << sym_name;
3395 else
3396 outs() << format("0x%" PRIx64, n_value);
3397 if (cro.ivars != 0)
3398 outs() << " + " << format("0x%" PRIx64, cro.ivars);
3399 } else
3400 outs() << format("0x%" PRIx64, cro.ivars);
3401 outs() << "\n";
3402 if (cro.ivars + n_value != 0)
3403 print_ivar_list64_t(cro.ivars + n_value, info);
3404
3405 outs() << " weakIvarLayout ";
3406 sym_name =
3407 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
3408 info, n_value, cro.weakIvarLayout);
3409 if (n_value != 0) {
3410 if (info->verbose && sym_name != nullptr)
3411 outs() << sym_name;
3412 else
3413 outs() << format("0x%" PRIx64, n_value);
3414 if (cro.weakIvarLayout != 0)
3415 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
3416 } else
3417 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
3418 outs() << "\n";
3419 print_layout_map64(cro.weakIvarLayout + n_value, info);
3420
3421 outs() << " baseProperties ";
3422 sym_name =
3423 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
3424 info, n_value, cro.baseProperties);
3425 if (n_value != 0) {
3426 if (info->verbose && sym_name != nullptr)
3427 outs() << sym_name;
3428 else
3429 outs() << format("0x%" PRIx64, n_value);
3430 if (cro.baseProperties != 0)
3431 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
3432 } else
3433 outs() << format("0x%" PRIx64, cro.baseProperties);
3434 outs() << "\n";
3435 if (cro.baseProperties + n_value != 0)
3436 print_objc_property_list64(cro.baseProperties + n_value, info);
3437
3438 is_meta_class = (cro.flags & RO_META) ? true : false;
3439}
3440
3441static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
3442 struct class64_t c;
3443 const char *r;
3444 uint32_t offset, left;
3445 SectionRef S;
3446 const char *name;
3447 uint64_t isa_n_value, n_value;
3448
3449 r = get_pointer_64(p, offset, left, S, info);
3450 if (r == nullptr || left < sizeof(struct class64_t))
3451 return;
3452 memset(&c, '\0', sizeof(struct class64_t));
3453 if (left < sizeof(struct class64_t)) {
3454 memcpy(&c, r, left);
3455 outs() << " (class_t entends past the end of the section)\n";
3456 } else
3457 memcpy(&c, r, sizeof(struct class64_t));
3458 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3459 swapStruct(c);
3460
3461 outs() << " isa " << format("0x%" PRIx64, c.isa);
3462 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
3463 isa_n_value, c.isa);
3464 if (name != nullptr)
3465 outs() << " " << name;
3466 outs() << "\n";
3467
3468 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
3469 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
3470 n_value, c.superclass);
3471 if (name != nullptr)
3472 outs() << " " << name;
3473 outs() << "\n";
3474
3475 outs() << " cache " << format("0x%" PRIx64, c.cache);
3476 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
3477 n_value, c.cache);
3478 if (name != nullptr)
3479 outs() << " " << name;
3480 outs() << "\n";
3481
3482 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
3483 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
3484 n_value, c.vtable);
3485 if (name != nullptr)
3486 outs() << " " << name;
3487 outs() << "\n";
3488
3489 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
3490 n_value, c.data);
3491 outs() << " data ";
3492 if (n_value != 0) {
3493 if (info->verbose && name != nullptr)
3494 outs() << name;
3495 else
3496 outs() << format("0x%" PRIx64, n_value);
3497 if (c.data != 0)
3498 outs() << " + " << format("0x%" PRIx64, c.data);
3499 } else
3500 outs() << format("0x%" PRIx64, c.data);
3501 outs() << " (struct class_ro_t *)";
3502
3503 // This is a Swift class if some of the low bits of the pointer are set.
3504 if ((c.data + n_value) & 0x7)
3505 outs() << " Swift class";
3506 outs() << "\n";
3507 bool is_meta_class = true;
3508 print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class);
3509
3510 if (is_meta_class == false) {
3511 outs() << "Meta Class\n";
3512 print_class64_t(c.isa + isa_n_value, info);
3513 }
3514}
3515
3516static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
3517 struct category64_t c;
3518 const char *r;
3519 uint32_t offset, xoffset, left;
3520 SectionRef S, xS;
3521 const char *name, *sym_name;
3522 uint64_t n_value;
3523
3524 r = get_pointer_64(p, offset, left, S, info);
3525 if (r == nullptr)
3526 return;
3527 memset(&c, '\0', sizeof(struct category64_t));
3528 if (left < sizeof(struct category64_t)) {
3529 memcpy(&c, r, left);
3530 outs() << " (category_t entends past the end of the section)\n";
3531 } else
3532 memcpy(&c, r, sizeof(struct category64_t));
3533 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3534 swapStruct(c);
3535
3536 outs() << " name ";
3537 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
3538 info, n_value, c.name);
3539 if (n_value != 0) {
3540 if (info->verbose && sym_name != nullptr)
3541 outs() << sym_name;
3542 else
3543 outs() << format("0x%" PRIx64, n_value);
3544 if (c.name != 0)
3545 outs() << " + " << format("0x%" PRIx64, c.name);
3546 } else
3547 outs() << format("0x%" PRIx64, c.name);
3548 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
3549 if (name != nullptr)
3550 outs() << format(" %.*s", left, name);
3551 outs() << "\n";
3552
3553 outs() << " cls ";
3554 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
3555 n_value, c.cls);
3556 if (n_value != 0) {
3557 if (info->verbose && sym_name != nullptr)
3558 outs() << sym_name;
3559 else
3560 outs() << format("0x%" PRIx64, n_value);
3561 if (c.cls != 0)
3562 outs() << " + " << format("0x%" PRIx64, c.cls);
3563 } else
3564 outs() << format("0x%" PRIx64, c.cls);
3565 outs() << "\n";
3566 if (c.cls + n_value != 0)
3567 print_class64_t(c.cls + n_value, info);
3568
3569 outs() << " instanceMethods ";
3570 sym_name =
3571 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
3572 info, n_value, c.instanceMethods);
3573 if (n_value != 0) {
3574 if (info->verbose && sym_name != nullptr)
3575 outs() << sym_name;
3576 else
3577 outs() << format("0x%" PRIx64, n_value);
3578 if (c.instanceMethods != 0)
3579 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
3580 } else
3581 outs() << format("0x%" PRIx64, c.instanceMethods);
3582 outs() << "\n";
3583 if (c.instanceMethods + n_value != 0)
3584 print_method_list64_t(c.instanceMethods + n_value, info, "");
3585
3586 outs() << " classMethods ";
3587 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
3588 S, info, n_value, c.classMethods);
3589 if (n_value != 0) {
3590 if (info->verbose && sym_name != nullptr)
3591 outs() << sym_name;
3592 else
3593 outs() << format("0x%" PRIx64, n_value);
3594 if (c.classMethods != 0)
3595 outs() << " + " << format("0x%" PRIx64, c.classMethods);
3596 } else
3597 outs() << format("0x%" PRIx64, c.classMethods);
3598 outs() << "\n";
3599 if (c.classMethods + n_value != 0)
3600 print_method_list64_t(c.classMethods + n_value, info, "");
3601
3602 outs() << " protocols ";
3603 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
3604 info, n_value, c.protocols);
3605 if (n_value != 0) {
3606 if (info->verbose && sym_name != nullptr)
3607 outs() << sym_name;
3608 else
3609 outs() << format("0x%" PRIx64, n_value);
3610 if (c.protocols != 0)
3611 outs() << " + " << format("0x%" PRIx64, c.protocols);
3612 } else
3613 outs() << format("0x%" PRIx64, c.protocols);
3614 outs() << "\n";
3615 if (c.protocols + n_value != 0)
3616 print_protocol_list64_t(c.protocols + n_value, info);
3617
3618 outs() << "instanceProperties ";
3619 sym_name =
3620 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
3621 S, info, n_value, c.instanceProperties);
3622 if (n_value != 0) {
3623 if (info->verbose && sym_name != nullptr)
3624 outs() << sym_name;
3625 else
3626 outs() << format("0x%" PRIx64, n_value);
3627 if (c.instanceProperties != 0)
3628 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
3629 } else
3630 outs() << format("0x%" PRIx64, c.instanceProperties);
3631 outs() << "\n";
3632 if (c.instanceProperties + n_value != 0)
3633 print_objc_property_list64(c.instanceProperties + n_value, info);
3634}
3635
3636static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
3637 uint32_t i, left, offset, xoffset;
3638 uint64_t p, n_value;
3639 struct message_ref64 mr;
3640 const char *name, *sym_name;
3641 const char *r;
3642 SectionRef xS;
3643
3644 if (S == SectionRef())
3645 return;
3646
3647 StringRef SectName;
3648 S.getName(SectName);
3649 DataRefImpl Ref = S.getRawDataRefImpl();
3650 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3651 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3652 offset = 0;
3653 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
3654 p = S.getAddress() + i;
3655 r = get_pointer_64(p, offset, left, S, info);
3656 if (r == nullptr)
3657 return;
3658 memset(&mr, '\0', sizeof(struct message_ref64));
3659 if (left < sizeof(struct message_ref64)) {
3660 memcpy(&mr, r, left);
3661 outs() << " (message_ref entends past the end of the section)\n";
3662 } else
3663 memcpy(&mr, r, sizeof(struct message_ref64));
3664 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3665 swapStruct(mr);
3666
3667 outs() << " imp ";
3668 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
3669 n_value, mr.imp);
3670 if (n_value != 0) {
3671 outs() << format("0x%" PRIx64, n_value) << " ";
3672 if (mr.imp != 0)
3673 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
3674 } else
3675 outs() << format("0x%" PRIx64, mr.imp) << " ";
3676 if (name != nullptr)
3677 outs() << " " << name;
3678 outs() << "\n";
3679
3680 outs() << " sel ";
3681 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
3682 info, n_value, mr.sel);
3683 if (n_value != 0) {
3684 if (info->verbose && sym_name != nullptr)
3685 outs() << sym_name;
3686 else
3687 outs() << format("0x%" PRIx64, n_value);
3688 if (mr.sel != 0)
3689 outs() << " + " << format("0x%" PRIx64, mr.sel);
3690 } else
3691 outs() << format("0x%" PRIx64, mr.sel);
3692 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
3693 if (name != nullptr)
3694 outs() << format(" %.*s", left, name);
3695 outs() << "\n";
3696
3697 offset += sizeof(struct message_ref64);
3698 }
3699}
3700
3701static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
3702 uint32_t left, offset, swift_version;
3703 uint64_t p;
3704 struct objc_image_info64 o;
3705 const char *r;
3706
3707 StringRef SectName;
3708 S.getName(SectName);
3709 DataRefImpl Ref = S.getRawDataRefImpl();
3710 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3711 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3712 p = S.getAddress();
3713 r = get_pointer_64(p, offset, left, S, info);
3714 if (r == nullptr)
3715 return;
3716 memset(&o, '\0', sizeof(struct objc_image_info64));
3717 if (left < sizeof(struct objc_image_info64)) {
3718 memcpy(&o, r, left);
3719 outs() << " (objc_image_info entends past the end of the section)\n";
3720 } else
3721 memcpy(&o, r, sizeof(struct objc_image_info64));
3722 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3723 swapStruct(o);
3724 outs() << " version " << o.version << "\n";
3725 outs() << " flags " << format("0x%" PRIx32, o.flags);
3726 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
3727 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
3728 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
3729 outs() << " OBJC_IMAGE_SUPPORTS_GC";
3730 swift_version = (o.flags >> 8) & 0xff;
3731 if (swift_version != 0) {
3732 if (swift_version == 1)
3733 outs() << " Swift 1.0";
3734 else if (swift_version == 2)
3735 outs() << " Swift 1.1";
3736 else
3737 outs() << " unknown future Swift version (" << swift_version << ")";
3738 }
3739 outs() << "\n";
3740}
3741
3742static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
3743 SymbolAddressMap AddrMap;
3744 if (verbose)
3745 CreateSymbolAddressMap(O, &AddrMap);
3746
3747 std::vector<SectionRef> Sections;
3748 for (const SectionRef &Section : O->sections()) {
3749 StringRef SectName;
3750 Section.getName(SectName);
3751 Sections.push_back(Section);
3752 }
3753
3754 struct DisassembleInfo info;
3755 // Set up the block of info used by the Symbolizer call backs.
3756 info.verbose = verbose;
3757 info.O = O;
3758 info.AddrMap = &AddrMap;
3759 info.Sections = &Sections;
3760 info.class_name = nullptr;
3761 info.selector_name = nullptr;
3762 info.method = nullptr;
3763 info.demangled_name = nullptr;
3764 info.bindtable = nullptr;
3765 info.adrp_addr = 0;
3766 info.adrp_inst = 0;
3767
3768 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
3769 if (CL != SectionRef()) {
3770 info.S = CL;
3771 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
3772 } else {
3773 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
3774 info.S = CL;
3775 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
3776 }
3777
3778 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
3779 if (CR != SectionRef()) {
3780 info.S = CR;
3781 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
3782 } else {
3783 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
3784 info.S = CR;
3785 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
3786 }
3787
3788 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
3789 if (SR != SectionRef()) {
3790 info.S = SR;
3791 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
3792 } else {
3793 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
3794 info.S = SR;
3795 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
3796 }
3797
3798 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
3799 if (CA != SectionRef()) {
3800 info.S = CA;
3801 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
3802 } else {
3803 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
3804 info.S = CA;
3805 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
3806 }
3807
3808 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
3809 if (PL != SectionRef()) {
3810 info.S = PL;
3811 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
3812 } else {
3813 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
3814 info.S = PL;
3815 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
3816 }
3817
3818 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
3819 if (MR != SectionRef()) {
3820 info.S = MR;
3821 print_message_refs64(MR, &info);
3822 } else {
3823 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
3824 info.S = MR;
3825 print_message_refs64(MR, &info);
3826 }
3827
3828 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
3829 if (II != SectionRef()) {
3830 info.S = II;
3831 print_image_info64(II, &info);
3832 } else {
3833 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
3834 info.S = II;
3835 print_image_info64(II, &info);
3836 }
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00003837
3838 if (info.bindtable != nullptr)
3839 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00003840}
3841
3842static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
3843 outs() << "Printing Objc2 32-bit MetaData not yet supported\n";
3844}
3845
3846static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
3847 const SectionRef S = get_section(O, "__OBJC", "__module_info");
3848 if (S != SectionRef()) {
3849 outs() << "Printing Objc1 32-bit MetaData not yet supported\n";
3850 return true;
3851 }
3852 return false;
3853}
3854
3855static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
3856 if (O->is64Bit())
3857 printObjc2_64bit_MetaData(O, verbose);
3858 else {
3859 MachO::mach_header H;
3860 H = O->getHeader();
3861 if (H.cputype == MachO::CPU_TYPE_ARM)
3862 printObjc2_32bit_MetaData(O, verbose);
3863 else {
3864 // This is the 32-bit non-arm cputype case. Which is normally
3865 // the first Objective-C ABI. But it may be the case of a
3866 // binary for the iOS simulator which is the second Objective-C
3867 // ABI. In that case printObjc1_32bit_MetaData() will determine that
3868 // and return false.
3869 if (printObjc1_32bit_MetaData(O, verbose) == false)
3870 printObjc2_32bit_MetaData(O, verbose);
3871 }
3872 }
3873}
3874
Kevin Enderbybf246f52014-09-24 23:08:22 +00003875// GuessLiteralPointer returns a string which for the item in the Mach-O file
3876// for the address passed in as ReferenceValue for printing as a comment with
3877// the instruction and also returns the corresponding type of that item
3878// indirectly through ReferenceType.
3879//
3880// If ReferenceValue is an address of literal cstring then a pointer to the
3881// cstring is returned and ReferenceType is set to
3882// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
3883//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003884// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
3885// Class ref that name is returned and the ReferenceType is set accordingly.
3886//
3887// Lastly, literals which are Symbol address in a literal pool are looked for
3888// and if found the symbol name is returned and ReferenceType is set to
3889// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
3890//
3891// If there is no item in the Mach-O file for the address passed in as
3892// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003893static const char *GuessLiteralPointer(uint64_t ReferenceValue,
3894 uint64_t ReferencePC,
3895 uint64_t *ReferenceType,
3896 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00003897 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00003898 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00003899 uint64_t sect_offset = ReferencePC - sect_addr;
3900 bool reloc_found = false;
3901 DataRefImpl Rel;
3902 MachO::any_relocation_info RE;
3903 bool isExtern = false;
3904 SymbolRef Symbol;
3905 for (const RelocationRef &Reloc : info->S.relocations()) {
3906 uint64_t RelocOffset;
3907 Reloc.getOffset(RelocOffset);
3908 if (RelocOffset == sect_offset) {
3909 Rel = Reloc.getRawDataRefImpl();
3910 RE = info->O->getRelocation(Rel);
3911 if (info->O->isRelocationScattered(RE))
3912 continue;
3913 isExtern = info->O->getPlainRelocationExternal(RE);
3914 if (isExtern) {
3915 symbol_iterator RelocSym = Reloc.getSymbol();
3916 Symbol = *RelocSym;
3917 }
3918 reloc_found = true;
3919 break;
3920 }
3921 }
3922 // If there is an external relocation entry for a symbol in a section
3923 // then used that symbol's value for the value of the reference.
3924 if (reloc_found && isExtern) {
3925 if (info->O->getAnyRelocationPCRel(RE)) {
3926 unsigned Type = info->O->getAnyRelocationType(RE);
3927 if (Type == MachO::X86_64_RELOC_SIGNED) {
3928 Symbol.getAddress(ReferenceValue);
3929 }
3930 }
3931 }
3932
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003933 // Look for literals such as Objective-C CFStrings refs, Selector refs,
3934 // Message refs and Class refs.
3935 bool classref, selref, msgref, cfstring;
3936 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
3937 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00003938 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003939 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
3940 // And the pointer_value in that section is typically zero as it will be
3941 // set by dyld as part of the "bind information".
3942 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
3943 if (name != nullptr) {
3944 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003945 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003946 if (class_name != nullptr && class_name[1] == '_' &&
3947 class_name[2] != '\0') {
3948 info->class_name = class_name + 2;
3949 return name;
3950 }
3951 }
3952 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00003953
David Blaikie33dd45d02015-03-23 18:39:02 +00003954 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003955 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
3956 const char *name =
3957 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
3958 if (name != nullptr)
3959 info->class_name = name;
3960 else
3961 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00003962 return name;
3963 }
3964
David Blaikie33dd45d02015-03-23 18:39:02 +00003965 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003966 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
3967 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
3968 return name;
3969 }
3970
David Blaikie33dd45d02015-03-23 18:39:02 +00003971 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003972 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
3973
3974 if (pointer_value != 0)
3975 ReferenceValue = pointer_value;
3976
3977 const char *name = GuessCstringPointer(ReferenceValue, info);
3978 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00003979 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003980 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
3981 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00003982 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003983 info->class_name = nullptr;
3984 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
3985 info->selector_name = name;
3986 } else
3987 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
3988 return name;
3989 }
3990
3991 // Lastly look for an indirect symbol with this ReferenceValue which is in
3992 // a literal pool. If found return that symbol name.
3993 name = GuessIndirectSymbol(ReferenceValue, info);
3994 if (name) {
3995 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
3996 return name;
3997 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00003998
3999 return nullptr;
4000}
4001
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004002// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00004003// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004004// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
4005// is created and returns the symbol name that matches the ReferenceValue or
4006// nullptr if none. The ReferenceType is passed in for the IN type of
4007// reference the instruction is making from the values in defined in the header
4008// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
4009// Out type and the ReferenceName will also be set which is added as a comment
4010// to the disassembled instruction.
4011//
Kevin Enderby04bf6932014-10-28 23:39:46 +00004012#if HAVE_CXXABI_H
4013// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004014// returned through ReferenceName and ReferenceType is set to
4015// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00004016#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004017//
4018// When this is called to get a symbol name for a branch target then the
4019// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
4020// SymbolValue will be looked for in the indirect symbol table to determine if
4021// it is an address for a symbol stub. If so then the symbol name for that
4022// stub is returned indirectly through ReferenceName and then ReferenceType is
4023// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
4024//
Kevin Enderbybf246f52014-09-24 23:08:22 +00004025// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004026// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
4027// SymbolValue is checked to be an address of literal pointer, symbol pointer,
4028// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004029// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00004030static const char *SymbolizerSymbolLookUp(void *DisInfo,
4031 uint64_t ReferenceValue,
4032 uint64_t *ReferenceType,
4033 uint64_t ReferencePC,
4034 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004035 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00004036 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00004037 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00004038 *ReferenceName = nullptr;
4039 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004040 return nullptr;
4041 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00004042
Kevin Enderbyf6d25852015-01-31 00:37:11 +00004043 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00004044
Kevin Enderby85974882014-09-26 22:20:44 +00004045 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
4046 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00004047 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004048 method_reference(info, ReferenceType, ReferenceName);
4049 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
4050 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
4051 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00004052#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004053 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00004054 if (info->demangled_name != nullptr)
4055 free(info->demangled_name);
4056 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004057 info->demangled_name =
4058 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00004059 if (info->demangled_name != nullptr) {
4060 *ReferenceName = info->demangled_name;
4061 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
4062 } else
4063 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4064 } else
4065#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004066 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4067 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
4068 *ReferenceName =
4069 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00004070 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004071 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00004072 else
4073 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004074 // If this is arm64 and the reference is an adrp instruction save the
4075 // instruction, passed in ReferenceValue and the address of the instruction
4076 // for use later if we see and add immediate instruction.
4077 } else if (info->O->getArch() == Triple::aarch64 &&
4078 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
4079 info->adrp_inst = ReferenceValue;
4080 info->adrp_addr = ReferencePC;
4081 SymbolName = nullptr;
4082 *ReferenceName = nullptr;
4083 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4084 // If this is arm64 and reference is an add immediate instruction and we
4085 // have
4086 // seen an adrp instruction just before it and the adrp's Xd register
4087 // matches
4088 // this add's Xn register reconstruct the value being referenced and look to
4089 // see if it is a literal pointer. Note the add immediate instruction is
4090 // passed in ReferenceValue.
4091 } else if (info->O->getArch() == Triple::aarch64 &&
4092 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
4093 ReferencePC - 4 == info->adrp_addr &&
4094 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
4095 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
4096 uint32_t addxri_inst;
4097 uint64_t adrp_imm, addxri_imm;
4098
4099 adrp_imm =
4100 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
4101 if (info->adrp_inst & 0x0200000)
4102 adrp_imm |= 0xfffffffffc000000LL;
4103
4104 addxri_inst = ReferenceValue;
4105 addxri_imm = (addxri_inst >> 10) & 0xfff;
4106 if (((addxri_inst >> 22) & 0x3) == 1)
4107 addxri_imm <<= 12;
4108
4109 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
4110 (adrp_imm << 12) + addxri_imm;
4111
4112 *ReferenceName =
4113 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
4114 if (*ReferenceName == nullptr)
4115 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4116 // If this is arm64 and the reference is a load register instruction and we
4117 // have seen an adrp instruction just before it and the adrp's Xd register
4118 // matches this add's Xn register reconstruct the value being referenced and
4119 // look to see if it is a literal pointer. Note the load register
4120 // instruction is passed in ReferenceValue.
4121 } else if (info->O->getArch() == Triple::aarch64 &&
4122 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
4123 ReferencePC - 4 == info->adrp_addr &&
4124 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
4125 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
4126 uint32_t ldrxui_inst;
4127 uint64_t adrp_imm, ldrxui_imm;
4128
4129 adrp_imm =
4130 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
4131 if (info->adrp_inst & 0x0200000)
4132 adrp_imm |= 0xfffffffffc000000LL;
4133
4134 ldrxui_inst = ReferenceValue;
4135 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
4136
4137 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
4138 (adrp_imm << 12) + (ldrxui_imm << 3);
4139
4140 *ReferenceName =
4141 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
4142 if (*ReferenceName == nullptr)
4143 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4144 }
4145 // If this arm64 and is an load register (PC-relative) instruction the
4146 // ReferenceValue is the PC plus the immediate value.
4147 else if (info->O->getArch() == Triple::aarch64 &&
4148 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
4149 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
4150 *ReferenceName =
4151 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
4152 if (*ReferenceName == nullptr)
4153 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00004154 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00004155#if HAVE_CXXABI_H
4156 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
4157 if (info->demangled_name != nullptr)
4158 free(info->demangled_name);
4159 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004160 info->demangled_name =
4161 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00004162 if (info->demangled_name != nullptr) {
4163 *ReferenceName = info->demangled_name;
4164 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
4165 }
4166 }
4167#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004168 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00004169 *ReferenceName = nullptr;
4170 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4171 }
4172
4173 return SymbolName;
4174}
4175
Kevin Enderbybf246f52014-09-24 23:08:22 +00004176/// \brief Emits the comments that are stored in the CommentStream.
4177/// Each comment in the CommentStream must end with a newline.
4178static void emitComments(raw_svector_ostream &CommentStream,
4179 SmallString<128> &CommentsToEmit,
4180 formatted_raw_ostream &FormattedOS,
4181 const MCAsmInfo &MAI) {
4182 // Flush the stream before taking its content.
4183 CommentStream.flush();
4184 StringRef Comments = CommentsToEmit.str();
4185 // Get the default information for printing a comment.
4186 const char *CommentBegin = MAI.getCommentString();
4187 unsigned CommentColumn = MAI.getCommentColumn();
4188 bool IsFirst = true;
4189 while (!Comments.empty()) {
4190 if (!IsFirst)
4191 FormattedOS << '\n';
4192 // Emit a line of comments.
4193 FormattedOS.PadToColumn(CommentColumn);
4194 size_t Position = Comments.find('\n');
4195 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
4196 // Move after the newline character.
4197 Comments = Comments.substr(Position + 1);
4198 IsFirst = false;
4199 }
4200 FormattedOS.flush();
4201
4202 // Tell the comment stream that the vector changed underneath it.
4203 CommentsToEmit.clear();
4204 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004205}
4206
Kevin Enderby95df54c2015-02-04 01:01:38 +00004207static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
4208 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004209 const char *McpuDefault = nullptr;
4210 const Target *ThumbTarget = nullptr;
4211 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004212 if (!TheTarget) {
4213 // GetTarget prints out stuff.
4214 return;
4215 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004216 if (MCPU.empty() && McpuDefault)
4217 MCPU = McpuDefault;
4218
Ahmed Charles56440fd2014-03-06 05:51:42 +00004219 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004220 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004221 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004222 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004223
Kevin Enderbyc9595622014-08-06 23:24:41 +00004224 // Package up features to be passed to target/subtarget
4225 std::string FeaturesStr;
4226 if (MAttrs.size()) {
4227 SubtargetFeatures Features;
4228 for (unsigned i = 0; i != MAttrs.size(); ++i)
4229 Features.AddFeature(MAttrs[i]);
4230 FeaturesStr = Features.getString();
4231 }
4232
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004233 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00004234 std::unique_ptr<const MCRegisterInfo> MRI(
4235 TheTarget->createMCRegInfo(TripleName));
4236 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00004237 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00004238 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00004239 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00004240 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004241 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004242 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004243 std::unique_ptr<MCSymbolizer> Symbolizer;
4244 struct DisassembleInfo SymbolizerInfo;
4245 std::unique_ptr<MCRelocationInfo> RelInfo(
4246 TheTarget->createMCRelocationInfo(TripleName, Ctx));
4247 if (RelInfo) {
4248 Symbolizer.reset(TheTarget->createMCSymbolizer(
4249 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00004250 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004251 DisAsm->setSymbolizer(std::move(Symbolizer));
4252 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004253 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00004254 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +00004255 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00004256 // Set the display preference for hex vs. decimal immediates.
4257 IP->setPrintImmHex(PrintImmHex);
4258 // Comment stream and backing vector.
4259 SmallString<128> CommentsToEmit;
4260 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00004261 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
4262 // if it is done then arm64 comments for string literals don't get printed
4263 // and some constant get printed instead and not setting it causes intel
4264 // (32-bit and 64-bit) comments printed with different spacing before the
4265 // comment causing different diffs with the 'C' disassembler library API.
4266 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004267
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004268 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00004269 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004270 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004271 return;
4272 }
4273
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004274 // Set up thumb disassembler.
4275 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
4276 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
4277 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004278 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004279 std::unique_ptr<MCInstPrinter> ThumbIP;
4280 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004281 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
4282 struct DisassembleInfo ThumbSymbolizerInfo;
4283 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004284 if (ThumbTarget) {
4285 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
4286 ThumbAsmInfo.reset(
4287 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
4288 ThumbSTI.reset(
4289 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
4290 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
4291 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00004292 MCContext *PtrThumbCtx = ThumbCtx.get();
4293 ThumbRelInfo.reset(
4294 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
4295 if (ThumbRelInfo) {
4296 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
4297 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00004298 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00004299 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
4300 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004301 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
4302 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +00004303 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
4304 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00004305 // Set the display preference for hex vs. decimal immediates.
4306 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004307 }
4308
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004309 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004310 errs() << "error: couldn't initialize disassembler for target "
4311 << ThumbTripleName << '\n';
4312 return;
4313 }
4314
Charles Davis8bdfafd2013-09-01 04:28:48 +00004315 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004316
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004317 // FIXME: Using the -cfg command line option, this code used to be able to
4318 // annotate relocations with the referenced symbol's name, and if this was
4319 // inside a __[cf]string section, the data it points to. This is now replaced
4320 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00004321 std::vector<SectionRef> Sections;
4322 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004323 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00004324 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004325
Kevin Enderby273ae012013-06-06 17:20:50 +00004326 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
4327 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004328
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004329 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00004330 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004331
Kevin Enderby273ae012013-06-06 17:20:50 +00004332 // Build a data in code table that is sorted on by the address of each entry.
4333 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00004334 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00004335 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00004336 else
4337 BaseAddress = BaseSegmentAddress;
4338 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00004339 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00004340 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00004341 uint32_t Offset;
4342 DI->getOffset(Offset);
4343 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
4344 }
4345 array_pod_sort(Dices.begin(), Dices.end());
4346
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004347#ifndef NDEBUG
4348 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
4349#else
4350 raw_ostream &DebugOut = nulls();
4351#endif
4352
Ahmed Charles56440fd2014-03-06 05:51:42 +00004353 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00004354 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00004355 // Try to find debug info and set up the DIContext for it.
4356 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00004357 // A separate DSym file path was specified, parse it as a macho file,
4358 // get the sections and supply it to the section name parsing machinery.
4359 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00004360 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00004361 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00004362 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00004363 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00004364 return;
4365 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00004366 DbgObj =
4367 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
4368 .get()
4369 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00004370 }
4371
Eric Christopher7370b552012-11-12 21:40:38 +00004372 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00004373 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00004374 }
4375
Kevin Enderby95df54c2015-02-04 01:01:38 +00004376 if (DumpSections.size() == 0)
4377 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00004378
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004379 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00004380 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00004381 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
4382 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004383
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00004384 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004385
Rafael Espindolab0f76a42013-04-05 15:15:22 +00004386 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00004387 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00004388 continue;
4389
Rafael Espindola7fc5b872014-11-12 02:04:27 +00004390 StringRef BytesStr;
4391 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00004392 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
4393 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00004394 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00004395
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004396 bool symbolTableWorked = false;
4397
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004398 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00004399 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
4400 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00004401 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00004402 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00004403 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00004404 RelocOffset -= SectionAddress;
4405
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00004406 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00004407
Rafael Espindola806f0062013-06-05 01:33:53 +00004408 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004409 }
4410 array_pod_sort(Relocs.begin(), Relocs.end());
4411
Kevin Enderbybf246f52014-09-24 23:08:22 +00004412 // Create a map of symbol addresses to symbol names for use by
4413 // the SymbolizerSymbolLookUp() routine.
4414 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00004415 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00004416 for (const SymbolRef &Symbol : MachOOF->symbols()) {
4417 SymbolRef::Type ST;
4418 Symbol.getType(ST);
4419 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
4420 ST == SymbolRef::ST_Other) {
4421 uint64_t Address;
4422 Symbol.getAddress(Address);
4423 StringRef SymName;
4424 Symbol.getName(SymName);
4425 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00004426 if (!DisSymName.empty() && DisSymName == SymName)
4427 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00004428 }
4429 }
David Blaikie33dd45d02015-03-23 18:39:02 +00004430 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00004431 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
4432 return;
4433 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004434 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00004435 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004436 SymbolizerInfo.O = MachOOF;
4437 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00004438 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004439 SymbolizerInfo.Sections = &Sections;
4440 SymbolizerInfo.class_name = nullptr;
4441 SymbolizerInfo.selector_name = nullptr;
4442 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00004443 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00004444 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00004445 SymbolizerInfo.adrp_addr = 0;
4446 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004447 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00004448 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004449 ThumbSymbolizerInfo.O = MachOOF;
4450 ThumbSymbolizerInfo.S = Sections[SectIdx];
4451 ThumbSymbolizerInfo.AddrMap = &AddrMap;
4452 ThumbSymbolizerInfo.Sections = &Sections;
4453 ThumbSymbolizerInfo.class_name = nullptr;
4454 ThumbSymbolizerInfo.selector_name = nullptr;
4455 ThumbSymbolizerInfo.method = nullptr;
4456 ThumbSymbolizerInfo.demangled_name = nullptr;
4457 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00004458 ThumbSymbolizerInfo.adrp_addr = 0;
4459 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004460
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004461 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004462 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00004463 StringRef SymName;
4464 Symbols[SymIdx].getName(SymName);
4465
4466 SymbolRef::Type ST;
4467 Symbols[SymIdx].getType(ST);
4468 if (ST != SymbolRef::ST_Function)
4469 continue;
4470
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004471 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00004472 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00004473 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004474 continue;
4475
Kevin Enderby6a221752015-03-17 17:10:57 +00004476 // If we are only disassembling one symbol see if this is that symbol.
4477 if (!DisSymName.empty() && DisSymName != SymName)
4478 continue;
4479
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004480 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00004481 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00004482 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00004483 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00004484 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00004485
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004486 // Stop disassembling either at the beginning of the next symbol or at
4487 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00004488 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00004489 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004490 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00004491 while (Symbols.size() > NextSymIdx) {
4492 SymbolRef::Type NextSymType;
4493 Symbols[NextSymIdx].getType(NextSymType);
4494 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00004495 containsNextSym =
4496 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00004497 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00004498 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00004499 break;
4500 }
4501 ++NextSymIdx;
4502 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004503
Rafael Espindola80291272014-10-08 15:28:58 +00004504 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004505 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00004506 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004507
4508 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00004509
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004510 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
4511 bool isThumb =
4512 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
4513
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004514 outs() << SymName << ":\n";
4515 DILineInfo lastLine;
4516 for (uint64_t Index = Start; Index < End; Index += Size) {
4517 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00004518
Kevin Enderbybf246f52014-09-24 23:08:22 +00004519 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00004520 if (!NoLeadingAddr) {
4521 if (FullLeadingAddr) {
4522 if (MachOOF->is64Bit())
4523 outs() << format("%016" PRIx64, PC);
4524 else
4525 outs() << format("%08" PRIx64, PC);
4526 } else {
4527 outs() << format("%8" PRIx64 ":", PC);
4528 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00004529 }
4530 if (!NoShowRawInsn)
4531 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00004532
4533 // Check the data in code table here to see if this is data not an
4534 // instruction to be disassembled.
4535 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00004536 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004537 dice_table_iterator DTI =
4538 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
4539 compareDiceTableEntries);
4540 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00004541 uint16_t Length;
4542 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00004543 uint16_t Kind;
4544 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00004545 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00004546 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
4547 (PC == (DTI->first + Length - 1)) && (Length & 1))
4548 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00004549 continue;
4550 }
4551
Kevin Enderbybf246f52014-09-24 23:08:22 +00004552 SmallVector<char, 64> AnnotationsBytes;
4553 raw_svector_ostream Annotations(AnnotationsBytes);
4554
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004555 bool gotInst;
4556 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00004557 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004558 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004559 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00004560 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00004561 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004562 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00004563 if (!NoShowRawInsn) {
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00004564 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size));
Kevin Enderbybf246f52014-09-24 23:08:22 +00004565 }
4566 formatted_raw_ostream FormattedOS(outs());
4567 Annotations.flush();
4568 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004569 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00004570 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004571 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00004572 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00004573 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00004574
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004575 // Print debug info.
4576 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004577 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004578 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00004579 if (dli != lastLine && dli.Line != 0)
4580 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
4581 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004582 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004583 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004584 outs() << "\n";
4585 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004586 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004587 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004588 outs() << format("\t.byte 0x%02x #bad opcode\n",
4589 *(Bytes.data() + Index) & 0xff);
4590 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004591 } else if (Arch == Triple::aarch64) {
4592 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
4593 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
4594 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
4595 (*(Bytes.data() + Index + 3) & 0xff) << 24;
4596 outs() << format("\t.long\t0x%08x\n", opcode);
4597 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004598 } else {
4599 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
4600 if (Size == 0)
4601 Size = 1; // skip illegible bytes
4602 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004603 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004604 }
4605 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004606 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00004607 // Reading the symbol table didn't work, disassemble the whole section.
4608 uint64_t SectAddress = Sections[SectIdx].getAddress();
4609 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00004610 uint64_t InstSize;
4611 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00004612 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00004613
Kevin Enderbybf246f52014-09-24 23:08:22 +00004614 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00004615 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
4616 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00004617 if (!NoLeadingAddr) {
4618 if (FullLeadingAddr) {
4619 if (MachOOF->is64Bit())
4620 outs() << format("%016" PRIx64, PC);
4621 else
4622 outs() << format("%08" PRIx64, PC);
4623 } else {
4624 outs() << format("%8" PRIx64 ":", PC);
4625 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00004626 }
4627 if (!NoShowRawInsn) {
4628 outs() << "\t";
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00004629 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize));
Kevin Enderbybf246f52014-09-24 23:08:22 +00004630 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00004631 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00004632 outs() << "\n";
4633 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004634 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004635 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004636 outs() << format("\t.byte 0x%02x #bad opcode\n",
4637 *(Bytes.data() + Index) & 0xff);
4638 InstSize = 1; // skip exactly one illegible byte and move on.
4639 } else {
4640 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
4641 if (InstSize == 0)
4642 InstSize = 1; // skip illegible bytes
4643 }
Bill Wendling4e68e062012-07-19 00:17:40 +00004644 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00004645 }
4646 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00004647 // The TripleName's need to be reset if we are called again for a different
4648 // archtecture.
4649 TripleName = "";
4650 ThumbTripleName = "";
4651
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004652 if (SymbolizerInfo.method != nullptr)
4653 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00004654 if (SymbolizerInfo.demangled_name != nullptr)
4655 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00004656 if (SymbolizerInfo.bindtable != nullptr)
4657 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004658 if (ThumbSymbolizerInfo.method != nullptr)
4659 free(ThumbSymbolizerInfo.method);
4660 if (ThumbSymbolizerInfo.demangled_name != nullptr)
4661 free(ThumbSymbolizerInfo.demangled_name);
4662 if (ThumbSymbolizerInfo.bindtable != nullptr)
4663 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004664 }
4665}
Tim Northover4bd286a2014-08-01 13:07:19 +00004666
Tim Northover39c70bb2014-08-12 11:52:59 +00004667//===----------------------------------------------------------------------===//
4668// __compact_unwind section dumping
4669//===----------------------------------------------------------------------===//
4670
Tim Northover4bd286a2014-08-01 13:07:19 +00004671namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00004672
4673template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004674 using llvm::support::little;
4675 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00004676
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004677 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
4678 Buf += sizeof(T);
4679 return Val;
4680}
Tim Northover39c70bb2014-08-12 11:52:59 +00004681
Tim Northover4bd286a2014-08-01 13:07:19 +00004682struct CompactUnwindEntry {
4683 uint32_t OffsetInSection;
4684
4685 uint64_t FunctionAddr;
4686 uint32_t Length;
4687 uint32_t CompactEncoding;
4688 uint64_t PersonalityAddr;
4689 uint64_t LSDAAddr;
4690
4691 RelocationRef FunctionReloc;
4692 RelocationRef PersonalityReloc;
4693 RelocationRef LSDAReloc;
4694
4695 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004696 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00004697 if (Is64)
4698 read<uint64_t>(Contents.data() + Offset);
4699 else
4700 read<uint32_t>(Contents.data() + Offset);
4701 }
4702
4703private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004704 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00004705 FunctionAddr = readNext<UIntPtr>(Buf);
4706 Length = readNext<uint32_t>(Buf);
4707 CompactEncoding = readNext<uint32_t>(Buf);
4708 PersonalityAddr = readNext<UIntPtr>(Buf);
4709 LSDAAddr = readNext<UIntPtr>(Buf);
4710 }
4711};
4712}
4713
4714/// Given a relocation from __compact_unwind, consisting of the RelocationRef
4715/// and data being relocated, determine the best base Name and Addend to use for
4716/// display purposes.
4717///
4718/// 1. An Extern relocation will directly reference a symbol (and the data is
4719/// then already an addend), so use that.
4720/// 2. Otherwise the data is an offset in the object file's layout; try to find
4721// a symbol before it in the same section, and use the offset from there.
4722/// 3. Finally, if all that fails, fall back to an offset from the start of the
4723/// referenced section.
4724static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
4725 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004726 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00004727 StringRef &Name, uint64_t &Addend) {
4728 if (Reloc.getSymbol() != Obj->symbol_end()) {
4729 Reloc.getSymbol()->getName(Name);
4730 Addend = Addr;
4731 return;
4732 }
4733
4734 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
4735 SectionRef RelocSection = Obj->getRelocationSection(RE);
4736
Rafael Espindola80291272014-10-08 15:28:58 +00004737 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00004738
4739 auto Sym = Symbols.upper_bound(Addr);
4740 if (Sym == Symbols.begin()) {
4741 // The first symbol in the object is after this reference, the best we can
4742 // do is section-relative notation.
4743 RelocSection.getName(Name);
4744 Addend = Addr - SectionAddr;
4745 return;
4746 }
4747
4748 // Go back one so that SymbolAddress <= Addr.
4749 --Sym;
4750
4751 section_iterator SymSection = Obj->section_end();
4752 Sym->second.getSection(SymSection);
4753 if (RelocSection == *SymSection) {
4754 // There's a valid symbol in the same section before this reference.
4755 Sym->second.getName(Name);
4756 Addend = Addr - Sym->first;
4757 return;
4758 }
4759
4760 // There is a symbol before this reference, but it's in a different
4761 // section. Probably not helpful to mention it, so use the section name.
4762 RelocSection.getName(Name);
4763 Addend = Addr - SectionAddr;
4764}
4765
4766static void printUnwindRelocDest(const MachOObjectFile *Obj,
4767 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004768 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00004769 StringRef Name;
4770 uint64_t Addend;
4771
Tim Northover0b0add52014-09-09 10:45:06 +00004772 if (!Reloc.getObjectFile())
4773 return;
4774
Tim Northover4bd286a2014-08-01 13:07:19 +00004775 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
4776
4777 outs() << Name;
4778 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00004779 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00004780}
4781
4782static void
4783printMachOCompactUnwindSection(const MachOObjectFile *Obj,
4784 std::map<uint64_t, SymbolRef> &Symbols,
4785 const SectionRef &CompactUnwind) {
4786
4787 assert(Obj->isLittleEndian() &&
4788 "There should not be a big-endian .o with __compact_unwind");
4789
4790 bool Is64 = Obj->is64Bit();
4791 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
4792 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
4793
4794 StringRef Contents;
4795 CompactUnwind.getContents(Contents);
4796
4797 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
4798
4799 // First populate the initial raw offsets, encodings and so on from the entry.
4800 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
4801 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
4802 CompactUnwinds.push_back(Entry);
4803 }
4804
4805 // Next we need to look at the relocations to find out what objects are
4806 // actually being referred to.
4807 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
4808 uint64_t RelocAddress;
4809 Reloc.getOffset(RelocAddress);
4810
4811 uint32_t EntryIdx = RelocAddress / EntrySize;
4812 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
4813 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
4814
4815 if (OffsetInEntry == 0)
4816 Entry.FunctionReloc = Reloc;
4817 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
4818 Entry.PersonalityReloc = Reloc;
4819 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
4820 Entry.LSDAReloc = Reloc;
4821 else
4822 llvm_unreachable("Unexpected relocation in __compact_unwind section");
4823 }
4824
4825 // Finally, we're ready to print the data we've gathered.
4826 outs() << "Contents of __compact_unwind section:\n";
4827 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00004828 outs() << " Entry at offset "
4829 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00004830
4831 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004832 outs() << " start: " << format("0x%" PRIx64,
4833 Entry.FunctionAddr) << ' ';
4834 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00004835 outs() << '\n';
4836
4837 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004838 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
4839 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00004840 // 3. The 32-bit compact encoding.
4841 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00004842 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00004843
4844 // 4. The personality function, if present.
4845 if (Entry.PersonalityReloc.getObjectFile()) {
4846 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00004847 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00004848 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
4849 Entry.PersonalityAddr);
4850 outs() << '\n';
4851 }
4852
4853 // 5. This entry's language-specific data area.
4854 if (Entry.LSDAReloc.getObjectFile()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004855 outs() << " LSDA: " << format("0x%" PRIx64,
4856 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00004857 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
4858 outs() << '\n';
4859 }
4860 }
4861}
4862
Tim Northover39c70bb2014-08-12 11:52:59 +00004863//===----------------------------------------------------------------------===//
4864// __unwind_info section dumping
4865//===----------------------------------------------------------------------===//
4866
4867static void printRegularSecondLevelUnwindPage(const char *PageStart) {
4868 const char *Pos = PageStart;
4869 uint32_t Kind = readNext<uint32_t>(Pos);
4870 (void)Kind;
4871 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
4872
4873 uint16_t EntriesStart = readNext<uint16_t>(Pos);
4874 uint16_t NumEntries = readNext<uint16_t>(Pos);
4875
4876 Pos = PageStart + EntriesStart;
4877 for (unsigned i = 0; i < NumEntries; ++i) {
4878 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
4879 uint32_t Encoding = readNext<uint32_t>(Pos);
4880
4881 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004882 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
4883 << ", "
4884 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00004885 }
4886}
4887
4888static void printCompressedSecondLevelUnwindPage(
4889 const char *PageStart, uint32_t FunctionBase,
4890 const SmallVectorImpl<uint32_t> &CommonEncodings) {
4891 const char *Pos = PageStart;
4892 uint32_t Kind = readNext<uint32_t>(Pos);
4893 (void)Kind;
4894 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
4895
4896 uint16_t EntriesStart = readNext<uint16_t>(Pos);
4897 uint16_t NumEntries = readNext<uint16_t>(Pos);
4898
4899 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
4900 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00004901 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
4902 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00004903
4904 Pos = PageStart + EntriesStart;
4905 for (unsigned i = 0; i < NumEntries; ++i) {
4906 uint32_t Entry = readNext<uint32_t>(Pos);
4907 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
4908 uint32_t EncodingIdx = Entry >> 24;
4909
4910 uint32_t Encoding;
4911 if (EncodingIdx < CommonEncodings.size())
4912 Encoding = CommonEncodings[EncodingIdx];
4913 else
4914 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
4915
4916 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004917 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
4918 << ", "
4919 << "encoding[" << EncodingIdx
4920 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00004921 }
4922}
4923
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004924static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
4925 std::map<uint64_t, SymbolRef> &Symbols,
4926 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00004927
4928 assert(Obj->isLittleEndian() &&
4929 "There should not be a big-endian .o with __unwind_info");
4930
4931 outs() << "Contents of __unwind_info section:\n";
4932
4933 StringRef Contents;
4934 UnwindInfo.getContents(Contents);
4935 const char *Pos = Contents.data();
4936
4937 //===----------------------------------
4938 // Section header
4939 //===----------------------------------
4940
4941 uint32_t Version = readNext<uint32_t>(Pos);
4942 outs() << " Version: "
4943 << format("0x%" PRIx32, Version) << '\n';
4944 assert(Version == 1 && "only understand version 1");
4945
4946 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
4947 outs() << " Common encodings array section offset: "
4948 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
4949 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
4950 outs() << " Number of common encodings in array: "
4951 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
4952
4953 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
4954 outs() << " Personality function array section offset: "
4955 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
4956 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
4957 outs() << " Number of personality functions in array: "
4958 << format("0x%" PRIx32, NumPersonalities) << '\n';
4959
4960 uint32_t IndicesStart = readNext<uint32_t>(Pos);
4961 outs() << " Index array section offset: "
4962 << format("0x%" PRIx32, IndicesStart) << '\n';
4963 uint32_t NumIndices = readNext<uint32_t>(Pos);
4964 outs() << " Number of indices in array: "
4965 << format("0x%" PRIx32, NumIndices) << '\n';
4966
4967 //===----------------------------------
4968 // A shared list of common encodings
4969 //===----------------------------------
4970
4971 // These occupy indices in the range [0, N] whenever an encoding is referenced
4972 // from a compressed 2nd level index table. In practice the linker only
4973 // creates ~128 of these, so that indices are available to embed encodings in
4974 // the 2nd level index.
4975
4976 SmallVector<uint32_t, 64> CommonEncodings;
4977 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
4978 Pos = Contents.data() + CommonEncodingsStart;
4979 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
4980 uint32_t Encoding = readNext<uint32_t>(Pos);
4981 CommonEncodings.push_back(Encoding);
4982
4983 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
4984 << '\n';
4985 }
4986
Tim Northover39c70bb2014-08-12 11:52:59 +00004987 //===----------------------------------
4988 // Personality functions used in this executable
4989 //===----------------------------------
4990
4991 // There should be only a handful of these (one per source language,
4992 // roughly). Particularly since they only get 2 bits in the compact encoding.
4993
4994 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
4995 Pos = Contents.data() + PersonalitiesStart;
4996 for (unsigned i = 0; i < NumPersonalities; ++i) {
4997 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
4998 outs() << " personality[" << i + 1
4999 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
5000 }
5001
5002 //===----------------------------------
5003 // The level 1 index entries
5004 //===----------------------------------
5005
5006 // These specify an approximate place to start searching for the more detailed
5007 // information, sorted by PC.
5008
5009 struct IndexEntry {
5010 uint32_t FunctionOffset;
5011 uint32_t SecondLevelPageStart;
5012 uint32_t LSDAStart;
5013 };
5014
5015 SmallVector<IndexEntry, 4> IndexEntries;
5016
5017 outs() << " Top level indices: (count = " << NumIndices << ")\n";
5018 Pos = Contents.data() + IndicesStart;
5019 for (unsigned i = 0; i < NumIndices; ++i) {
5020 IndexEntry Entry;
5021
5022 Entry.FunctionOffset = readNext<uint32_t>(Pos);
5023 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
5024 Entry.LSDAStart = readNext<uint32_t>(Pos);
5025 IndexEntries.push_back(Entry);
5026
5027 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005028 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
5029 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00005030 << "2nd level page offset="
5031 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005032 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00005033 }
5034
Tim Northover39c70bb2014-08-12 11:52:59 +00005035 //===----------------------------------
5036 // Next come the LSDA tables
5037 //===----------------------------------
5038
5039 // The LSDA layout is rather implicit: it's a contiguous array of entries from
5040 // the first top-level index's LSDAOffset to the last (sentinel).
5041
5042 outs() << " LSDA descriptors:\n";
5043 Pos = Contents.data() + IndexEntries[0].LSDAStart;
5044 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
5045 (2 * sizeof(uint32_t));
5046 for (int i = 0; i < NumLSDAs; ++i) {
5047 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
5048 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
5049 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005050 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
5051 << ", "
5052 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00005053 }
5054
5055 //===----------------------------------
5056 // Finally, the 2nd level indices
5057 //===----------------------------------
5058
5059 // Generally these are 4K in size, and have 2 possible forms:
5060 // + Regular stores up to 511 entries with disparate encodings
5061 // + Compressed stores up to 1021 entries if few enough compact encoding
5062 // values are used.
5063 outs() << " Second level indices:\n";
5064 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
5065 // The final sentinel top-level index has no associated 2nd level page
5066 if (IndexEntries[i].SecondLevelPageStart == 0)
5067 break;
5068
5069 outs() << " Second level index[" << i << "]: "
5070 << "offset in section="
5071 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
5072 << ", "
5073 << "base function offset="
5074 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
5075
5076 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00005077 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00005078 if (Kind == 2)
5079 printRegularSecondLevelUnwindPage(Pos);
5080 else if (Kind == 3)
5081 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
5082 CommonEncodings);
5083 else
5084 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00005085 }
5086}
5087
Tim Northover4bd286a2014-08-01 13:07:19 +00005088void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
5089 std::map<uint64_t, SymbolRef> Symbols;
5090 for (const SymbolRef &SymRef : Obj->symbols()) {
5091 // Discard any undefined or absolute symbols. They're not going to take part
5092 // in the convenience lookup for unwind info and just take up resources.
5093 section_iterator Section = Obj->section_end();
5094 SymRef.getSection(Section);
5095 if (Section == Obj->section_end())
5096 continue;
5097
5098 uint64_t Addr;
5099 SymRef.getAddress(Addr);
5100 Symbols.insert(std::make_pair(Addr, SymRef));
5101 }
5102
5103 for (const SectionRef &Section : Obj->sections()) {
5104 StringRef SectName;
5105 Section.getName(SectName);
5106 if (SectName == "__compact_unwind")
5107 printMachOCompactUnwindSection(Obj, Symbols, Section);
5108 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00005109 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00005110 else if (SectName == "__eh_frame")
5111 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00005112 }
5113}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005114
5115static void PrintMachHeader(uint32_t magic, uint32_t cputype,
5116 uint32_t cpusubtype, uint32_t filetype,
5117 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
5118 bool verbose) {
5119 outs() << "Mach header\n";
5120 outs() << " magic cputype cpusubtype caps filetype ncmds "
5121 "sizeofcmds flags\n";
5122 if (verbose) {
5123 if (magic == MachO::MH_MAGIC)
5124 outs() << " MH_MAGIC";
5125 else if (magic == MachO::MH_MAGIC_64)
5126 outs() << "MH_MAGIC_64";
5127 else
5128 outs() << format(" 0x%08" PRIx32, magic);
5129 switch (cputype) {
5130 case MachO::CPU_TYPE_I386:
5131 outs() << " I386";
5132 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5133 case MachO::CPU_SUBTYPE_I386_ALL:
5134 outs() << " ALL";
5135 break;
5136 default:
5137 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5138 break;
5139 }
5140 break;
5141 case MachO::CPU_TYPE_X86_64:
5142 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00005143 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5144 case MachO::CPU_SUBTYPE_X86_64_ALL:
5145 outs() << " ALL";
5146 break;
5147 case MachO::CPU_SUBTYPE_X86_64_H:
5148 outs() << " Haswell";
5149 break;
5150 default:
5151 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5152 break;
5153 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005154 break;
5155 case MachO::CPU_TYPE_ARM:
5156 outs() << " ARM";
5157 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5158 case MachO::CPU_SUBTYPE_ARM_ALL:
5159 outs() << " ALL";
5160 break;
5161 case MachO::CPU_SUBTYPE_ARM_V4T:
5162 outs() << " V4T";
5163 break;
5164 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
5165 outs() << " V5TEJ";
5166 break;
5167 case MachO::CPU_SUBTYPE_ARM_XSCALE:
5168 outs() << " XSCALE";
5169 break;
5170 case MachO::CPU_SUBTYPE_ARM_V6:
5171 outs() << " V6";
5172 break;
5173 case MachO::CPU_SUBTYPE_ARM_V6M:
5174 outs() << " V6M";
5175 break;
5176 case MachO::CPU_SUBTYPE_ARM_V7:
5177 outs() << " V7";
5178 break;
5179 case MachO::CPU_SUBTYPE_ARM_V7EM:
5180 outs() << " V7EM";
5181 break;
5182 case MachO::CPU_SUBTYPE_ARM_V7K:
5183 outs() << " V7K";
5184 break;
5185 case MachO::CPU_SUBTYPE_ARM_V7M:
5186 outs() << " V7M";
5187 break;
5188 case MachO::CPU_SUBTYPE_ARM_V7S:
5189 outs() << " V7S";
5190 break;
5191 default:
5192 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5193 break;
5194 }
5195 break;
5196 case MachO::CPU_TYPE_ARM64:
5197 outs() << " ARM64";
5198 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5199 case MachO::CPU_SUBTYPE_ARM64_ALL:
5200 outs() << " ALL";
5201 break;
5202 default:
5203 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5204 break;
5205 }
5206 break;
5207 case MachO::CPU_TYPE_POWERPC:
5208 outs() << " PPC";
5209 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5210 case MachO::CPU_SUBTYPE_POWERPC_ALL:
5211 outs() << " ALL";
5212 break;
5213 default:
5214 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5215 break;
5216 }
5217 break;
5218 case MachO::CPU_TYPE_POWERPC64:
5219 outs() << " PPC64";
5220 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5221 case MachO::CPU_SUBTYPE_POWERPC_ALL:
5222 outs() << " ALL";
5223 break;
5224 default:
5225 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5226 break;
5227 }
5228 break;
5229 }
5230 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005231 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005232 } else {
5233 outs() << format(" 0x%02" PRIx32,
5234 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
5235 }
5236 switch (filetype) {
5237 case MachO::MH_OBJECT:
5238 outs() << " OBJECT";
5239 break;
5240 case MachO::MH_EXECUTE:
5241 outs() << " EXECUTE";
5242 break;
5243 case MachO::MH_FVMLIB:
5244 outs() << " FVMLIB";
5245 break;
5246 case MachO::MH_CORE:
5247 outs() << " CORE";
5248 break;
5249 case MachO::MH_PRELOAD:
5250 outs() << " PRELOAD";
5251 break;
5252 case MachO::MH_DYLIB:
5253 outs() << " DYLIB";
5254 break;
5255 case MachO::MH_DYLIB_STUB:
5256 outs() << " DYLIB_STUB";
5257 break;
5258 case MachO::MH_DYLINKER:
5259 outs() << " DYLINKER";
5260 break;
5261 case MachO::MH_BUNDLE:
5262 outs() << " BUNDLE";
5263 break;
5264 case MachO::MH_DSYM:
5265 outs() << " DSYM";
5266 break;
5267 case MachO::MH_KEXT_BUNDLE:
5268 outs() << " KEXTBUNDLE";
5269 break;
5270 default:
5271 outs() << format(" %10u", filetype);
5272 break;
5273 }
5274 outs() << format(" %5u", ncmds);
5275 outs() << format(" %10u", sizeofcmds);
5276 uint32_t f = flags;
5277 if (f & MachO::MH_NOUNDEFS) {
5278 outs() << " NOUNDEFS";
5279 f &= ~MachO::MH_NOUNDEFS;
5280 }
5281 if (f & MachO::MH_INCRLINK) {
5282 outs() << " INCRLINK";
5283 f &= ~MachO::MH_INCRLINK;
5284 }
5285 if (f & MachO::MH_DYLDLINK) {
5286 outs() << " DYLDLINK";
5287 f &= ~MachO::MH_DYLDLINK;
5288 }
5289 if (f & MachO::MH_BINDATLOAD) {
5290 outs() << " BINDATLOAD";
5291 f &= ~MachO::MH_BINDATLOAD;
5292 }
5293 if (f & MachO::MH_PREBOUND) {
5294 outs() << " PREBOUND";
5295 f &= ~MachO::MH_PREBOUND;
5296 }
5297 if (f & MachO::MH_SPLIT_SEGS) {
5298 outs() << " SPLIT_SEGS";
5299 f &= ~MachO::MH_SPLIT_SEGS;
5300 }
5301 if (f & MachO::MH_LAZY_INIT) {
5302 outs() << " LAZY_INIT";
5303 f &= ~MachO::MH_LAZY_INIT;
5304 }
5305 if (f & MachO::MH_TWOLEVEL) {
5306 outs() << " TWOLEVEL";
5307 f &= ~MachO::MH_TWOLEVEL;
5308 }
5309 if (f & MachO::MH_FORCE_FLAT) {
5310 outs() << " FORCE_FLAT";
5311 f &= ~MachO::MH_FORCE_FLAT;
5312 }
5313 if (f & MachO::MH_NOMULTIDEFS) {
5314 outs() << " NOMULTIDEFS";
5315 f &= ~MachO::MH_NOMULTIDEFS;
5316 }
5317 if (f & MachO::MH_NOFIXPREBINDING) {
5318 outs() << " NOFIXPREBINDING";
5319 f &= ~MachO::MH_NOFIXPREBINDING;
5320 }
5321 if (f & MachO::MH_PREBINDABLE) {
5322 outs() << " PREBINDABLE";
5323 f &= ~MachO::MH_PREBINDABLE;
5324 }
5325 if (f & MachO::MH_ALLMODSBOUND) {
5326 outs() << " ALLMODSBOUND";
5327 f &= ~MachO::MH_ALLMODSBOUND;
5328 }
5329 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
5330 outs() << " SUBSECTIONS_VIA_SYMBOLS";
5331 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
5332 }
5333 if (f & MachO::MH_CANONICAL) {
5334 outs() << " CANONICAL";
5335 f &= ~MachO::MH_CANONICAL;
5336 }
5337 if (f & MachO::MH_WEAK_DEFINES) {
5338 outs() << " WEAK_DEFINES";
5339 f &= ~MachO::MH_WEAK_DEFINES;
5340 }
5341 if (f & MachO::MH_BINDS_TO_WEAK) {
5342 outs() << " BINDS_TO_WEAK";
5343 f &= ~MachO::MH_BINDS_TO_WEAK;
5344 }
5345 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
5346 outs() << " ALLOW_STACK_EXECUTION";
5347 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
5348 }
5349 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
5350 outs() << " DEAD_STRIPPABLE_DYLIB";
5351 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
5352 }
5353 if (f & MachO::MH_PIE) {
5354 outs() << " PIE";
5355 f &= ~MachO::MH_PIE;
5356 }
5357 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
5358 outs() << " NO_REEXPORTED_DYLIBS";
5359 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
5360 }
5361 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
5362 outs() << " MH_HAS_TLV_DESCRIPTORS";
5363 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
5364 }
5365 if (f & MachO::MH_NO_HEAP_EXECUTION) {
5366 outs() << " MH_NO_HEAP_EXECUTION";
5367 f &= ~MachO::MH_NO_HEAP_EXECUTION;
5368 }
5369 if (f & MachO::MH_APP_EXTENSION_SAFE) {
5370 outs() << " APP_EXTENSION_SAFE";
5371 f &= ~MachO::MH_APP_EXTENSION_SAFE;
5372 }
5373 if (f != 0 || flags == 0)
5374 outs() << format(" 0x%08" PRIx32, f);
5375 } else {
5376 outs() << format(" 0x%08" PRIx32, magic);
5377 outs() << format(" %7d", cputype);
5378 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5379 outs() << format(" 0x%02" PRIx32,
5380 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
5381 outs() << format(" %10u", filetype);
5382 outs() << format(" %5u", ncmds);
5383 outs() << format(" %10u", sizeofcmds);
5384 outs() << format(" 0x%08" PRIx32, flags);
5385 }
5386 outs() << "\n";
5387}
5388
Kevin Enderby956366c2014-08-29 22:30:52 +00005389static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
5390 StringRef SegName, uint64_t vmaddr,
5391 uint64_t vmsize, uint64_t fileoff,
5392 uint64_t filesize, uint32_t maxprot,
5393 uint32_t initprot, uint32_t nsects,
5394 uint32_t flags, uint32_t object_size,
5395 bool verbose) {
5396 uint64_t expected_cmdsize;
5397 if (cmd == MachO::LC_SEGMENT) {
5398 outs() << " cmd LC_SEGMENT\n";
5399 expected_cmdsize = nsects;
5400 expected_cmdsize *= sizeof(struct MachO::section);
5401 expected_cmdsize += sizeof(struct MachO::segment_command);
5402 } else {
5403 outs() << " cmd LC_SEGMENT_64\n";
5404 expected_cmdsize = nsects;
5405 expected_cmdsize *= sizeof(struct MachO::section_64);
5406 expected_cmdsize += sizeof(struct MachO::segment_command_64);
5407 }
5408 outs() << " cmdsize " << cmdsize;
5409 if (cmdsize != expected_cmdsize)
5410 outs() << " Inconsistent size\n";
5411 else
5412 outs() << "\n";
5413 outs() << " segname " << SegName << "\n";
5414 if (cmd == MachO::LC_SEGMENT_64) {
5415 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
5416 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
5417 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00005418 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
5419 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00005420 }
5421 outs() << " fileoff " << fileoff;
5422 if (fileoff > object_size)
5423 outs() << " (past end of file)\n";
5424 else
5425 outs() << "\n";
5426 outs() << " filesize " << filesize;
5427 if (fileoff + filesize > object_size)
5428 outs() << " (past end of file)\n";
5429 else
5430 outs() << "\n";
5431 if (verbose) {
5432 if ((maxprot &
5433 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
5434 MachO::VM_PROT_EXECUTE)) != 0)
5435 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
5436 else {
5437 if (maxprot & MachO::VM_PROT_READ)
5438 outs() << " maxprot r";
5439 else
5440 outs() << " maxprot -";
5441 if (maxprot & MachO::VM_PROT_WRITE)
5442 outs() << "w";
5443 else
5444 outs() << "-";
5445 if (maxprot & MachO::VM_PROT_EXECUTE)
5446 outs() << "x\n";
5447 else
5448 outs() << "-\n";
5449 }
5450 if ((initprot &
5451 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
5452 MachO::VM_PROT_EXECUTE)) != 0)
5453 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
5454 else {
5455 if (initprot & MachO::VM_PROT_READ)
5456 outs() << " initprot r";
5457 else
5458 outs() << " initprot -";
5459 if (initprot & MachO::VM_PROT_WRITE)
5460 outs() << "w";
5461 else
5462 outs() << "-";
5463 if (initprot & MachO::VM_PROT_EXECUTE)
5464 outs() << "x\n";
5465 else
5466 outs() << "-\n";
5467 }
5468 } else {
5469 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
5470 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
5471 }
5472 outs() << " nsects " << nsects << "\n";
5473 if (verbose) {
5474 outs() << " flags";
5475 if (flags == 0)
5476 outs() << " (none)\n";
5477 else {
5478 if (flags & MachO::SG_HIGHVM) {
5479 outs() << " HIGHVM";
5480 flags &= ~MachO::SG_HIGHVM;
5481 }
5482 if (flags & MachO::SG_FVMLIB) {
5483 outs() << " FVMLIB";
5484 flags &= ~MachO::SG_FVMLIB;
5485 }
5486 if (flags & MachO::SG_NORELOC) {
5487 outs() << " NORELOC";
5488 flags &= ~MachO::SG_NORELOC;
5489 }
5490 if (flags & MachO::SG_PROTECTED_VERSION_1) {
5491 outs() << " PROTECTED_VERSION_1";
5492 flags &= ~MachO::SG_PROTECTED_VERSION_1;
5493 }
5494 if (flags)
5495 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
5496 else
5497 outs() << "\n";
5498 }
5499 } else {
5500 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
5501 }
5502}
5503
5504static void PrintSection(const char *sectname, const char *segname,
5505 uint64_t addr, uint64_t size, uint32_t offset,
5506 uint32_t align, uint32_t reloff, uint32_t nreloc,
5507 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
5508 uint32_t cmd, const char *sg_segname,
5509 uint32_t filetype, uint32_t object_size,
5510 bool verbose) {
5511 outs() << "Section\n";
5512 outs() << " sectname " << format("%.16s\n", sectname);
5513 outs() << " segname " << format("%.16s", segname);
5514 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
5515 outs() << " (does not match segment)\n";
5516 else
5517 outs() << "\n";
5518 if (cmd == MachO::LC_SEGMENT_64) {
5519 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
5520 outs() << " size " << format("0x%016" PRIx64, size);
5521 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00005522 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
5523 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00005524 }
5525 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
5526 outs() << " (past end of file)\n";
5527 else
5528 outs() << "\n";
5529 outs() << " offset " << offset;
5530 if (offset > object_size)
5531 outs() << " (past end of file)\n";
5532 else
5533 outs() << "\n";
5534 uint32_t align_shifted = 1 << align;
5535 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
5536 outs() << " reloff " << reloff;
5537 if (reloff > object_size)
5538 outs() << " (past end of file)\n";
5539 else
5540 outs() << "\n";
5541 outs() << " nreloc " << nreloc;
5542 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
5543 outs() << " (past end of file)\n";
5544 else
5545 outs() << "\n";
5546 uint32_t section_type = flags & MachO::SECTION_TYPE;
5547 if (verbose) {
5548 outs() << " type";
5549 if (section_type == MachO::S_REGULAR)
5550 outs() << " S_REGULAR\n";
5551 else if (section_type == MachO::S_ZEROFILL)
5552 outs() << " S_ZEROFILL\n";
5553 else if (section_type == MachO::S_CSTRING_LITERALS)
5554 outs() << " S_CSTRING_LITERALS\n";
5555 else if (section_type == MachO::S_4BYTE_LITERALS)
5556 outs() << " S_4BYTE_LITERALS\n";
5557 else if (section_type == MachO::S_8BYTE_LITERALS)
5558 outs() << " S_8BYTE_LITERALS\n";
5559 else if (section_type == MachO::S_16BYTE_LITERALS)
5560 outs() << " S_16BYTE_LITERALS\n";
5561 else if (section_type == MachO::S_LITERAL_POINTERS)
5562 outs() << " S_LITERAL_POINTERS\n";
5563 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
5564 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
5565 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
5566 outs() << " S_LAZY_SYMBOL_POINTERS\n";
5567 else if (section_type == MachO::S_SYMBOL_STUBS)
5568 outs() << " S_SYMBOL_STUBS\n";
5569 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
5570 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
5571 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
5572 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
5573 else if (section_type == MachO::S_COALESCED)
5574 outs() << " S_COALESCED\n";
5575 else if (section_type == MachO::S_INTERPOSING)
5576 outs() << " S_INTERPOSING\n";
5577 else if (section_type == MachO::S_DTRACE_DOF)
5578 outs() << " S_DTRACE_DOF\n";
5579 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
5580 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
5581 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
5582 outs() << " S_THREAD_LOCAL_REGULAR\n";
5583 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
5584 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
5585 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
5586 outs() << " S_THREAD_LOCAL_VARIABLES\n";
5587 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
5588 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
5589 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
5590 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
5591 else
5592 outs() << format("0x%08" PRIx32, section_type) << "\n";
5593 outs() << "attributes";
5594 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
5595 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
5596 outs() << " PURE_INSTRUCTIONS";
5597 if (section_attributes & MachO::S_ATTR_NO_TOC)
5598 outs() << " NO_TOC";
5599 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
5600 outs() << " STRIP_STATIC_SYMS";
5601 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
5602 outs() << " NO_DEAD_STRIP";
5603 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
5604 outs() << " LIVE_SUPPORT";
5605 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
5606 outs() << " SELF_MODIFYING_CODE";
5607 if (section_attributes & MachO::S_ATTR_DEBUG)
5608 outs() << " DEBUG";
5609 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
5610 outs() << " SOME_INSTRUCTIONS";
5611 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
5612 outs() << " EXT_RELOC";
5613 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
5614 outs() << " LOC_RELOC";
5615 if (section_attributes == 0)
5616 outs() << " (none)";
5617 outs() << "\n";
5618 } else
5619 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
5620 outs() << " reserved1 " << reserved1;
5621 if (section_type == MachO::S_SYMBOL_STUBS ||
5622 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
5623 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
5624 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
5625 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
5626 outs() << " (index into indirect symbol table)\n";
5627 else
5628 outs() << "\n";
5629 outs() << " reserved2 " << reserved2;
5630 if (section_type == MachO::S_SYMBOL_STUBS)
5631 outs() << " (size of stubs)\n";
5632 else
5633 outs() << "\n";
5634}
5635
David Majnemer73cc6ff2014-11-13 19:48:56 +00005636static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00005637 uint32_t object_size) {
5638 outs() << " cmd LC_SYMTAB\n";
5639 outs() << " cmdsize " << st.cmdsize;
5640 if (st.cmdsize != sizeof(struct MachO::symtab_command))
5641 outs() << " Incorrect size\n";
5642 else
5643 outs() << "\n";
5644 outs() << " symoff " << st.symoff;
5645 if (st.symoff > object_size)
5646 outs() << " (past end of file)\n";
5647 else
5648 outs() << "\n";
5649 outs() << " nsyms " << st.nsyms;
5650 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00005651 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00005652 big_size = st.nsyms;
5653 big_size *= sizeof(struct MachO::nlist_64);
5654 big_size += st.symoff;
5655 if (big_size > object_size)
5656 outs() << " (past end of file)\n";
5657 else
5658 outs() << "\n";
5659 } else {
5660 big_size = st.nsyms;
5661 big_size *= sizeof(struct MachO::nlist);
5662 big_size += st.symoff;
5663 if (big_size > object_size)
5664 outs() << " (past end of file)\n";
5665 else
5666 outs() << "\n";
5667 }
5668 outs() << " stroff " << st.stroff;
5669 if (st.stroff > object_size)
5670 outs() << " (past end of file)\n";
5671 else
5672 outs() << "\n";
5673 outs() << " strsize " << st.strsize;
5674 big_size = st.stroff;
5675 big_size += st.strsize;
5676 if (big_size > object_size)
5677 outs() << " (past end of file)\n";
5678 else
5679 outs() << "\n";
5680}
5681
5682static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
5683 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00005684 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00005685 outs() << " cmd LC_DYSYMTAB\n";
5686 outs() << " cmdsize " << dyst.cmdsize;
5687 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
5688 outs() << " Incorrect size\n";
5689 else
5690 outs() << "\n";
5691 outs() << " ilocalsym " << dyst.ilocalsym;
5692 if (dyst.ilocalsym > nsyms)
5693 outs() << " (greater than the number of symbols)\n";
5694 else
5695 outs() << "\n";
5696 outs() << " nlocalsym " << dyst.nlocalsym;
5697 uint64_t big_size;
5698 big_size = dyst.ilocalsym;
5699 big_size += dyst.nlocalsym;
5700 if (big_size > nsyms)
5701 outs() << " (past the end of the symbol table)\n";
5702 else
5703 outs() << "\n";
5704 outs() << " iextdefsym " << dyst.iextdefsym;
5705 if (dyst.iextdefsym > nsyms)
5706 outs() << " (greater than the number of symbols)\n";
5707 else
5708 outs() << "\n";
5709 outs() << " nextdefsym " << dyst.nextdefsym;
5710 big_size = dyst.iextdefsym;
5711 big_size += dyst.nextdefsym;
5712 if (big_size > nsyms)
5713 outs() << " (past the end of the symbol table)\n";
5714 else
5715 outs() << "\n";
5716 outs() << " iundefsym " << dyst.iundefsym;
5717 if (dyst.iundefsym > nsyms)
5718 outs() << " (greater than the number of symbols)\n";
5719 else
5720 outs() << "\n";
5721 outs() << " nundefsym " << dyst.nundefsym;
5722 big_size = dyst.iundefsym;
5723 big_size += dyst.nundefsym;
5724 if (big_size > nsyms)
5725 outs() << " (past the end of the symbol table)\n";
5726 else
5727 outs() << "\n";
5728 outs() << " tocoff " << dyst.tocoff;
5729 if (dyst.tocoff > object_size)
5730 outs() << " (past end of file)\n";
5731 else
5732 outs() << "\n";
5733 outs() << " ntoc " << dyst.ntoc;
5734 big_size = dyst.ntoc;
5735 big_size *= sizeof(struct MachO::dylib_table_of_contents);
5736 big_size += dyst.tocoff;
5737 if (big_size > object_size)
5738 outs() << " (past end of file)\n";
5739 else
5740 outs() << "\n";
5741 outs() << " modtaboff " << dyst.modtaboff;
5742 if (dyst.modtaboff > object_size)
5743 outs() << " (past end of file)\n";
5744 else
5745 outs() << "\n";
5746 outs() << " nmodtab " << dyst.nmodtab;
5747 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00005748 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00005749 modtabend = dyst.nmodtab;
5750 modtabend *= sizeof(struct MachO::dylib_module_64);
5751 modtabend += dyst.modtaboff;
5752 } else {
5753 modtabend = dyst.nmodtab;
5754 modtabend *= sizeof(struct MachO::dylib_module);
5755 modtabend += dyst.modtaboff;
5756 }
5757 if (modtabend > object_size)
5758 outs() << " (past end of file)\n";
5759 else
5760 outs() << "\n";
5761 outs() << " extrefsymoff " << dyst.extrefsymoff;
5762 if (dyst.extrefsymoff > object_size)
5763 outs() << " (past end of file)\n";
5764 else
5765 outs() << "\n";
5766 outs() << " nextrefsyms " << dyst.nextrefsyms;
5767 big_size = dyst.nextrefsyms;
5768 big_size *= sizeof(struct MachO::dylib_reference);
5769 big_size += dyst.extrefsymoff;
5770 if (big_size > object_size)
5771 outs() << " (past end of file)\n";
5772 else
5773 outs() << "\n";
5774 outs() << " indirectsymoff " << dyst.indirectsymoff;
5775 if (dyst.indirectsymoff > object_size)
5776 outs() << " (past end of file)\n";
5777 else
5778 outs() << "\n";
5779 outs() << " nindirectsyms " << dyst.nindirectsyms;
5780 big_size = dyst.nindirectsyms;
5781 big_size *= sizeof(uint32_t);
5782 big_size += dyst.indirectsymoff;
5783 if (big_size > object_size)
5784 outs() << " (past end of file)\n";
5785 else
5786 outs() << "\n";
5787 outs() << " extreloff " << dyst.extreloff;
5788 if (dyst.extreloff > object_size)
5789 outs() << " (past end of file)\n";
5790 else
5791 outs() << "\n";
5792 outs() << " nextrel " << dyst.nextrel;
5793 big_size = dyst.nextrel;
5794 big_size *= sizeof(struct MachO::relocation_info);
5795 big_size += dyst.extreloff;
5796 if (big_size > object_size)
5797 outs() << " (past end of file)\n";
5798 else
5799 outs() << "\n";
5800 outs() << " locreloff " << dyst.locreloff;
5801 if (dyst.locreloff > object_size)
5802 outs() << " (past end of file)\n";
5803 else
5804 outs() << "\n";
5805 outs() << " nlocrel " << dyst.nlocrel;
5806 big_size = dyst.nlocrel;
5807 big_size *= sizeof(struct MachO::relocation_info);
5808 big_size += dyst.locreloff;
5809 if (big_size > object_size)
5810 outs() << " (past end of file)\n";
5811 else
5812 outs() << "\n";
5813}
5814
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005815static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
5816 uint32_t object_size) {
5817 if (dc.cmd == MachO::LC_DYLD_INFO)
5818 outs() << " cmd LC_DYLD_INFO\n";
5819 else
5820 outs() << " cmd LC_DYLD_INFO_ONLY\n";
5821 outs() << " cmdsize " << dc.cmdsize;
5822 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
5823 outs() << " Incorrect size\n";
5824 else
5825 outs() << "\n";
5826 outs() << " rebase_off " << dc.rebase_off;
5827 if (dc.rebase_off > object_size)
5828 outs() << " (past end of file)\n";
5829 else
5830 outs() << "\n";
5831 outs() << " rebase_size " << dc.rebase_size;
5832 uint64_t big_size;
5833 big_size = dc.rebase_off;
5834 big_size += dc.rebase_size;
5835 if (big_size > object_size)
5836 outs() << " (past end of file)\n";
5837 else
5838 outs() << "\n";
5839 outs() << " bind_off " << dc.bind_off;
5840 if (dc.bind_off > object_size)
5841 outs() << " (past end of file)\n";
5842 else
5843 outs() << "\n";
5844 outs() << " bind_size " << dc.bind_size;
5845 big_size = dc.bind_off;
5846 big_size += dc.bind_size;
5847 if (big_size > object_size)
5848 outs() << " (past end of file)\n";
5849 else
5850 outs() << "\n";
5851 outs() << " weak_bind_off " << dc.weak_bind_off;
5852 if (dc.weak_bind_off > object_size)
5853 outs() << " (past end of file)\n";
5854 else
5855 outs() << "\n";
5856 outs() << " weak_bind_size " << dc.weak_bind_size;
5857 big_size = dc.weak_bind_off;
5858 big_size += dc.weak_bind_size;
5859 if (big_size > object_size)
5860 outs() << " (past end of file)\n";
5861 else
5862 outs() << "\n";
5863 outs() << " lazy_bind_off " << dc.lazy_bind_off;
5864 if (dc.lazy_bind_off > object_size)
5865 outs() << " (past end of file)\n";
5866 else
5867 outs() << "\n";
5868 outs() << " lazy_bind_size " << dc.lazy_bind_size;
5869 big_size = dc.lazy_bind_off;
5870 big_size += dc.lazy_bind_size;
5871 if (big_size > object_size)
5872 outs() << " (past end of file)\n";
5873 else
5874 outs() << "\n";
5875 outs() << " export_off " << dc.export_off;
5876 if (dc.export_off > object_size)
5877 outs() << " (past end of file)\n";
5878 else
5879 outs() << "\n";
5880 outs() << " export_size " << dc.export_size;
5881 big_size = dc.export_off;
5882 big_size += dc.export_size;
5883 if (big_size > object_size)
5884 outs() << " (past end of file)\n";
5885 else
5886 outs() << "\n";
5887}
5888
5889static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
5890 const char *Ptr) {
5891 if (dyld.cmd == MachO::LC_ID_DYLINKER)
5892 outs() << " cmd LC_ID_DYLINKER\n";
5893 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
5894 outs() << " cmd LC_LOAD_DYLINKER\n";
5895 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
5896 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
5897 else
5898 outs() << " cmd ?(" << dyld.cmd << ")\n";
5899 outs() << " cmdsize " << dyld.cmdsize;
5900 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
5901 outs() << " Incorrect size\n";
5902 else
5903 outs() << "\n";
5904 if (dyld.name >= dyld.cmdsize)
5905 outs() << " name ?(bad offset " << dyld.name << ")\n";
5906 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005907 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005908 outs() << " name " << P << " (offset " << dyld.name << ")\n";
5909 }
5910}
5911
5912static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
5913 outs() << " cmd LC_UUID\n";
5914 outs() << " cmdsize " << uuid.cmdsize;
5915 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
5916 outs() << " Incorrect size\n";
5917 else
5918 outs() << "\n";
5919 outs() << " uuid ";
5920 outs() << format("%02" PRIX32, uuid.uuid[0]);
5921 outs() << format("%02" PRIX32, uuid.uuid[1]);
5922 outs() << format("%02" PRIX32, uuid.uuid[2]);
5923 outs() << format("%02" PRIX32, uuid.uuid[3]);
5924 outs() << "-";
5925 outs() << format("%02" PRIX32, uuid.uuid[4]);
5926 outs() << format("%02" PRIX32, uuid.uuid[5]);
5927 outs() << "-";
5928 outs() << format("%02" PRIX32, uuid.uuid[6]);
5929 outs() << format("%02" PRIX32, uuid.uuid[7]);
5930 outs() << "-";
5931 outs() << format("%02" PRIX32, uuid.uuid[8]);
5932 outs() << format("%02" PRIX32, uuid.uuid[9]);
5933 outs() << "-";
5934 outs() << format("%02" PRIX32, uuid.uuid[10]);
5935 outs() << format("%02" PRIX32, uuid.uuid[11]);
5936 outs() << format("%02" PRIX32, uuid.uuid[12]);
5937 outs() << format("%02" PRIX32, uuid.uuid[13]);
5938 outs() << format("%02" PRIX32, uuid.uuid[14]);
5939 outs() << format("%02" PRIX32, uuid.uuid[15]);
5940 outs() << "\n";
5941}
5942
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005943static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00005944 outs() << " cmd LC_RPATH\n";
5945 outs() << " cmdsize " << rpath.cmdsize;
5946 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
5947 outs() << " Incorrect size\n";
5948 else
5949 outs() << "\n";
5950 if (rpath.path >= rpath.cmdsize)
5951 outs() << " path ?(bad offset " << rpath.path << ")\n";
5952 else {
5953 const char *P = (const char *)(Ptr) + rpath.path;
5954 outs() << " path " << P << " (offset " << rpath.path << ")\n";
5955 }
5956}
5957
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005958static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
5959 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
5960 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
5961 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
5962 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
5963 else
5964 outs() << " cmd " << vd.cmd << " (?)\n";
5965 outs() << " cmdsize " << vd.cmdsize;
5966 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
5967 outs() << " Incorrect size\n";
5968 else
5969 outs() << "\n";
5970 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
5971 << ((vd.version >> 8) & 0xff);
5972 if ((vd.version & 0xff) != 0)
5973 outs() << "." << (vd.version & 0xff);
5974 outs() << "\n";
5975 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00005976 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005977 else {
5978 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
5979 << ((vd.sdk >> 8) & 0xff);
5980 }
5981 if ((vd.sdk & 0xff) != 0)
5982 outs() << "." << (vd.sdk & 0xff);
5983 outs() << "\n";
5984}
5985
5986static void PrintSourceVersionCommand(MachO::source_version_command sd) {
5987 outs() << " cmd LC_SOURCE_VERSION\n";
5988 outs() << " cmdsize " << sd.cmdsize;
5989 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
5990 outs() << " Incorrect size\n";
5991 else
5992 outs() << "\n";
5993 uint64_t a = (sd.version >> 40) & 0xffffff;
5994 uint64_t b = (sd.version >> 30) & 0x3ff;
5995 uint64_t c = (sd.version >> 20) & 0x3ff;
5996 uint64_t d = (sd.version >> 10) & 0x3ff;
5997 uint64_t e = sd.version & 0x3ff;
5998 outs() << " version " << a << "." << b;
5999 if (e != 0)
6000 outs() << "." << c << "." << d << "." << e;
6001 else if (d != 0)
6002 outs() << "." << c << "." << d;
6003 else if (c != 0)
6004 outs() << "." << c;
6005 outs() << "\n";
6006}
6007
6008static void PrintEntryPointCommand(MachO::entry_point_command ep) {
6009 outs() << " cmd LC_MAIN\n";
6010 outs() << " cmdsize " << ep.cmdsize;
6011 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
6012 outs() << " Incorrect size\n";
6013 else
6014 outs() << "\n";
6015 outs() << " entryoff " << ep.entryoff << "\n";
6016 outs() << " stacksize " << ep.stacksize << "\n";
6017}
6018
Kevin Enderby0804f4672014-12-16 23:25:52 +00006019static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
6020 uint32_t object_size) {
6021 outs() << " cmd LC_ENCRYPTION_INFO\n";
6022 outs() << " cmdsize " << ec.cmdsize;
6023 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
6024 outs() << " Incorrect size\n";
6025 else
6026 outs() << "\n";
6027 outs() << " cryptoff " << ec.cryptoff;
6028 if (ec.cryptoff > object_size)
6029 outs() << " (past end of file)\n";
6030 else
6031 outs() << "\n";
6032 outs() << " cryptsize " << ec.cryptsize;
6033 if (ec.cryptsize > object_size)
6034 outs() << " (past end of file)\n";
6035 else
6036 outs() << "\n";
6037 outs() << " cryptid " << ec.cryptid << "\n";
6038}
6039
Kevin Enderby57538292014-12-17 01:01:30 +00006040static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006041 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00006042 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
6043 outs() << " cmdsize " << ec.cmdsize;
6044 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
6045 outs() << " Incorrect size\n";
6046 else
6047 outs() << "\n";
6048 outs() << " cryptoff " << ec.cryptoff;
6049 if (ec.cryptoff > object_size)
6050 outs() << " (past end of file)\n";
6051 else
6052 outs() << "\n";
6053 outs() << " cryptsize " << ec.cryptsize;
6054 if (ec.cryptsize > object_size)
6055 outs() << " (past end of file)\n";
6056 else
6057 outs() << "\n";
6058 outs() << " cryptid " << ec.cryptid << "\n";
6059 outs() << " pad " << ec.pad << "\n";
6060}
6061
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006062static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
6063 const char *Ptr) {
6064 outs() << " cmd LC_LINKER_OPTION\n";
6065 outs() << " cmdsize " << lo.cmdsize;
6066 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
6067 outs() << " Incorrect size\n";
6068 else
6069 outs() << "\n";
6070 outs() << " count " << lo.count << "\n";
6071 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
6072 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
6073 uint32_t i = 0;
6074 while (left > 0) {
6075 while (*string == '\0' && left > 0) {
6076 string++;
6077 left--;
6078 }
6079 if (left > 0) {
6080 i++;
6081 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00006082 uint32_t NullPos = StringRef(string, left).find('\0');
6083 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006084 string += len;
6085 left -= len;
6086 }
6087 }
6088 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006089 outs() << " count " << lo.count << " does not match number of strings "
6090 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006091}
6092
Kevin Enderbyb4b79312014-12-18 19:24:35 +00006093static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
6094 const char *Ptr) {
6095 outs() << " cmd LC_SUB_FRAMEWORK\n";
6096 outs() << " cmdsize " << sub.cmdsize;
6097 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
6098 outs() << " Incorrect size\n";
6099 else
6100 outs() << "\n";
6101 if (sub.umbrella < sub.cmdsize) {
6102 const char *P = Ptr + sub.umbrella;
6103 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
6104 } else {
6105 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
6106 }
6107}
6108
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00006109static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
6110 const char *Ptr) {
6111 outs() << " cmd LC_SUB_UMBRELLA\n";
6112 outs() << " cmdsize " << sub.cmdsize;
6113 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
6114 outs() << " Incorrect size\n";
6115 else
6116 outs() << "\n";
6117 if (sub.sub_umbrella < sub.cmdsize) {
6118 const char *P = Ptr + sub.sub_umbrella;
6119 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
6120 } else {
6121 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
6122 }
6123}
6124
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00006125static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006126 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00006127 outs() << " cmd LC_SUB_LIBRARY\n";
6128 outs() << " cmdsize " << sub.cmdsize;
6129 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
6130 outs() << " Incorrect size\n";
6131 else
6132 outs() << "\n";
6133 if (sub.sub_library < sub.cmdsize) {
6134 const char *P = Ptr + sub.sub_library;
6135 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
6136 } else {
6137 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
6138 }
6139}
6140
Kevin Enderby186eac32014-12-19 21:06:24 +00006141static void PrintSubClientCommand(MachO::sub_client_command sub,
6142 const char *Ptr) {
6143 outs() << " cmd LC_SUB_CLIENT\n";
6144 outs() << " cmdsize " << sub.cmdsize;
6145 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
6146 outs() << " Incorrect size\n";
6147 else
6148 outs() << "\n";
6149 if (sub.client < sub.cmdsize) {
6150 const char *P = Ptr + sub.client;
6151 outs() << " client " << P << " (offset " << sub.client << ")\n";
6152 } else {
6153 outs() << " client ?(bad offset " << sub.client << ")\n";
6154 }
6155}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00006156
Kevin Enderby52e4ce42014-12-19 22:25:22 +00006157static void PrintRoutinesCommand(MachO::routines_command r) {
6158 outs() << " cmd LC_ROUTINES\n";
6159 outs() << " cmdsize " << r.cmdsize;
6160 if (r.cmdsize != sizeof(struct MachO::routines_command))
6161 outs() << " Incorrect size\n";
6162 else
6163 outs() << "\n";
6164 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
6165 outs() << " init_module " << r.init_module << "\n";
6166 outs() << " reserved1 " << r.reserved1 << "\n";
6167 outs() << " reserved2 " << r.reserved2 << "\n";
6168 outs() << " reserved3 " << r.reserved3 << "\n";
6169 outs() << " reserved4 " << r.reserved4 << "\n";
6170 outs() << " reserved5 " << r.reserved5 << "\n";
6171 outs() << " reserved6 " << r.reserved6 << "\n";
6172}
6173
6174static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
6175 outs() << " cmd LC_ROUTINES_64\n";
6176 outs() << " cmdsize " << r.cmdsize;
6177 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
6178 outs() << " Incorrect size\n";
6179 else
6180 outs() << "\n";
6181 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
6182 outs() << " init_module " << r.init_module << "\n";
6183 outs() << " reserved1 " << r.reserved1 << "\n";
6184 outs() << " reserved2 " << r.reserved2 << "\n";
6185 outs() << " reserved3 " << r.reserved3 << "\n";
6186 outs() << " reserved4 " << r.reserved4 << "\n";
6187 outs() << " reserved5 " << r.reserved5 << "\n";
6188 outs() << " reserved6 " << r.reserved6 << "\n";
6189}
6190
Kevin Enderby48ef5342014-12-23 22:56:39 +00006191static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
6192 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
6193 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
6194 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
6195 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
6196 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
6197 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
6198 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
6199 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
6200 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
6201 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
6202 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
6203 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
6204 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
6205 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
6206 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
6207 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
6208 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
6209 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
6210 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
6211 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
6212 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
6213}
6214
Kevin Enderby227df342014-12-23 23:43:59 +00006215static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006216 uint32_t f;
6217 outs() << "\t mmst_reg ";
6218 for (f = 0; f < 10; f++)
6219 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
6220 outs() << "\n";
6221 outs() << "\t mmst_rsrv ";
6222 for (f = 0; f < 6; f++)
6223 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
6224 outs() << "\n";
6225}
6226
Kevin Enderbyaefb0032014-12-24 00:16:51 +00006227static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006228 uint32_t f;
6229 outs() << "\t xmm_reg ";
6230 for (f = 0; f < 16; f++)
6231 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
6232 outs() << "\n";
6233}
6234
6235static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
6236 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
6237 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
6238 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
6239 outs() << " denorm " << fpu.fpu_fcw.denorm;
6240 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
6241 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
6242 outs() << " undfl " << fpu.fpu_fcw.undfl;
6243 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
6244 outs() << "\t\t pc ";
6245 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
6246 outs() << "FP_PREC_24B ";
6247 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
6248 outs() << "FP_PREC_53B ";
6249 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
6250 outs() << "FP_PREC_64B ";
6251 else
6252 outs() << fpu.fpu_fcw.pc << " ";
6253 outs() << "rc ";
6254 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
6255 outs() << "FP_RND_NEAR ";
6256 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
6257 outs() << "FP_RND_DOWN ";
6258 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
6259 outs() << "FP_RND_UP ";
6260 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006261 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006262 outs() << "\n";
6263 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
6264 outs() << " denorm " << fpu.fpu_fsw.denorm;
6265 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
6266 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
6267 outs() << " undfl " << fpu.fpu_fsw.undfl;
6268 outs() << " precis " << fpu.fpu_fsw.precis;
6269 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
6270 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
6271 outs() << " c0 " << fpu.fpu_fsw.c0;
6272 outs() << " c1 " << fpu.fpu_fsw.c1;
6273 outs() << " c2 " << fpu.fpu_fsw.c2;
6274 outs() << " tos " << fpu.fpu_fsw.tos;
6275 outs() << " c3 " << fpu.fpu_fsw.c3;
6276 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
6277 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
6278 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
6279 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
6280 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
6281 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
6282 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
6283 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
6284 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
6285 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
6286 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
6287 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
6288 outs() << "\n";
6289 outs() << "\t fpu_stmm0:\n";
6290 Print_mmst_reg(fpu.fpu_stmm0);
6291 outs() << "\t fpu_stmm1:\n";
6292 Print_mmst_reg(fpu.fpu_stmm1);
6293 outs() << "\t fpu_stmm2:\n";
6294 Print_mmst_reg(fpu.fpu_stmm2);
6295 outs() << "\t fpu_stmm3:\n";
6296 Print_mmst_reg(fpu.fpu_stmm3);
6297 outs() << "\t fpu_stmm4:\n";
6298 Print_mmst_reg(fpu.fpu_stmm4);
6299 outs() << "\t fpu_stmm5:\n";
6300 Print_mmst_reg(fpu.fpu_stmm5);
6301 outs() << "\t fpu_stmm6:\n";
6302 Print_mmst_reg(fpu.fpu_stmm6);
6303 outs() << "\t fpu_stmm7:\n";
6304 Print_mmst_reg(fpu.fpu_stmm7);
6305 outs() << "\t fpu_xmm0:\n";
6306 Print_xmm_reg(fpu.fpu_xmm0);
6307 outs() << "\t fpu_xmm1:\n";
6308 Print_xmm_reg(fpu.fpu_xmm1);
6309 outs() << "\t fpu_xmm2:\n";
6310 Print_xmm_reg(fpu.fpu_xmm2);
6311 outs() << "\t fpu_xmm3:\n";
6312 Print_xmm_reg(fpu.fpu_xmm3);
6313 outs() << "\t fpu_xmm4:\n";
6314 Print_xmm_reg(fpu.fpu_xmm4);
6315 outs() << "\t fpu_xmm5:\n";
6316 Print_xmm_reg(fpu.fpu_xmm5);
6317 outs() << "\t fpu_xmm6:\n";
6318 Print_xmm_reg(fpu.fpu_xmm6);
6319 outs() << "\t fpu_xmm7:\n";
6320 Print_xmm_reg(fpu.fpu_xmm7);
6321 outs() << "\t fpu_xmm8:\n";
6322 Print_xmm_reg(fpu.fpu_xmm8);
6323 outs() << "\t fpu_xmm9:\n";
6324 Print_xmm_reg(fpu.fpu_xmm9);
6325 outs() << "\t fpu_xmm10:\n";
6326 Print_xmm_reg(fpu.fpu_xmm10);
6327 outs() << "\t fpu_xmm11:\n";
6328 Print_xmm_reg(fpu.fpu_xmm11);
6329 outs() << "\t fpu_xmm12:\n";
6330 Print_xmm_reg(fpu.fpu_xmm12);
6331 outs() << "\t fpu_xmm13:\n";
6332 Print_xmm_reg(fpu.fpu_xmm13);
6333 outs() << "\t fpu_xmm14:\n";
6334 Print_xmm_reg(fpu.fpu_xmm14);
6335 outs() << "\t fpu_xmm15:\n";
6336 Print_xmm_reg(fpu.fpu_xmm15);
6337 outs() << "\t fpu_rsrv4:\n";
6338 for (uint32_t f = 0; f < 6; f++) {
6339 outs() << "\t ";
6340 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006341 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006342 outs() << "\n";
6343 }
6344 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
6345 outs() << "\n";
6346}
6347
6348static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
6349 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
6350 outs() << " err " << format("0x%08" PRIx32, exc64.err);
6351 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
6352}
6353
6354static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
6355 bool isLittleEndian, uint32_t cputype) {
6356 if (t.cmd == MachO::LC_THREAD)
6357 outs() << " cmd LC_THREAD\n";
6358 else if (t.cmd == MachO::LC_UNIXTHREAD)
6359 outs() << " cmd LC_UNIXTHREAD\n";
6360 else
6361 outs() << " cmd " << t.cmd << " (unknown)\n";
6362 outs() << " cmdsize " << t.cmdsize;
6363 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
6364 outs() << " Incorrect size\n";
6365 else
6366 outs() << "\n";
6367
6368 const char *begin = Ptr + sizeof(struct MachO::thread_command);
6369 const char *end = Ptr + t.cmdsize;
6370 uint32_t flavor, count, left;
6371 if (cputype == MachO::CPU_TYPE_X86_64) {
6372 while (begin < end) {
6373 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
6374 memcpy((char *)&flavor, begin, sizeof(uint32_t));
6375 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006376 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006377 flavor = 0;
6378 begin = end;
6379 }
6380 if (isLittleEndian != sys::IsLittleEndianHost)
6381 sys::swapByteOrder(flavor);
6382 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
6383 memcpy((char *)&count, begin, sizeof(uint32_t));
6384 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006385 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006386 count = 0;
6387 begin = end;
6388 }
6389 if (isLittleEndian != sys::IsLittleEndianHost)
6390 sys::swapByteOrder(count);
6391 if (flavor == MachO::x86_THREAD_STATE64) {
6392 outs() << " flavor x86_THREAD_STATE64\n";
6393 if (count == MachO::x86_THREAD_STATE64_COUNT)
6394 outs() << " count x86_THREAD_STATE64_COUNT\n";
6395 else
6396 outs() << " count " << count
6397 << " (not x86_THREAD_STATE64_COUNT)\n";
6398 MachO::x86_thread_state64_t cpu64;
6399 left = end - begin;
6400 if (left >= sizeof(MachO::x86_thread_state64_t)) {
6401 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
6402 begin += sizeof(MachO::x86_thread_state64_t);
6403 } else {
6404 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
6405 memcpy(&cpu64, begin, left);
6406 begin += left;
6407 }
6408 if (isLittleEndian != sys::IsLittleEndianHost)
6409 swapStruct(cpu64);
6410 Print_x86_thread_state64_t(cpu64);
6411 } else if (flavor == MachO::x86_THREAD_STATE) {
6412 outs() << " flavor x86_THREAD_STATE\n";
6413 if (count == MachO::x86_THREAD_STATE_COUNT)
6414 outs() << " count x86_THREAD_STATE_COUNT\n";
6415 else
6416 outs() << " count " << count
6417 << " (not x86_THREAD_STATE_COUNT)\n";
6418 struct MachO::x86_thread_state_t ts;
6419 left = end - begin;
6420 if (left >= sizeof(MachO::x86_thread_state_t)) {
6421 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
6422 begin += sizeof(MachO::x86_thread_state_t);
6423 } else {
6424 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
6425 memcpy(&ts, begin, left);
6426 begin += left;
6427 }
6428 if (isLittleEndian != sys::IsLittleEndianHost)
6429 swapStruct(ts);
6430 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
6431 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
6432 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
6433 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
6434 else
6435 outs() << "tsh.count " << ts.tsh.count
6436 << " (not x86_THREAD_STATE64_COUNT\n";
6437 Print_x86_thread_state64_t(ts.uts.ts64);
6438 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006439 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
6440 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006441 }
6442 } else if (flavor == MachO::x86_FLOAT_STATE) {
6443 outs() << " flavor x86_FLOAT_STATE\n";
6444 if (count == MachO::x86_FLOAT_STATE_COUNT)
6445 outs() << " count x86_FLOAT_STATE_COUNT\n";
6446 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006447 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006448 struct MachO::x86_float_state_t fs;
6449 left = end - begin;
6450 if (left >= sizeof(MachO::x86_float_state_t)) {
6451 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
6452 begin += sizeof(MachO::x86_float_state_t);
6453 } else {
6454 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
6455 memcpy(&fs, begin, left);
6456 begin += left;
6457 }
6458 if (isLittleEndian != sys::IsLittleEndianHost)
6459 swapStruct(fs);
6460 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
6461 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006462 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00006463 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
6464 else
6465 outs() << "fsh.count " << fs.fsh.count
6466 << " (not x86_FLOAT_STATE64_COUNT\n";
6467 Print_x86_float_state_t(fs.ufs.fs64);
6468 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006469 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
6470 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006471 }
6472 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
6473 outs() << " flavor x86_EXCEPTION_STATE\n";
6474 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
6475 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
6476 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006477 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00006478 << " (not x86_EXCEPTION_STATE_COUNT)\n";
6479 struct MachO::x86_exception_state_t es;
6480 left = end - begin;
6481 if (left >= sizeof(MachO::x86_exception_state_t)) {
6482 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
6483 begin += sizeof(MachO::x86_exception_state_t);
6484 } else {
6485 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
6486 memcpy(&es, begin, left);
6487 begin += left;
6488 }
6489 if (isLittleEndian != sys::IsLittleEndianHost)
6490 swapStruct(es);
6491 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
6492 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006493 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00006494 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
6495 else
6496 outs() << "\t esh.count " << es.esh.count
6497 << " (not x86_EXCEPTION_STATE64_COUNT\n";
6498 Print_x86_exception_state_t(es.ues.es64);
6499 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006500 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
6501 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006502 }
6503 } else {
6504 outs() << " flavor " << flavor << " (unknown)\n";
6505 outs() << " count " << count << "\n";
6506 outs() << " state (unknown)\n";
6507 begin += count * sizeof(uint32_t);
6508 }
6509 }
6510 } else {
6511 while (begin < end) {
6512 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
6513 memcpy((char *)&flavor, begin, sizeof(uint32_t));
6514 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006515 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006516 flavor = 0;
6517 begin = end;
6518 }
6519 if (isLittleEndian != sys::IsLittleEndianHost)
6520 sys::swapByteOrder(flavor);
6521 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
6522 memcpy((char *)&count, begin, sizeof(uint32_t));
6523 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006524 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006525 count = 0;
6526 begin = end;
6527 }
6528 if (isLittleEndian != sys::IsLittleEndianHost)
6529 sys::swapByteOrder(count);
6530 outs() << " flavor " << flavor << "\n";
6531 outs() << " count " << count << "\n";
6532 outs() << " state (Unknown cputype/cpusubtype)\n";
6533 begin += count * sizeof(uint32_t);
6534 }
6535 }
6536}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006537
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006538static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
6539 if (dl.cmd == MachO::LC_ID_DYLIB)
6540 outs() << " cmd LC_ID_DYLIB\n";
6541 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
6542 outs() << " cmd LC_LOAD_DYLIB\n";
6543 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
6544 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
6545 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
6546 outs() << " cmd LC_REEXPORT_DYLIB\n";
6547 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
6548 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
6549 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
6550 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
6551 else
6552 outs() << " cmd " << dl.cmd << " (unknown)\n";
6553 outs() << " cmdsize " << dl.cmdsize;
6554 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
6555 outs() << " Incorrect size\n";
6556 else
6557 outs() << "\n";
6558 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006559 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006560 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
6561 } else {
6562 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
6563 }
6564 outs() << " time stamp " << dl.dylib.timestamp << " ";
6565 time_t t = dl.dylib.timestamp;
6566 outs() << ctime(&t);
6567 outs() << " current version ";
6568 if (dl.dylib.current_version == 0xffffffff)
6569 outs() << "n/a\n";
6570 else
6571 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
6572 << ((dl.dylib.current_version >> 8) & 0xff) << "."
6573 << (dl.dylib.current_version & 0xff) << "\n";
6574 outs() << "compatibility version ";
6575 if (dl.dylib.compatibility_version == 0xffffffff)
6576 outs() << "n/a\n";
6577 else
6578 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
6579 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
6580 << (dl.dylib.compatibility_version & 0xff) << "\n";
6581}
6582
6583static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
6584 uint32_t object_size) {
6585 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
6586 outs() << " cmd LC_FUNCTION_STARTS\n";
6587 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
6588 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
6589 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
6590 outs() << " cmd LC_FUNCTION_STARTS\n";
6591 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
6592 outs() << " cmd LC_DATA_IN_CODE\n";
6593 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
6594 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
6595 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
6596 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
6597 else
6598 outs() << " cmd " << ld.cmd << " (?)\n";
6599 outs() << " cmdsize " << ld.cmdsize;
6600 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
6601 outs() << " Incorrect size\n";
6602 else
6603 outs() << "\n";
6604 outs() << " dataoff " << ld.dataoff;
6605 if (ld.dataoff > object_size)
6606 outs() << " (past end of file)\n";
6607 else
6608 outs() << "\n";
6609 outs() << " datasize " << ld.datasize;
6610 uint64_t big_size = ld.dataoff;
6611 big_size += ld.datasize;
6612 if (big_size > object_size)
6613 outs() << " (past end of file)\n";
6614 else
6615 outs() << "\n";
6616}
6617
Kevin Enderby956366c2014-08-29 22:30:52 +00006618static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
6619 uint32_t filetype, uint32_t cputype,
6620 bool verbose) {
Filipe Cabecinhase71bd0c2015-01-06 17:08:26 +00006621 if (ncmds == 0)
6622 return;
Kevin Enderby956366c2014-08-29 22:30:52 +00006623 StringRef Buf = Obj->getData();
6624 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
6625 for (unsigned i = 0;; ++i) {
6626 outs() << "Load command " << i << "\n";
6627 if (Command.C.cmd == MachO::LC_SEGMENT) {
6628 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
6629 const char *sg_segname = SLC.segname;
6630 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
6631 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
6632 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
6633 verbose);
6634 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00006635 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00006636 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
6637 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
6638 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
6639 }
6640 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
6641 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
6642 const char *sg_segname = SLC_64.segname;
6643 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
6644 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
6645 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
6646 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
6647 for (unsigned j = 0; j < SLC_64.nsects; j++) {
6648 MachO::section_64 S_64 = Obj->getSection64(Command, j);
6649 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
6650 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
6651 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
6652 sg_segname, filetype, Buf.size(), verbose);
6653 }
6654 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
6655 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00006656 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00006657 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
6658 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
6659 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00006660 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
6661 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006662 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
6663 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
6664 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
6665 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
6666 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
6667 Command.C.cmd == MachO::LC_ID_DYLINKER ||
6668 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
6669 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
6670 PrintDyldLoadCommand(Dyld, Command.Ptr);
6671 } else if (Command.C.cmd == MachO::LC_UUID) {
6672 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
6673 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00006674 } else if (Command.C.cmd == MachO::LC_RPATH) {
6675 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
6676 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00006677 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
6678 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006679 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
6680 PrintVersionMinLoadCommand(Vd);
6681 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
6682 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
6683 PrintSourceVersionCommand(Sd);
6684 } else if (Command.C.cmd == MachO::LC_MAIN) {
6685 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
6686 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00006687 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006688 MachO::encryption_info_command Ei =
6689 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00006690 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00006691 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006692 MachO::encryption_info_command_64 Ei =
6693 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00006694 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006695 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006696 MachO::linker_option_command Lo =
6697 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006698 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00006699 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
6700 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
6701 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00006702 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
6703 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
6704 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00006705 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
6706 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
6707 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00006708 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
6709 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
6710 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00006711 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
6712 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
6713 PrintRoutinesCommand(Rc);
6714 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
6715 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
6716 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00006717 } else if (Command.C.cmd == MachO::LC_THREAD ||
6718 Command.C.cmd == MachO::LC_UNIXTHREAD) {
6719 MachO::thread_command Tc = Obj->getThreadCommand(Command);
6720 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00006721 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
6722 Command.C.cmd == MachO::LC_ID_DYLIB ||
6723 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
6724 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
6725 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
6726 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006727 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
6728 PrintDylibCommand(Dl, Command.Ptr);
6729 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
6730 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
6731 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
6732 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
6733 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
6734 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
6735 MachO::linkedit_data_command Ld =
6736 Obj->getLinkeditDataLoadCommand(Command);
6737 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00006738 } else {
6739 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
6740 << ")\n";
6741 outs() << " cmdsize " << Command.C.cmdsize << "\n";
6742 // TODO: get and print the raw bytes of the load command.
6743 }
6744 // TODO: print all the other kinds of load commands.
6745 if (i == ncmds - 1)
6746 break;
6747 else
6748 Command = Obj->getNextLoadCommandInfo(Command);
6749 }
6750}
6751
6752static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
6753 uint32_t &filetype, uint32_t &cputype,
6754 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006755 if (Obj->is64Bit()) {
6756 MachO::mach_header_64 H_64;
6757 H_64 = Obj->getHeader64();
6758 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
6759 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00006760 ncmds = H_64.ncmds;
6761 filetype = H_64.filetype;
6762 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006763 } else {
6764 MachO::mach_header H;
6765 H = Obj->getHeader();
6766 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
6767 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00006768 ncmds = H.ncmds;
6769 filetype = H.filetype;
6770 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006771 }
6772}
6773
6774void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
6775 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00006776 uint32_t ncmds = 0;
6777 uint32_t filetype = 0;
6778 uint32_t cputype = 0;
Kevin Enderbyf0640752015-03-13 17:56:32 +00006779 getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
6780 PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006781}
Nick Kledzikd04bc352014-08-30 00:20:14 +00006782
6783//===----------------------------------------------------------------------===//
6784// export trie dumping
6785//===----------------------------------------------------------------------===//
6786
6787void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006788 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
6789 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00006790 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
6791 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
6792 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
6793 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
6794 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
6795 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
6796 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
6797 if (ReExport)
6798 outs() << "[re-export] ";
6799 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006800 outs() << format("0x%08llX ",
6801 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006802 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00006803 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006804 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00006805 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00006806 if (WeakDef) {
6807 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006808 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00006809 }
6810 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006811 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00006812 outs() << ", ";
6813 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006814 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00006815 }
6816 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006817 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00006818 outs() << ", ";
6819 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006820 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00006821 }
6822 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006823 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00006824 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006825 outs() << format("resolver=0x%08llX", Entry.other());
6826 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00006827 }
6828 outs() << "]";
6829 }
6830 if (ReExport) {
6831 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006832 int Ordinal = Entry.other() - 1;
6833 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
6834 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00006835 outs() << " (from " << DylibName << ")";
6836 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006837 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00006838 }
6839 outs() << "\n";
6840 }
6841}
Nick Kledzikac431442014-09-12 21:34:15 +00006842
Nick Kledzikac431442014-09-12 21:34:15 +00006843//===----------------------------------------------------------------------===//
6844// rebase table dumping
6845//===----------------------------------------------------------------------===//
6846
6847namespace {
6848class SegInfo {
6849public:
6850 SegInfo(const object::MachOObjectFile *Obj);
6851
6852 StringRef segmentName(uint32_t SegIndex);
6853 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
6854 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
6855
6856private:
6857 struct SectionInfo {
6858 uint64_t Address;
6859 uint64_t Size;
6860 StringRef SectionName;
6861 StringRef SegmentName;
6862 uint64_t OffsetInSegment;
6863 uint64_t SegmentStartAddress;
6864 uint32_t SegmentIndex;
6865 };
6866 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
6867 SmallVector<SectionInfo, 32> Sections;
6868};
6869}
6870
6871SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
6872 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00006873 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00006874 StringRef CurSegName;
6875 uint64_t CurSegAddress;
6876 for (const SectionRef &Section : Obj->sections()) {
6877 SectionInfo Info;
6878 if (error(Section.getName(Info.SectionName)))
6879 return;
Rafael Espindola80291272014-10-08 15:28:58 +00006880 Info.Address = Section.getAddress();
6881 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00006882 Info.SegmentName =
6883 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
6884 if (!Info.SegmentName.equals(CurSegName)) {
6885 ++CurSegIndex;
6886 CurSegName = Info.SegmentName;
6887 CurSegAddress = Info.Address;
6888 }
6889 Info.SegmentIndex = CurSegIndex - 1;
6890 Info.OffsetInSegment = Info.Address - CurSegAddress;
6891 Info.SegmentStartAddress = CurSegAddress;
6892 Sections.push_back(Info);
6893 }
6894}
6895
6896StringRef SegInfo::segmentName(uint32_t SegIndex) {
6897 for (const SectionInfo &SI : Sections) {
6898 if (SI.SegmentIndex == SegIndex)
6899 return SI.SegmentName;
6900 }
6901 llvm_unreachable("invalid segIndex");
6902}
6903
6904const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
6905 uint64_t OffsetInSeg) {
6906 for (const SectionInfo &SI : Sections) {
6907 if (SI.SegmentIndex != SegIndex)
6908 continue;
6909 if (SI.OffsetInSegment > OffsetInSeg)
6910 continue;
6911 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
6912 continue;
6913 return SI;
6914 }
6915 llvm_unreachable("segIndex and offset not in any section");
6916}
6917
6918StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
6919 return findSection(SegIndex, OffsetInSeg).SectionName;
6920}
6921
6922uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
6923 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
6924 return SI.SegmentStartAddress + OffsetInSeg;
6925}
6926
6927void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
6928 // Build table of sections so names can used in final output.
6929 SegInfo sectionTable(Obj);
6930
6931 outs() << "segment section address type\n";
6932 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
6933 uint32_t SegIndex = Entry.segmentIndex();
6934 uint64_t OffsetInSeg = Entry.segmentOffset();
6935 StringRef SegmentName = sectionTable.segmentName(SegIndex);
6936 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
6937 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
6938
6939 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006940 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
6941 SegmentName.str().c_str(), SectionName.str().c_str(),
6942 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00006943 }
6944}
Nick Kledzik56ebef42014-09-16 01:41:51 +00006945
6946static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
6947 StringRef DylibName;
6948 switch (Ordinal) {
6949 case MachO::BIND_SPECIAL_DYLIB_SELF:
6950 return "this-image";
6951 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
6952 return "main-executable";
6953 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
6954 return "flat-namespace";
6955 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00006956 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006957 std::error_code EC =
6958 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00006959 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00006960 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00006961 return DylibName;
6962 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00006963 }
Nick Kledzikabd29872014-09-16 22:03:13 +00006964 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00006965}
6966
6967//===----------------------------------------------------------------------===//
6968// bind table dumping
6969//===----------------------------------------------------------------------===//
6970
6971void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
6972 // Build table of sections so names can used in final output.
6973 SegInfo sectionTable(Obj);
6974
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006975 outs() << "segment section address type "
6976 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00006977 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
6978 uint32_t SegIndex = Entry.segmentIndex();
6979 uint64_t OffsetInSeg = Entry.segmentOffset();
6980 StringRef SegmentName = sectionTable.segmentName(SegIndex);
6981 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
6982 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
6983
6984 // Table lines look like:
6985 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006986 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00006987 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006988 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006989 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006990 << left_justify(SectionName, 18) << " "
6991 << format_hex(Address, 10, true) << " "
6992 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006993 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006994 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006995 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00006996 }
6997}
6998
6999//===----------------------------------------------------------------------===//
7000// lazy bind table dumping
7001//===----------------------------------------------------------------------===//
7002
7003void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
7004 // Build table of sections so names can used in final output.
7005 SegInfo sectionTable(Obj);
7006
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007007 outs() << "segment section address "
7008 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00007009 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
7010 uint32_t SegIndex = Entry.segmentIndex();
7011 uint64_t OffsetInSeg = Entry.segmentOffset();
7012 StringRef SegmentName = sectionTable.segmentName(SegIndex);
7013 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
7014 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
7015
7016 // Table lines look like:
7017 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007018 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007019 << left_justify(SectionName, 18) << " "
7020 << format_hex(Address, 10, true) << " "
7021 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00007022 << Entry.symbolName() << "\n";
7023 }
7024}
7025
Nick Kledzik56ebef42014-09-16 01:41:51 +00007026//===----------------------------------------------------------------------===//
7027// weak bind table dumping
7028//===----------------------------------------------------------------------===//
7029
7030void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
7031 // Build table of sections so names can used in final output.
7032 SegInfo sectionTable(Obj);
7033
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007034 outs() << "segment section address "
7035 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00007036 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
7037 // Strong symbols don't have a location to update.
7038 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007039 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00007040 << Entry.symbolName() << "\n";
7041 continue;
7042 }
7043 uint32_t SegIndex = Entry.segmentIndex();
7044 uint64_t OffsetInSeg = Entry.segmentOffset();
7045 StringRef SegmentName = sectionTable.segmentName(SegIndex);
7046 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
7047 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
7048
7049 // Table lines look like:
7050 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007051 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007052 << left_justify(SectionName, 18) << " "
7053 << format_hex(Address, 10, true) << " "
7054 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007055 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
7056 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00007057 }
7058}
7059
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007060// get_dyld_bind_info_symbolname() is used for disassembly and passed an
7061// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
7062// information for that address. If the address is found its binding symbol
7063// name is returned. If not nullptr is returned.
7064static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
7065 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00007066 if (info->bindtable == nullptr) {
7067 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007068 SegInfo sectionTable(info->O);
7069 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
7070 uint32_t SegIndex = Entry.segmentIndex();
7071 uint64_t OffsetInSeg = Entry.segmentOffset();
7072 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
7073 const char *SymbolName = nullptr;
7074 StringRef name = Entry.symbolName();
7075 if (!name.empty())
7076 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00007077 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007078 }
7079 }
Kevin Enderby078be602014-10-23 19:53:12 +00007080 for (bind_table_iterator BI = info->bindtable->begin(),
7081 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007082 BI != BE; ++BI) {
7083 uint64_t Address = BI->first;
7084 if (ReferenceValue == Address) {
7085 const char *SymbolName = BI->second;
7086 return SymbolName;
7087 }
7088 }
7089 return nullptr;
7090}