blob: b16506f903f13007d435074a468ed6d8528effbd [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 }
3837}
3838
3839static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
3840 outs() << "Printing Objc2 32-bit MetaData not yet supported\n";
3841}
3842
3843static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
3844 const SectionRef S = get_section(O, "__OBJC", "__module_info");
3845 if (S != SectionRef()) {
3846 outs() << "Printing Objc1 32-bit MetaData not yet supported\n";
3847 return true;
3848 }
3849 return false;
3850}
3851
3852static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
3853 if (O->is64Bit())
3854 printObjc2_64bit_MetaData(O, verbose);
3855 else {
3856 MachO::mach_header H;
3857 H = O->getHeader();
3858 if (H.cputype == MachO::CPU_TYPE_ARM)
3859 printObjc2_32bit_MetaData(O, verbose);
3860 else {
3861 // This is the 32-bit non-arm cputype case. Which is normally
3862 // the first Objective-C ABI. But it may be the case of a
3863 // binary for the iOS simulator which is the second Objective-C
3864 // ABI. In that case printObjc1_32bit_MetaData() will determine that
3865 // and return false.
3866 if (printObjc1_32bit_MetaData(O, verbose) == false)
3867 printObjc2_32bit_MetaData(O, verbose);
3868 }
3869 }
3870}
3871
Kevin Enderbybf246f52014-09-24 23:08:22 +00003872// GuessLiteralPointer returns a string which for the item in the Mach-O file
3873// for the address passed in as ReferenceValue for printing as a comment with
3874// the instruction and also returns the corresponding type of that item
3875// indirectly through ReferenceType.
3876//
3877// If ReferenceValue is an address of literal cstring then a pointer to the
3878// cstring is returned and ReferenceType is set to
3879// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
3880//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003881// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
3882// Class ref that name is returned and the ReferenceType is set accordingly.
3883//
3884// Lastly, literals which are Symbol address in a literal pool are looked for
3885// and if found the symbol name is returned and ReferenceType is set to
3886// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
3887//
3888// If there is no item in the Mach-O file for the address passed in as
3889// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003890static const char *GuessLiteralPointer(uint64_t ReferenceValue,
3891 uint64_t ReferencePC,
3892 uint64_t *ReferenceType,
3893 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00003894 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00003895 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00003896 uint64_t sect_offset = ReferencePC - sect_addr;
3897 bool reloc_found = false;
3898 DataRefImpl Rel;
3899 MachO::any_relocation_info RE;
3900 bool isExtern = false;
3901 SymbolRef Symbol;
3902 for (const RelocationRef &Reloc : info->S.relocations()) {
3903 uint64_t RelocOffset;
3904 Reloc.getOffset(RelocOffset);
3905 if (RelocOffset == sect_offset) {
3906 Rel = Reloc.getRawDataRefImpl();
3907 RE = info->O->getRelocation(Rel);
3908 if (info->O->isRelocationScattered(RE))
3909 continue;
3910 isExtern = info->O->getPlainRelocationExternal(RE);
3911 if (isExtern) {
3912 symbol_iterator RelocSym = Reloc.getSymbol();
3913 Symbol = *RelocSym;
3914 }
3915 reloc_found = true;
3916 break;
3917 }
3918 }
3919 // If there is an external relocation entry for a symbol in a section
3920 // then used that symbol's value for the value of the reference.
3921 if (reloc_found && isExtern) {
3922 if (info->O->getAnyRelocationPCRel(RE)) {
3923 unsigned Type = info->O->getAnyRelocationType(RE);
3924 if (Type == MachO::X86_64_RELOC_SIGNED) {
3925 Symbol.getAddress(ReferenceValue);
3926 }
3927 }
3928 }
3929
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003930 // Look for literals such as Objective-C CFStrings refs, Selector refs,
3931 // Message refs and Class refs.
3932 bool classref, selref, msgref, cfstring;
3933 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
3934 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00003935 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003936 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
3937 // And the pointer_value in that section is typically zero as it will be
3938 // set by dyld as part of the "bind information".
3939 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
3940 if (name != nullptr) {
3941 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003942 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003943 if (class_name != nullptr && class_name[1] == '_' &&
3944 class_name[2] != '\0') {
3945 info->class_name = class_name + 2;
3946 return name;
3947 }
3948 }
3949 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00003950
David Blaikie33dd45d02015-03-23 18:39:02 +00003951 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003952 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
3953 const char *name =
3954 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
3955 if (name != nullptr)
3956 info->class_name = name;
3957 else
3958 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00003959 return name;
3960 }
3961
David Blaikie33dd45d02015-03-23 18:39:02 +00003962 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003963 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
3964 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
3965 return name;
3966 }
3967
David Blaikie33dd45d02015-03-23 18:39:02 +00003968 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003969 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
3970
3971 if (pointer_value != 0)
3972 ReferenceValue = pointer_value;
3973
3974 const char *name = GuessCstringPointer(ReferenceValue, info);
3975 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00003976 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003977 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
3978 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00003979 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003980 info->class_name = nullptr;
3981 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
3982 info->selector_name = name;
3983 } else
3984 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
3985 return name;
3986 }
3987
3988 // Lastly look for an indirect symbol with this ReferenceValue which is in
3989 // a literal pool. If found return that symbol name.
3990 name = GuessIndirectSymbol(ReferenceValue, info);
3991 if (name) {
3992 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
3993 return name;
3994 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00003995
3996 return nullptr;
3997}
3998
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003999// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00004000// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004001// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
4002// is created and returns the symbol name that matches the ReferenceValue or
4003// nullptr if none. The ReferenceType is passed in for the IN type of
4004// reference the instruction is making from the values in defined in the header
4005// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
4006// Out type and the ReferenceName will also be set which is added as a comment
4007// to the disassembled instruction.
4008//
Kevin Enderby04bf6932014-10-28 23:39:46 +00004009#if HAVE_CXXABI_H
4010// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004011// returned through ReferenceName and ReferenceType is set to
4012// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00004013#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004014//
4015// When this is called to get a symbol name for a branch target then the
4016// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
4017// SymbolValue will be looked for in the indirect symbol table to determine if
4018// it is an address for a symbol stub. If so then the symbol name for that
4019// stub is returned indirectly through ReferenceName and then ReferenceType is
4020// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
4021//
Kevin Enderbybf246f52014-09-24 23:08:22 +00004022// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004023// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
4024// SymbolValue is checked to be an address of literal pointer, symbol pointer,
4025// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004026// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00004027static const char *SymbolizerSymbolLookUp(void *DisInfo,
4028 uint64_t ReferenceValue,
4029 uint64_t *ReferenceType,
4030 uint64_t ReferencePC,
4031 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004032 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00004033 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00004034 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00004035 *ReferenceName = nullptr;
4036 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004037 return nullptr;
4038 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00004039
Kevin Enderbyf6d25852015-01-31 00:37:11 +00004040 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00004041
Kevin Enderby85974882014-09-26 22:20:44 +00004042 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
4043 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00004044 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004045 method_reference(info, ReferenceType, ReferenceName);
4046 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
4047 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
4048 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00004049#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004050 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00004051 if (info->demangled_name != nullptr)
4052 free(info->demangled_name);
4053 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004054 info->demangled_name =
4055 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00004056 if (info->demangled_name != nullptr) {
4057 *ReferenceName = info->demangled_name;
4058 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
4059 } else
4060 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4061 } else
4062#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004063 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4064 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
4065 *ReferenceName =
4066 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00004067 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004068 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00004069 else
4070 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004071 // If this is arm64 and the reference is an adrp instruction save the
4072 // instruction, passed in ReferenceValue and the address of the instruction
4073 // for use later if we see and add immediate instruction.
4074 } else if (info->O->getArch() == Triple::aarch64 &&
4075 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
4076 info->adrp_inst = ReferenceValue;
4077 info->adrp_addr = ReferencePC;
4078 SymbolName = nullptr;
4079 *ReferenceName = nullptr;
4080 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4081 // If this is arm64 and reference is an add immediate instruction and we
4082 // have
4083 // seen an adrp instruction just before it and the adrp's Xd register
4084 // matches
4085 // this add's Xn register reconstruct the value being referenced and look to
4086 // see if it is a literal pointer. Note the add immediate instruction is
4087 // passed in ReferenceValue.
4088 } else if (info->O->getArch() == Triple::aarch64 &&
4089 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
4090 ReferencePC - 4 == info->adrp_addr &&
4091 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
4092 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
4093 uint32_t addxri_inst;
4094 uint64_t adrp_imm, addxri_imm;
4095
4096 adrp_imm =
4097 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
4098 if (info->adrp_inst & 0x0200000)
4099 adrp_imm |= 0xfffffffffc000000LL;
4100
4101 addxri_inst = ReferenceValue;
4102 addxri_imm = (addxri_inst >> 10) & 0xfff;
4103 if (((addxri_inst >> 22) & 0x3) == 1)
4104 addxri_imm <<= 12;
4105
4106 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
4107 (adrp_imm << 12) + addxri_imm;
4108
4109 *ReferenceName =
4110 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
4111 if (*ReferenceName == nullptr)
4112 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4113 // If this is arm64 and the reference is a load register instruction and we
4114 // have seen an adrp instruction just before it and the adrp's Xd register
4115 // matches this add's Xn register reconstruct the value being referenced and
4116 // look to see if it is a literal pointer. Note the load register
4117 // instruction is passed in ReferenceValue.
4118 } else if (info->O->getArch() == Triple::aarch64 &&
4119 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
4120 ReferencePC - 4 == info->adrp_addr &&
4121 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
4122 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
4123 uint32_t ldrxui_inst;
4124 uint64_t adrp_imm, ldrxui_imm;
4125
4126 adrp_imm =
4127 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
4128 if (info->adrp_inst & 0x0200000)
4129 adrp_imm |= 0xfffffffffc000000LL;
4130
4131 ldrxui_inst = ReferenceValue;
4132 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
4133
4134 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
4135 (adrp_imm << 12) + (ldrxui_imm << 3);
4136
4137 *ReferenceName =
4138 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
4139 if (*ReferenceName == nullptr)
4140 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4141 }
4142 // If this arm64 and is an load register (PC-relative) instruction the
4143 // ReferenceValue is the PC plus the immediate value.
4144 else if (info->O->getArch() == Triple::aarch64 &&
4145 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
4146 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
4147 *ReferenceName =
4148 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
4149 if (*ReferenceName == nullptr)
4150 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00004151 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00004152#if HAVE_CXXABI_H
4153 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
4154 if (info->demangled_name != nullptr)
4155 free(info->demangled_name);
4156 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004157 info->demangled_name =
4158 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00004159 if (info->demangled_name != nullptr) {
4160 *ReferenceName = info->demangled_name;
4161 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
4162 }
4163 }
4164#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004165 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00004166 *ReferenceName = nullptr;
4167 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
4168 }
4169
4170 return SymbolName;
4171}
4172
Kevin Enderbybf246f52014-09-24 23:08:22 +00004173/// \brief Emits the comments that are stored in the CommentStream.
4174/// Each comment in the CommentStream must end with a newline.
4175static void emitComments(raw_svector_ostream &CommentStream,
4176 SmallString<128> &CommentsToEmit,
4177 formatted_raw_ostream &FormattedOS,
4178 const MCAsmInfo &MAI) {
4179 // Flush the stream before taking its content.
4180 CommentStream.flush();
4181 StringRef Comments = CommentsToEmit.str();
4182 // Get the default information for printing a comment.
4183 const char *CommentBegin = MAI.getCommentString();
4184 unsigned CommentColumn = MAI.getCommentColumn();
4185 bool IsFirst = true;
4186 while (!Comments.empty()) {
4187 if (!IsFirst)
4188 FormattedOS << '\n';
4189 // Emit a line of comments.
4190 FormattedOS.PadToColumn(CommentColumn);
4191 size_t Position = Comments.find('\n');
4192 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
4193 // Move after the newline character.
4194 Comments = Comments.substr(Position + 1);
4195 IsFirst = false;
4196 }
4197 FormattedOS.flush();
4198
4199 // Tell the comment stream that the vector changed underneath it.
4200 CommentsToEmit.clear();
4201 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004202}
4203
Kevin Enderby95df54c2015-02-04 01:01:38 +00004204static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
4205 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004206 const char *McpuDefault = nullptr;
4207 const Target *ThumbTarget = nullptr;
4208 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004209 if (!TheTarget) {
4210 // GetTarget prints out stuff.
4211 return;
4212 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004213 if (MCPU.empty() && McpuDefault)
4214 MCPU = McpuDefault;
4215
Ahmed Charles56440fd2014-03-06 05:51:42 +00004216 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004217 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004218 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004219 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004220
Kevin Enderbyc9595622014-08-06 23:24:41 +00004221 // Package up features to be passed to target/subtarget
4222 std::string FeaturesStr;
4223 if (MAttrs.size()) {
4224 SubtargetFeatures Features;
4225 for (unsigned i = 0; i != MAttrs.size(); ++i)
4226 Features.AddFeature(MAttrs[i]);
4227 FeaturesStr = Features.getString();
4228 }
4229
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004230 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00004231 std::unique_ptr<const MCRegisterInfo> MRI(
4232 TheTarget->createMCRegInfo(TripleName));
4233 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00004234 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00004235 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00004236 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00004237 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004238 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004239 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004240 std::unique_ptr<MCSymbolizer> Symbolizer;
4241 struct DisassembleInfo SymbolizerInfo;
4242 std::unique_ptr<MCRelocationInfo> RelInfo(
4243 TheTarget->createMCRelocationInfo(TripleName, Ctx));
4244 if (RelInfo) {
4245 Symbolizer.reset(TheTarget->createMCSymbolizer(
4246 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00004247 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004248 DisAsm->setSymbolizer(std::move(Symbolizer));
4249 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004250 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00004251 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +00004252 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00004253 // Set the display preference for hex vs. decimal immediates.
4254 IP->setPrintImmHex(PrintImmHex);
4255 // Comment stream and backing vector.
4256 SmallString<128> CommentsToEmit;
4257 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00004258 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
4259 // if it is done then arm64 comments for string literals don't get printed
4260 // and some constant get printed instead and not setting it causes intel
4261 // (32-bit and 64-bit) comments printed with different spacing before the
4262 // comment causing different diffs with the 'C' disassembler library API.
4263 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004264
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004265 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00004266 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004267 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004268 return;
4269 }
4270
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004271 // Set up thumb disassembler.
4272 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
4273 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
4274 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004275 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004276 std::unique_ptr<MCInstPrinter> ThumbIP;
4277 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004278 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
4279 struct DisassembleInfo ThumbSymbolizerInfo;
4280 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004281 if (ThumbTarget) {
4282 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
4283 ThumbAsmInfo.reset(
4284 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
4285 ThumbSTI.reset(
4286 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
4287 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
4288 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00004289 MCContext *PtrThumbCtx = ThumbCtx.get();
4290 ThumbRelInfo.reset(
4291 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
4292 if (ThumbRelInfo) {
4293 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
4294 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00004295 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00004296 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
4297 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004298 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
4299 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +00004300 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
4301 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00004302 // Set the display preference for hex vs. decimal immediates.
4303 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004304 }
4305
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004306 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004307 errs() << "error: couldn't initialize disassembler for target "
4308 << ThumbTripleName << '\n';
4309 return;
4310 }
4311
Charles Davis8bdfafd2013-09-01 04:28:48 +00004312 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004313
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004314 // FIXME: Using the -cfg command line option, this code used to be able to
4315 // annotate relocations with the referenced symbol's name, and if this was
4316 // inside a __[cf]string section, the data it points to. This is now replaced
4317 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00004318 std::vector<SectionRef> Sections;
4319 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004320 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00004321 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004322
Kevin Enderby273ae012013-06-06 17:20:50 +00004323 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
4324 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004325
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004326 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00004327 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004328
Kevin Enderby273ae012013-06-06 17:20:50 +00004329 // Build a data in code table that is sorted on by the address of each entry.
4330 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00004331 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00004332 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00004333 else
4334 BaseAddress = BaseSegmentAddress;
4335 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00004336 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00004337 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00004338 uint32_t Offset;
4339 DI->getOffset(Offset);
4340 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
4341 }
4342 array_pod_sort(Dices.begin(), Dices.end());
4343
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004344#ifndef NDEBUG
4345 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
4346#else
4347 raw_ostream &DebugOut = nulls();
4348#endif
4349
Ahmed Charles56440fd2014-03-06 05:51:42 +00004350 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00004351 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00004352 // Try to find debug info and set up the DIContext for it.
4353 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00004354 // A separate DSym file path was specified, parse it as a macho file,
4355 // get the sections and supply it to the section name parsing machinery.
4356 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00004357 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00004358 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00004359 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00004360 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00004361 return;
4362 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00004363 DbgObj =
4364 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
4365 .get()
4366 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00004367 }
4368
Eric Christopher7370b552012-11-12 21:40:38 +00004369 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00004370 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00004371 }
4372
Kevin Enderby95df54c2015-02-04 01:01:38 +00004373 if (DumpSections.size() == 0)
4374 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00004375
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004376 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00004377 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00004378 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
4379 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004380
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00004381 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004382
Rafael Espindolab0f76a42013-04-05 15:15:22 +00004383 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00004384 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00004385 continue;
4386
Rafael Espindola7fc5b872014-11-12 02:04:27 +00004387 StringRef BytesStr;
4388 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00004389 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
4390 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00004391 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00004392
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004393 bool symbolTableWorked = false;
4394
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004395 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00004396 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
4397 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00004398 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00004399 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00004400 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00004401 RelocOffset -= SectionAddress;
4402
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00004403 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00004404
Rafael Espindola806f0062013-06-05 01:33:53 +00004405 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004406 }
4407 array_pod_sort(Relocs.begin(), Relocs.end());
4408
Kevin Enderbybf246f52014-09-24 23:08:22 +00004409 // Create a map of symbol addresses to symbol names for use by
4410 // the SymbolizerSymbolLookUp() routine.
4411 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00004412 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00004413 for (const SymbolRef &Symbol : MachOOF->symbols()) {
4414 SymbolRef::Type ST;
4415 Symbol.getType(ST);
4416 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
4417 ST == SymbolRef::ST_Other) {
4418 uint64_t Address;
4419 Symbol.getAddress(Address);
4420 StringRef SymName;
4421 Symbol.getName(SymName);
4422 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00004423 if (!DisSymName.empty() && DisSymName == SymName)
4424 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00004425 }
4426 }
David Blaikie33dd45d02015-03-23 18:39:02 +00004427 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00004428 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
4429 return;
4430 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004431 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00004432 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004433 SymbolizerInfo.O = MachOOF;
4434 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00004435 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004436 SymbolizerInfo.Sections = &Sections;
4437 SymbolizerInfo.class_name = nullptr;
4438 SymbolizerInfo.selector_name = nullptr;
4439 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00004440 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00004441 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00004442 SymbolizerInfo.adrp_addr = 0;
4443 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004444 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00004445 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004446 ThumbSymbolizerInfo.O = MachOOF;
4447 ThumbSymbolizerInfo.S = Sections[SectIdx];
4448 ThumbSymbolizerInfo.AddrMap = &AddrMap;
4449 ThumbSymbolizerInfo.Sections = &Sections;
4450 ThumbSymbolizerInfo.class_name = nullptr;
4451 ThumbSymbolizerInfo.selector_name = nullptr;
4452 ThumbSymbolizerInfo.method = nullptr;
4453 ThumbSymbolizerInfo.demangled_name = nullptr;
4454 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00004455 ThumbSymbolizerInfo.adrp_addr = 0;
4456 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00004457
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004458 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004459 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00004460 StringRef SymName;
4461 Symbols[SymIdx].getName(SymName);
4462
4463 SymbolRef::Type ST;
4464 Symbols[SymIdx].getType(ST);
4465 if (ST != SymbolRef::ST_Function)
4466 continue;
4467
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004468 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00004469 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00004470 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004471 continue;
4472
Kevin Enderby6a221752015-03-17 17:10:57 +00004473 // If we are only disassembling one symbol see if this is that symbol.
4474 if (!DisSymName.empty() && DisSymName != SymName)
4475 continue;
4476
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004477 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00004478 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00004479 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00004480 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00004481 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00004482
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00004483 // Stop disassembling either at the beginning of the next symbol or at
4484 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00004485 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00004486 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004487 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00004488 while (Symbols.size() > NextSymIdx) {
4489 SymbolRef::Type NextSymType;
4490 Symbols[NextSymIdx].getType(NextSymType);
4491 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00004492 containsNextSym =
4493 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00004494 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00004495 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00004496 break;
4497 }
4498 ++NextSymIdx;
4499 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004500
Rafael Espindola80291272014-10-08 15:28:58 +00004501 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004502 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00004503 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004504
4505 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00004506
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004507 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
4508 bool isThumb =
4509 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
4510
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004511 outs() << SymName << ":\n";
4512 DILineInfo lastLine;
4513 for (uint64_t Index = Start; Index < End; Index += Size) {
4514 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00004515
Kevin Enderbybf246f52014-09-24 23:08:22 +00004516 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00004517 if (!NoLeadingAddr) {
4518 if (FullLeadingAddr) {
4519 if (MachOOF->is64Bit())
4520 outs() << format("%016" PRIx64, PC);
4521 else
4522 outs() << format("%08" PRIx64, PC);
4523 } else {
4524 outs() << format("%8" PRIx64 ":", PC);
4525 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00004526 }
4527 if (!NoShowRawInsn)
4528 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00004529
4530 // Check the data in code table here to see if this is data not an
4531 // instruction to be disassembled.
4532 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00004533 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004534 dice_table_iterator DTI =
4535 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
4536 compareDiceTableEntries);
4537 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00004538 uint16_t Length;
4539 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00004540 uint16_t Kind;
4541 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00004542 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00004543 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
4544 (PC == (DTI->first + Length - 1)) && (Length & 1))
4545 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00004546 continue;
4547 }
4548
Kevin Enderbybf246f52014-09-24 23:08:22 +00004549 SmallVector<char, 64> AnnotationsBytes;
4550 raw_svector_ostream Annotations(AnnotationsBytes);
4551
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004552 bool gotInst;
4553 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00004554 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004555 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004556 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00004557 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00004558 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004559 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00004560 if (!NoShowRawInsn) {
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00004561 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size));
Kevin Enderbybf246f52014-09-24 23:08:22 +00004562 }
4563 formatted_raw_ostream FormattedOS(outs());
4564 Annotations.flush();
4565 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004566 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00004567 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00004568 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00004569 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00004570 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00004571
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004572 // Print debug info.
4573 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004574 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004575 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00004576 if (dli != lastLine && dli.Line != 0)
4577 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
4578 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004579 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004580 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004581 outs() << "\n";
4582 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004583 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004584 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004585 outs() << format("\t.byte 0x%02x #bad opcode\n",
4586 *(Bytes.data() + Index) & 0xff);
4587 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00004588 } else if (Arch == Triple::aarch64) {
4589 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
4590 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
4591 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
4592 (*(Bytes.data() + Index + 3) & 0xff) << 24;
4593 outs() << format("\t.long\t0x%08x\n", opcode);
4594 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004595 } else {
4596 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
4597 if (Size == 0)
4598 Size = 1; // skip illegible bytes
4599 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004600 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004601 }
4602 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00004603 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00004604 // Reading the symbol table didn't work, disassemble the whole section.
4605 uint64_t SectAddress = Sections[SectIdx].getAddress();
4606 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00004607 uint64_t InstSize;
4608 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00004609 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00004610
Kevin Enderbybf246f52014-09-24 23:08:22 +00004611 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00004612 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
4613 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00004614 if (!NoLeadingAddr) {
4615 if (FullLeadingAddr) {
4616 if (MachOOF->is64Bit())
4617 outs() << format("%016" PRIx64, PC);
4618 else
4619 outs() << format("%08" PRIx64, PC);
4620 } else {
4621 outs() << format("%8" PRIx64 ":", PC);
4622 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00004623 }
4624 if (!NoShowRawInsn) {
4625 outs() << "\t";
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00004626 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize));
Kevin Enderbybf246f52014-09-24 23:08:22 +00004627 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00004628 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00004629 outs() << "\n";
4630 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004631 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004632 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004633 outs() << format("\t.byte 0x%02x #bad opcode\n",
4634 *(Bytes.data() + Index) & 0xff);
4635 InstSize = 1; // skip exactly one illegible byte and move on.
4636 } else {
4637 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
4638 if (InstSize == 0)
4639 InstSize = 1; // skip illegible bytes
4640 }
Bill Wendling4e68e062012-07-19 00:17:40 +00004641 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00004642 }
4643 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00004644 // The TripleName's need to be reset if we are called again for a different
4645 // archtecture.
4646 TripleName = "";
4647 ThumbTripleName = "";
4648
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004649 if (SymbolizerInfo.method != nullptr)
4650 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00004651 if (SymbolizerInfo.demangled_name != nullptr)
4652 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00004653 if (SymbolizerInfo.bindtable != nullptr)
4654 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00004655 if (ThumbSymbolizerInfo.method != nullptr)
4656 free(ThumbSymbolizerInfo.method);
4657 if (ThumbSymbolizerInfo.demangled_name != nullptr)
4658 free(ThumbSymbolizerInfo.demangled_name);
4659 if (ThumbSymbolizerInfo.bindtable != nullptr)
4660 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00004661 }
4662}
Tim Northover4bd286a2014-08-01 13:07:19 +00004663
Tim Northover39c70bb2014-08-12 11:52:59 +00004664//===----------------------------------------------------------------------===//
4665// __compact_unwind section dumping
4666//===----------------------------------------------------------------------===//
4667
Tim Northover4bd286a2014-08-01 13:07:19 +00004668namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00004669
4670template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004671 using llvm::support::little;
4672 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00004673
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004674 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
4675 Buf += sizeof(T);
4676 return Val;
4677}
Tim Northover39c70bb2014-08-12 11:52:59 +00004678
Tim Northover4bd286a2014-08-01 13:07:19 +00004679struct CompactUnwindEntry {
4680 uint32_t OffsetInSection;
4681
4682 uint64_t FunctionAddr;
4683 uint32_t Length;
4684 uint32_t CompactEncoding;
4685 uint64_t PersonalityAddr;
4686 uint64_t LSDAAddr;
4687
4688 RelocationRef FunctionReloc;
4689 RelocationRef PersonalityReloc;
4690 RelocationRef LSDAReloc;
4691
4692 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004693 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00004694 if (Is64)
4695 read<uint64_t>(Contents.data() + Offset);
4696 else
4697 read<uint32_t>(Contents.data() + Offset);
4698 }
4699
4700private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004701 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00004702 FunctionAddr = readNext<UIntPtr>(Buf);
4703 Length = readNext<uint32_t>(Buf);
4704 CompactEncoding = readNext<uint32_t>(Buf);
4705 PersonalityAddr = readNext<UIntPtr>(Buf);
4706 LSDAAddr = readNext<UIntPtr>(Buf);
4707 }
4708};
4709}
4710
4711/// Given a relocation from __compact_unwind, consisting of the RelocationRef
4712/// and data being relocated, determine the best base Name and Addend to use for
4713/// display purposes.
4714///
4715/// 1. An Extern relocation will directly reference a symbol (and the data is
4716/// then already an addend), so use that.
4717/// 2. Otherwise the data is an offset in the object file's layout; try to find
4718// a symbol before it in the same section, and use the offset from there.
4719/// 3. Finally, if all that fails, fall back to an offset from the start of the
4720/// referenced section.
4721static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
4722 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004723 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00004724 StringRef &Name, uint64_t &Addend) {
4725 if (Reloc.getSymbol() != Obj->symbol_end()) {
4726 Reloc.getSymbol()->getName(Name);
4727 Addend = Addr;
4728 return;
4729 }
4730
4731 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
4732 SectionRef RelocSection = Obj->getRelocationSection(RE);
4733
Rafael Espindola80291272014-10-08 15:28:58 +00004734 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00004735
4736 auto Sym = Symbols.upper_bound(Addr);
4737 if (Sym == Symbols.begin()) {
4738 // The first symbol in the object is after this reference, the best we can
4739 // do is section-relative notation.
4740 RelocSection.getName(Name);
4741 Addend = Addr - SectionAddr;
4742 return;
4743 }
4744
4745 // Go back one so that SymbolAddress <= Addr.
4746 --Sym;
4747
4748 section_iterator SymSection = Obj->section_end();
4749 Sym->second.getSection(SymSection);
4750 if (RelocSection == *SymSection) {
4751 // There's a valid symbol in the same section before this reference.
4752 Sym->second.getName(Name);
4753 Addend = Addr - Sym->first;
4754 return;
4755 }
4756
4757 // There is a symbol before this reference, but it's in a different
4758 // section. Probably not helpful to mention it, so use the section name.
4759 RelocSection.getName(Name);
4760 Addend = Addr - SectionAddr;
4761}
4762
4763static void printUnwindRelocDest(const MachOObjectFile *Obj,
4764 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004765 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00004766 StringRef Name;
4767 uint64_t Addend;
4768
Tim Northover0b0add52014-09-09 10:45:06 +00004769 if (!Reloc.getObjectFile())
4770 return;
4771
Tim Northover4bd286a2014-08-01 13:07:19 +00004772 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
4773
4774 outs() << Name;
4775 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00004776 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00004777}
4778
4779static void
4780printMachOCompactUnwindSection(const MachOObjectFile *Obj,
4781 std::map<uint64_t, SymbolRef> &Symbols,
4782 const SectionRef &CompactUnwind) {
4783
4784 assert(Obj->isLittleEndian() &&
4785 "There should not be a big-endian .o with __compact_unwind");
4786
4787 bool Is64 = Obj->is64Bit();
4788 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
4789 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
4790
4791 StringRef Contents;
4792 CompactUnwind.getContents(Contents);
4793
4794 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
4795
4796 // First populate the initial raw offsets, encodings and so on from the entry.
4797 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
4798 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
4799 CompactUnwinds.push_back(Entry);
4800 }
4801
4802 // Next we need to look at the relocations to find out what objects are
4803 // actually being referred to.
4804 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
4805 uint64_t RelocAddress;
4806 Reloc.getOffset(RelocAddress);
4807
4808 uint32_t EntryIdx = RelocAddress / EntrySize;
4809 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
4810 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
4811
4812 if (OffsetInEntry == 0)
4813 Entry.FunctionReloc = Reloc;
4814 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
4815 Entry.PersonalityReloc = Reloc;
4816 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
4817 Entry.LSDAReloc = Reloc;
4818 else
4819 llvm_unreachable("Unexpected relocation in __compact_unwind section");
4820 }
4821
4822 // Finally, we're ready to print the data we've gathered.
4823 outs() << "Contents of __compact_unwind section:\n";
4824 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00004825 outs() << " Entry at offset "
4826 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00004827
4828 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004829 outs() << " start: " << format("0x%" PRIx64,
4830 Entry.FunctionAddr) << ' ';
4831 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00004832 outs() << '\n';
4833
4834 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004835 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
4836 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00004837 // 3. The 32-bit compact encoding.
4838 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00004839 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00004840
4841 // 4. The personality function, if present.
4842 if (Entry.PersonalityReloc.getObjectFile()) {
4843 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00004844 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00004845 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
4846 Entry.PersonalityAddr);
4847 outs() << '\n';
4848 }
4849
4850 // 5. This entry's language-specific data area.
4851 if (Entry.LSDAReloc.getObjectFile()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004852 outs() << " LSDA: " << format("0x%" PRIx64,
4853 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00004854 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
4855 outs() << '\n';
4856 }
4857 }
4858}
4859
Tim Northover39c70bb2014-08-12 11:52:59 +00004860//===----------------------------------------------------------------------===//
4861// __unwind_info section dumping
4862//===----------------------------------------------------------------------===//
4863
4864static void printRegularSecondLevelUnwindPage(const char *PageStart) {
4865 const char *Pos = PageStart;
4866 uint32_t Kind = readNext<uint32_t>(Pos);
4867 (void)Kind;
4868 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
4869
4870 uint16_t EntriesStart = readNext<uint16_t>(Pos);
4871 uint16_t NumEntries = readNext<uint16_t>(Pos);
4872
4873 Pos = PageStart + EntriesStart;
4874 for (unsigned i = 0; i < NumEntries; ++i) {
4875 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
4876 uint32_t Encoding = readNext<uint32_t>(Pos);
4877
4878 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004879 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
4880 << ", "
4881 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00004882 }
4883}
4884
4885static void printCompressedSecondLevelUnwindPage(
4886 const char *PageStart, uint32_t FunctionBase,
4887 const SmallVectorImpl<uint32_t> &CommonEncodings) {
4888 const char *Pos = PageStart;
4889 uint32_t Kind = readNext<uint32_t>(Pos);
4890 (void)Kind;
4891 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
4892
4893 uint16_t EntriesStart = readNext<uint16_t>(Pos);
4894 uint16_t NumEntries = readNext<uint16_t>(Pos);
4895
4896 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
4897 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00004898 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
4899 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00004900
4901 Pos = PageStart + EntriesStart;
4902 for (unsigned i = 0; i < NumEntries; ++i) {
4903 uint32_t Entry = readNext<uint32_t>(Pos);
4904 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
4905 uint32_t EncodingIdx = Entry >> 24;
4906
4907 uint32_t Encoding;
4908 if (EncodingIdx < CommonEncodings.size())
4909 Encoding = CommonEncodings[EncodingIdx];
4910 else
4911 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
4912
4913 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004914 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
4915 << ", "
4916 << "encoding[" << EncodingIdx
4917 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00004918 }
4919}
4920
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004921static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
4922 std::map<uint64_t, SymbolRef> &Symbols,
4923 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00004924
4925 assert(Obj->isLittleEndian() &&
4926 "There should not be a big-endian .o with __unwind_info");
4927
4928 outs() << "Contents of __unwind_info section:\n";
4929
4930 StringRef Contents;
4931 UnwindInfo.getContents(Contents);
4932 const char *Pos = Contents.data();
4933
4934 //===----------------------------------
4935 // Section header
4936 //===----------------------------------
4937
4938 uint32_t Version = readNext<uint32_t>(Pos);
4939 outs() << " Version: "
4940 << format("0x%" PRIx32, Version) << '\n';
4941 assert(Version == 1 && "only understand version 1");
4942
4943 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
4944 outs() << " Common encodings array section offset: "
4945 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
4946 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
4947 outs() << " Number of common encodings in array: "
4948 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
4949
4950 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
4951 outs() << " Personality function array section offset: "
4952 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
4953 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
4954 outs() << " Number of personality functions in array: "
4955 << format("0x%" PRIx32, NumPersonalities) << '\n';
4956
4957 uint32_t IndicesStart = readNext<uint32_t>(Pos);
4958 outs() << " Index array section offset: "
4959 << format("0x%" PRIx32, IndicesStart) << '\n';
4960 uint32_t NumIndices = readNext<uint32_t>(Pos);
4961 outs() << " Number of indices in array: "
4962 << format("0x%" PRIx32, NumIndices) << '\n';
4963
4964 //===----------------------------------
4965 // A shared list of common encodings
4966 //===----------------------------------
4967
4968 // These occupy indices in the range [0, N] whenever an encoding is referenced
4969 // from a compressed 2nd level index table. In practice the linker only
4970 // creates ~128 of these, so that indices are available to embed encodings in
4971 // the 2nd level index.
4972
4973 SmallVector<uint32_t, 64> CommonEncodings;
4974 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
4975 Pos = Contents.data() + CommonEncodingsStart;
4976 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
4977 uint32_t Encoding = readNext<uint32_t>(Pos);
4978 CommonEncodings.push_back(Encoding);
4979
4980 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
4981 << '\n';
4982 }
4983
Tim Northover39c70bb2014-08-12 11:52:59 +00004984 //===----------------------------------
4985 // Personality functions used in this executable
4986 //===----------------------------------
4987
4988 // There should be only a handful of these (one per source language,
4989 // roughly). Particularly since they only get 2 bits in the compact encoding.
4990
4991 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
4992 Pos = Contents.data() + PersonalitiesStart;
4993 for (unsigned i = 0; i < NumPersonalities; ++i) {
4994 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
4995 outs() << " personality[" << i + 1
4996 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
4997 }
4998
4999 //===----------------------------------
5000 // The level 1 index entries
5001 //===----------------------------------
5002
5003 // These specify an approximate place to start searching for the more detailed
5004 // information, sorted by PC.
5005
5006 struct IndexEntry {
5007 uint32_t FunctionOffset;
5008 uint32_t SecondLevelPageStart;
5009 uint32_t LSDAStart;
5010 };
5011
5012 SmallVector<IndexEntry, 4> IndexEntries;
5013
5014 outs() << " Top level indices: (count = " << NumIndices << ")\n";
5015 Pos = Contents.data() + IndicesStart;
5016 for (unsigned i = 0; i < NumIndices; ++i) {
5017 IndexEntry Entry;
5018
5019 Entry.FunctionOffset = readNext<uint32_t>(Pos);
5020 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
5021 Entry.LSDAStart = readNext<uint32_t>(Pos);
5022 IndexEntries.push_back(Entry);
5023
5024 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005025 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
5026 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00005027 << "2nd level page offset="
5028 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005029 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00005030 }
5031
Tim Northover39c70bb2014-08-12 11:52:59 +00005032 //===----------------------------------
5033 // Next come the LSDA tables
5034 //===----------------------------------
5035
5036 // The LSDA layout is rather implicit: it's a contiguous array of entries from
5037 // the first top-level index's LSDAOffset to the last (sentinel).
5038
5039 outs() << " LSDA descriptors:\n";
5040 Pos = Contents.data() + IndexEntries[0].LSDAStart;
5041 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
5042 (2 * sizeof(uint32_t));
5043 for (int i = 0; i < NumLSDAs; ++i) {
5044 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
5045 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
5046 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005047 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
5048 << ", "
5049 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00005050 }
5051
5052 //===----------------------------------
5053 // Finally, the 2nd level indices
5054 //===----------------------------------
5055
5056 // Generally these are 4K in size, and have 2 possible forms:
5057 // + Regular stores up to 511 entries with disparate encodings
5058 // + Compressed stores up to 1021 entries if few enough compact encoding
5059 // values are used.
5060 outs() << " Second level indices:\n";
5061 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
5062 // The final sentinel top-level index has no associated 2nd level page
5063 if (IndexEntries[i].SecondLevelPageStart == 0)
5064 break;
5065
5066 outs() << " Second level index[" << i << "]: "
5067 << "offset in section="
5068 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
5069 << ", "
5070 << "base function offset="
5071 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
5072
5073 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00005074 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00005075 if (Kind == 2)
5076 printRegularSecondLevelUnwindPage(Pos);
5077 else if (Kind == 3)
5078 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
5079 CommonEncodings);
5080 else
5081 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00005082 }
5083}
5084
Tim Northover4bd286a2014-08-01 13:07:19 +00005085void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
5086 std::map<uint64_t, SymbolRef> Symbols;
5087 for (const SymbolRef &SymRef : Obj->symbols()) {
5088 // Discard any undefined or absolute symbols. They're not going to take part
5089 // in the convenience lookup for unwind info and just take up resources.
5090 section_iterator Section = Obj->section_end();
5091 SymRef.getSection(Section);
5092 if (Section == Obj->section_end())
5093 continue;
5094
5095 uint64_t Addr;
5096 SymRef.getAddress(Addr);
5097 Symbols.insert(std::make_pair(Addr, SymRef));
5098 }
5099
5100 for (const SectionRef &Section : Obj->sections()) {
5101 StringRef SectName;
5102 Section.getName(SectName);
5103 if (SectName == "__compact_unwind")
5104 printMachOCompactUnwindSection(Obj, Symbols, Section);
5105 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00005106 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00005107 else if (SectName == "__eh_frame")
5108 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00005109 }
5110}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005111
5112static void PrintMachHeader(uint32_t magic, uint32_t cputype,
5113 uint32_t cpusubtype, uint32_t filetype,
5114 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
5115 bool verbose) {
5116 outs() << "Mach header\n";
5117 outs() << " magic cputype cpusubtype caps filetype ncmds "
5118 "sizeofcmds flags\n";
5119 if (verbose) {
5120 if (magic == MachO::MH_MAGIC)
5121 outs() << " MH_MAGIC";
5122 else if (magic == MachO::MH_MAGIC_64)
5123 outs() << "MH_MAGIC_64";
5124 else
5125 outs() << format(" 0x%08" PRIx32, magic);
5126 switch (cputype) {
5127 case MachO::CPU_TYPE_I386:
5128 outs() << " I386";
5129 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5130 case MachO::CPU_SUBTYPE_I386_ALL:
5131 outs() << " ALL";
5132 break;
5133 default:
5134 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5135 break;
5136 }
5137 break;
5138 case MachO::CPU_TYPE_X86_64:
5139 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00005140 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5141 case MachO::CPU_SUBTYPE_X86_64_ALL:
5142 outs() << " ALL";
5143 break;
5144 case MachO::CPU_SUBTYPE_X86_64_H:
5145 outs() << " Haswell";
5146 break;
5147 default:
5148 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5149 break;
5150 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005151 break;
5152 case MachO::CPU_TYPE_ARM:
5153 outs() << " ARM";
5154 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5155 case MachO::CPU_SUBTYPE_ARM_ALL:
5156 outs() << " ALL";
5157 break;
5158 case MachO::CPU_SUBTYPE_ARM_V4T:
5159 outs() << " V4T";
5160 break;
5161 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
5162 outs() << " V5TEJ";
5163 break;
5164 case MachO::CPU_SUBTYPE_ARM_XSCALE:
5165 outs() << " XSCALE";
5166 break;
5167 case MachO::CPU_SUBTYPE_ARM_V6:
5168 outs() << " V6";
5169 break;
5170 case MachO::CPU_SUBTYPE_ARM_V6M:
5171 outs() << " V6M";
5172 break;
5173 case MachO::CPU_SUBTYPE_ARM_V7:
5174 outs() << " V7";
5175 break;
5176 case MachO::CPU_SUBTYPE_ARM_V7EM:
5177 outs() << " V7EM";
5178 break;
5179 case MachO::CPU_SUBTYPE_ARM_V7K:
5180 outs() << " V7K";
5181 break;
5182 case MachO::CPU_SUBTYPE_ARM_V7M:
5183 outs() << " V7M";
5184 break;
5185 case MachO::CPU_SUBTYPE_ARM_V7S:
5186 outs() << " V7S";
5187 break;
5188 default:
5189 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5190 break;
5191 }
5192 break;
5193 case MachO::CPU_TYPE_ARM64:
5194 outs() << " ARM64";
5195 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5196 case MachO::CPU_SUBTYPE_ARM64_ALL:
5197 outs() << " ALL";
5198 break;
5199 default:
5200 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5201 break;
5202 }
5203 break;
5204 case MachO::CPU_TYPE_POWERPC:
5205 outs() << " PPC";
5206 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5207 case MachO::CPU_SUBTYPE_POWERPC_ALL:
5208 outs() << " ALL";
5209 break;
5210 default:
5211 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5212 break;
5213 }
5214 break;
5215 case MachO::CPU_TYPE_POWERPC64:
5216 outs() << " PPC64";
5217 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
5218 case MachO::CPU_SUBTYPE_POWERPC_ALL:
5219 outs() << " ALL";
5220 break;
5221 default:
5222 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5223 break;
5224 }
5225 break;
5226 }
5227 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005228 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005229 } else {
5230 outs() << format(" 0x%02" PRIx32,
5231 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
5232 }
5233 switch (filetype) {
5234 case MachO::MH_OBJECT:
5235 outs() << " OBJECT";
5236 break;
5237 case MachO::MH_EXECUTE:
5238 outs() << " EXECUTE";
5239 break;
5240 case MachO::MH_FVMLIB:
5241 outs() << " FVMLIB";
5242 break;
5243 case MachO::MH_CORE:
5244 outs() << " CORE";
5245 break;
5246 case MachO::MH_PRELOAD:
5247 outs() << " PRELOAD";
5248 break;
5249 case MachO::MH_DYLIB:
5250 outs() << " DYLIB";
5251 break;
5252 case MachO::MH_DYLIB_STUB:
5253 outs() << " DYLIB_STUB";
5254 break;
5255 case MachO::MH_DYLINKER:
5256 outs() << " DYLINKER";
5257 break;
5258 case MachO::MH_BUNDLE:
5259 outs() << " BUNDLE";
5260 break;
5261 case MachO::MH_DSYM:
5262 outs() << " DSYM";
5263 break;
5264 case MachO::MH_KEXT_BUNDLE:
5265 outs() << " KEXTBUNDLE";
5266 break;
5267 default:
5268 outs() << format(" %10u", filetype);
5269 break;
5270 }
5271 outs() << format(" %5u", ncmds);
5272 outs() << format(" %10u", sizeofcmds);
5273 uint32_t f = flags;
5274 if (f & MachO::MH_NOUNDEFS) {
5275 outs() << " NOUNDEFS";
5276 f &= ~MachO::MH_NOUNDEFS;
5277 }
5278 if (f & MachO::MH_INCRLINK) {
5279 outs() << " INCRLINK";
5280 f &= ~MachO::MH_INCRLINK;
5281 }
5282 if (f & MachO::MH_DYLDLINK) {
5283 outs() << " DYLDLINK";
5284 f &= ~MachO::MH_DYLDLINK;
5285 }
5286 if (f & MachO::MH_BINDATLOAD) {
5287 outs() << " BINDATLOAD";
5288 f &= ~MachO::MH_BINDATLOAD;
5289 }
5290 if (f & MachO::MH_PREBOUND) {
5291 outs() << " PREBOUND";
5292 f &= ~MachO::MH_PREBOUND;
5293 }
5294 if (f & MachO::MH_SPLIT_SEGS) {
5295 outs() << " SPLIT_SEGS";
5296 f &= ~MachO::MH_SPLIT_SEGS;
5297 }
5298 if (f & MachO::MH_LAZY_INIT) {
5299 outs() << " LAZY_INIT";
5300 f &= ~MachO::MH_LAZY_INIT;
5301 }
5302 if (f & MachO::MH_TWOLEVEL) {
5303 outs() << " TWOLEVEL";
5304 f &= ~MachO::MH_TWOLEVEL;
5305 }
5306 if (f & MachO::MH_FORCE_FLAT) {
5307 outs() << " FORCE_FLAT";
5308 f &= ~MachO::MH_FORCE_FLAT;
5309 }
5310 if (f & MachO::MH_NOMULTIDEFS) {
5311 outs() << " NOMULTIDEFS";
5312 f &= ~MachO::MH_NOMULTIDEFS;
5313 }
5314 if (f & MachO::MH_NOFIXPREBINDING) {
5315 outs() << " NOFIXPREBINDING";
5316 f &= ~MachO::MH_NOFIXPREBINDING;
5317 }
5318 if (f & MachO::MH_PREBINDABLE) {
5319 outs() << " PREBINDABLE";
5320 f &= ~MachO::MH_PREBINDABLE;
5321 }
5322 if (f & MachO::MH_ALLMODSBOUND) {
5323 outs() << " ALLMODSBOUND";
5324 f &= ~MachO::MH_ALLMODSBOUND;
5325 }
5326 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
5327 outs() << " SUBSECTIONS_VIA_SYMBOLS";
5328 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
5329 }
5330 if (f & MachO::MH_CANONICAL) {
5331 outs() << " CANONICAL";
5332 f &= ~MachO::MH_CANONICAL;
5333 }
5334 if (f & MachO::MH_WEAK_DEFINES) {
5335 outs() << " WEAK_DEFINES";
5336 f &= ~MachO::MH_WEAK_DEFINES;
5337 }
5338 if (f & MachO::MH_BINDS_TO_WEAK) {
5339 outs() << " BINDS_TO_WEAK";
5340 f &= ~MachO::MH_BINDS_TO_WEAK;
5341 }
5342 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
5343 outs() << " ALLOW_STACK_EXECUTION";
5344 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
5345 }
5346 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
5347 outs() << " DEAD_STRIPPABLE_DYLIB";
5348 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
5349 }
5350 if (f & MachO::MH_PIE) {
5351 outs() << " PIE";
5352 f &= ~MachO::MH_PIE;
5353 }
5354 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
5355 outs() << " NO_REEXPORTED_DYLIBS";
5356 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
5357 }
5358 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
5359 outs() << " MH_HAS_TLV_DESCRIPTORS";
5360 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
5361 }
5362 if (f & MachO::MH_NO_HEAP_EXECUTION) {
5363 outs() << " MH_NO_HEAP_EXECUTION";
5364 f &= ~MachO::MH_NO_HEAP_EXECUTION;
5365 }
5366 if (f & MachO::MH_APP_EXTENSION_SAFE) {
5367 outs() << " APP_EXTENSION_SAFE";
5368 f &= ~MachO::MH_APP_EXTENSION_SAFE;
5369 }
5370 if (f != 0 || flags == 0)
5371 outs() << format(" 0x%08" PRIx32, f);
5372 } else {
5373 outs() << format(" 0x%08" PRIx32, magic);
5374 outs() << format(" %7d", cputype);
5375 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
5376 outs() << format(" 0x%02" PRIx32,
5377 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
5378 outs() << format(" %10u", filetype);
5379 outs() << format(" %5u", ncmds);
5380 outs() << format(" %10u", sizeofcmds);
5381 outs() << format(" 0x%08" PRIx32, flags);
5382 }
5383 outs() << "\n";
5384}
5385
Kevin Enderby956366c2014-08-29 22:30:52 +00005386static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
5387 StringRef SegName, uint64_t vmaddr,
5388 uint64_t vmsize, uint64_t fileoff,
5389 uint64_t filesize, uint32_t maxprot,
5390 uint32_t initprot, uint32_t nsects,
5391 uint32_t flags, uint32_t object_size,
5392 bool verbose) {
5393 uint64_t expected_cmdsize;
5394 if (cmd == MachO::LC_SEGMENT) {
5395 outs() << " cmd LC_SEGMENT\n";
5396 expected_cmdsize = nsects;
5397 expected_cmdsize *= sizeof(struct MachO::section);
5398 expected_cmdsize += sizeof(struct MachO::segment_command);
5399 } else {
5400 outs() << " cmd LC_SEGMENT_64\n";
5401 expected_cmdsize = nsects;
5402 expected_cmdsize *= sizeof(struct MachO::section_64);
5403 expected_cmdsize += sizeof(struct MachO::segment_command_64);
5404 }
5405 outs() << " cmdsize " << cmdsize;
5406 if (cmdsize != expected_cmdsize)
5407 outs() << " Inconsistent size\n";
5408 else
5409 outs() << "\n";
5410 outs() << " segname " << SegName << "\n";
5411 if (cmd == MachO::LC_SEGMENT_64) {
5412 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
5413 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
5414 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00005415 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
5416 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00005417 }
5418 outs() << " fileoff " << fileoff;
5419 if (fileoff > object_size)
5420 outs() << " (past end of file)\n";
5421 else
5422 outs() << "\n";
5423 outs() << " filesize " << filesize;
5424 if (fileoff + filesize > object_size)
5425 outs() << " (past end of file)\n";
5426 else
5427 outs() << "\n";
5428 if (verbose) {
5429 if ((maxprot &
5430 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
5431 MachO::VM_PROT_EXECUTE)) != 0)
5432 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
5433 else {
5434 if (maxprot & MachO::VM_PROT_READ)
5435 outs() << " maxprot r";
5436 else
5437 outs() << " maxprot -";
5438 if (maxprot & MachO::VM_PROT_WRITE)
5439 outs() << "w";
5440 else
5441 outs() << "-";
5442 if (maxprot & MachO::VM_PROT_EXECUTE)
5443 outs() << "x\n";
5444 else
5445 outs() << "-\n";
5446 }
5447 if ((initprot &
5448 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
5449 MachO::VM_PROT_EXECUTE)) != 0)
5450 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
5451 else {
5452 if (initprot & MachO::VM_PROT_READ)
5453 outs() << " initprot r";
5454 else
5455 outs() << " initprot -";
5456 if (initprot & MachO::VM_PROT_WRITE)
5457 outs() << "w";
5458 else
5459 outs() << "-";
5460 if (initprot & MachO::VM_PROT_EXECUTE)
5461 outs() << "x\n";
5462 else
5463 outs() << "-\n";
5464 }
5465 } else {
5466 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
5467 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
5468 }
5469 outs() << " nsects " << nsects << "\n";
5470 if (verbose) {
5471 outs() << " flags";
5472 if (flags == 0)
5473 outs() << " (none)\n";
5474 else {
5475 if (flags & MachO::SG_HIGHVM) {
5476 outs() << " HIGHVM";
5477 flags &= ~MachO::SG_HIGHVM;
5478 }
5479 if (flags & MachO::SG_FVMLIB) {
5480 outs() << " FVMLIB";
5481 flags &= ~MachO::SG_FVMLIB;
5482 }
5483 if (flags & MachO::SG_NORELOC) {
5484 outs() << " NORELOC";
5485 flags &= ~MachO::SG_NORELOC;
5486 }
5487 if (flags & MachO::SG_PROTECTED_VERSION_1) {
5488 outs() << " PROTECTED_VERSION_1";
5489 flags &= ~MachO::SG_PROTECTED_VERSION_1;
5490 }
5491 if (flags)
5492 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
5493 else
5494 outs() << "\n";
5495 }
5496 } else {
5497 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
5498 }
5499}
5500
5501static void PrintSection(const char *sectname, const char *segname,
5502 uint64_t addr, uint64_t size, uint32_t offset,
5503 uint32_t align, uint32_t reloff, uint32_t nreloc,
5504 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
5505 uint32_t cmd, const char *sg_segname,
5506 uint32_t filetype, uint32_t object_size,
5507 bool verbose) {
5508 outs() << "Section\n";
5509 outs() << " sectname " << format("%.16s\n", sectname);
5510 outs() << " segname " << format("%.16s", segname);
5511 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
5512 outs() << " (does not match segment)\n";
5513 else
5514 outs() << "\n";
5515 if (cmd == MachO::LC_SEGMENT_64) {
5516 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
5517 outs() << " size " << format("0x%016" PRIx64, size);
5518 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00005519 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
5520 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00005521 }
5522 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
5523 outs() << " (past end of file)\n";
5524 else
5525 outs() << "\n";
5526 outs() << " offset " << offset;
5527 if (offset > object_size)
5528 outs() << " (past end of file)\n";
5529 else
5530 outs() << "\n";
5531 uint32_t align_shifted = 1 << align;
5532 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
5533 outs() << " reloff " << reloff;
5534 if (reloff > object_size)
5535 outs() << " (past end of file)\n";
5536 else
5537 outs() << "\n";
5538 outs() << " nreloc " << nreloc;
5539 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
5540 outs() << " (past end of file)\n";
5541 else
5542 outs() << "\n";
5543 uint32_t section_type = flags & MachO::SECTION_TYPE;
5544 if (verbose) {
5545 outs() << " type";
5546 if (section_type == MachO::S_REGULAR)
5547 outs() << " S_REGULAR\n";
5548 else if (section_type == MachO::S_ZEROFILL)
5549 outs() << " S_ZEROFILL\n";
5550 else if (section_type == MachO::S_CSTRING_LITERALS)
5551 outs() << " S_CSTRING_LITERALS\n";
5552 else if (section_type == MachO::S_4BYTE_LITERALS)
5553 outs() << " S_4BYTE_LITERALS\n";
5554 else if (section_type == MachO::S_8BYTE_LITERALS)
5555 outs() << " S_8BYTE_LITERALS\n";
5556 else if (section_type == MachO::S_16BYTE_LITERALS)
5557 outs() << " S_16BYTE_LITERALS\n";
5558 else if (section_type == MachO::S_LITERAL_POINTERS)
5559 outs() << " S_LITERAL_POINTERS\n";
5560 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
5561 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
5562 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
5563 outs() << " S_LAZY_SYMBOL_POINTERS\n";
5564 else if (section_type == MachO::S_SYMBOL_STUBS)
5565 outs() << " S_SYMBOL_STUBS\n";
5566 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
5567 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
5568 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
5569 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
5570 else if (section_type == MachO::S_COALESCED)
5571 outs() << " S_COALESCED\n";
5572 else if (section_type == MachO::S_INTERPOSING)
5573 outs() << " S_INTERPOSING\n";
5574 else if (section_type == MachO::S_DTRACE_DOF)
5575 outs() << " S_DTRACE_DOF\n";
5576 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
5577 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
5578 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
5579 outs() << " S_THREAD_LOCAL_REGULAR\n";
5580 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
5581 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
5582 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
5583 outs() << " S_THREAD_LOCAL_VARIABLES\n";
5584 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
5585 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
5586 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
5587 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
5588 else
5589 outs() << format("0x%08" PRIx32, section_type) << "\n";
5590 outs() << "attributes";
5591 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
5592 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
5593 outs() << " PURE_INSTRUCTIONS";
5594 if (section_attributes & MachO::S_ATTR_NO_TOC)
5595 outs() << " NO_TOC";
5596 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
5597 outs() << " STRIP_STATIC_SYMS";
5598 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
5599 outs() << " NO_DEAD_STRIP";
5600 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
5601 outs() << " LIVE_SUPPORT";
5602 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
5603 outs() << " SELF_MODIFYING_CODE";
5604 if (section_attributes & MachO::S_ATTR_DEBUG)
5605 outs() << " DEBUG";
5606 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
5607 outs() << " SOME_INSTRUCTIONS";
5608 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
5609 outs() << " EXT_RELOC";
5610 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
5611 outs() << " LOC_RELOC";
5612 if (section_attributes == 0)
5613 outs() << " (none)";
5614 outs() << "\n";
5615 } else
5616 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
5617 outs() << " reserved1 " << reserved1;
5618 if (section_type == MachO::S_SYMBOL_STUBS ||
5619 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
5620 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
5621 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
5622 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
5623 outs() << " (index into indirect symbol table)\n";
5624 else
5625 outs() << "\n";
5626 outs() << " reserved2 " << reserved2;
5627 if (section_type == MachO::S_SYMBOL_STUBS)
5628 outs() << " (size of stubs)\n";
5629 else
5630 outs() << "\n";
5631}
5632
David Majnemer73cc6ff2014-11-13 19:48:56 +00005633static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00005634 uint32_t object_size) {
5635 outs() << " cmd LC_SYMTAB\n";
5636 outs() << " cmdsize " << st.cmdsize;
5637 if (st.cmdsize != sizeof(struct MachO::symtab_command))
5638 outs() << " Incorrect size\n";
5639 else
5640 outs() << "\n";
5641 outs() << " symoff " << st.symoff;
5642 if (st.symoff > object_size)
5643 outs() << " (past end of file)\n";
5644 else
5645 outs() << "\n";
5646 outs() << " nsyms " << st.nsyms;
5647 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00005648 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00005649 big_size = st.nsyms;
5650 big_size *= sizeof(struct MachO::nlist_64);
5651 big_size += st.symoff;
5652 if (big_size > object_size)
5653 outs() << " (past end of file)\n";
5654 else
5655 outs() << "\n";
5656 } else {
5657 big_size = st.nsyms;
5658 big_size *= sizeof(struct MachO::nlist);
5659 big_size += st.symoff;
5660 if (big_size > object_size)
5661 outs() << " (past end of file)\n";
5662 else
5663 outs() << "\n";
5664 }
5665 outs() << " stroff " << st.stroff;
5666 if (st.stroff > object_size)
5667 outs() << " (past end of file)\n";
5668 else
5669 outs() << "\n";
5670 outs() << " strsize " << st.strsize;
5671 big_size = st.stroff;
5672 big_size += st.strsize;
5673 if (big_size > object_size)
5674 outs() << " (past end of file)\n";
5675 else
5676 outs() << "\n";
5677}
5678
5679static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
5680 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00005681 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00005682 outs() << " cmd LC_DYSYMTAB\n";
5683 outs() << " cmdsize " << dyst.cmdsize;
5684 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
5685 outs() << " Incorrect size\n";
5686 else
5687 outs() << "\n";
5688 outs() << " ilocalsym " << dyst.ilocalsym;
5689 if (dyst.ilocalsym > nsyms)
5690 outs() << " (greater than the number of symbols)\n";
5691 else
5692 outs() << "\n";
5693 outs() << " nlocalsym " << dyst.nlocalsym;
5694 uint64_t big_size;
5695 big_size = dyst.ilocalsym;
5696 big_size += dyst.nlocalsym;
5697 if (big_size > nsyms)
5698 outs() << " (past the end of the symbol table)\n";
5699 else
5700 outs() << "\n";
5701 outs() << " iextdefsym " << dyst.iextdefsym;
5702 if (dyst.iextdefsym > nsyms)
5703 outs() << " (greater than the number of symbols)\n";
5704 else
5705 outs() << "\n";
5706 outs() << " nextdefsym " << dyst.nextdefsym;
5707 big_size = dyst.iextdefsym;
5708 big_size += dyst.nextdefsym;
5709 if (big_size > nsyms)
5710 outs() << " (past the end of the symbol table)\n";
5711 else
5712 outs() << "\n";
5713 outs() << " iundefsym " << dyst.iundefsym;
5714 if (dyst.iundefsym > nsyms)
5715 outs() << " (greater than the number of symbols)\n";
5716 else
5717 outs() << "\n";
5718 outs() << " nundefsym " << dyst.nundefsym;
5719 big_size = dyst.iundefsym;
5720 big_size += dyst.nundefsym;
5721 if (big_size > nsyms)
5722 outs() << " (past the end of the symbol table)\n";
5723 else
5724 outs() << "\n";
5725 outs() << " tocoff " << dyst.tocoff;
5726 if (dyst.tocoff > object_size)
5727 outs() << " (past end of file)\n";
5728 else
5729 outs() << "\n";
5730 outs() << " ntoc " << dyst.ntoc;
5731 big_size = dyst.ntoc;
5732 big_size *= sizeof(struct MachO::dylib_table_of_contents);
5733 big_size += dyst.tocoff;
5734 if (big_size > object_size)
5735 outs() << " (past end of file)\n";
5736 else
5737 outs() << "\n";
5738 outs() << " modtaboff " << dyst.modtaboff;
5739 if (dyst.modtaboff > object_size)
5740 outs() << " (past end of file)\n";
5741 else
5742 outs() << "\n";
5743 outs() << " nmodtab " << dyst.nmodtab;
5744 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00005745 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00005746 modtabend = dyst.nmodtab;
5747 modtabend *= sizeof(struct MachO::dylib_module_64);
5748 modtabend += dyst.modtaboff;
5749 } else {
5750 modtabend = dyst.nmodtab;
5751 modtabend *= sizeof(struct MachO::dylib_module);
5752 modtabend += dyst.modtaboff;
5753 }
5754 if (modtabend > object_size)
5755 outs() << " (past end of file)\n";
5756 else
5757 outs() << "\n";
5758 outs() << " extrefsymoff " << dyst.extrefsymoff;
5759 if (dyst.extrefsymoff > object_size)
5760 outs() << " (past end of file)\n";
5761 else
5762 outs() << "\n";
5763 outs() << " nextrefsyms " << dyst.nextrefsyms;
5764 big_size = dyst.nextrefsyms;
5765 big_size *= sizeof(struct MachO::dylib_reference);
5766 big_size += dyst.extrefsymoff;
5767 if (big_size > object_size)
5768 outs() << " (past end of file)\n";
5769 else
5770 outs() << "\n";
5771 outs() << " indirectsymoff " << dyst.indirectsymoff;
5772 if (dyst.indirectsymoff > object_size)
5773 outs() << " (past end of file)\n";
5774 else
5775 outs() << "\n";
5776 outs() << " nindirectsyms " << dyst.nindirectsyms;
5777 big_size = dyst.nindirectsyms;
5778 big_size *= sizeof(uint32_t);
5779 big_size += dyst.indirectsymoff;
5780 if (big_size > object_size)
5781 outs() << " (past end of file)\n";
5782 else
5783 outs() << "\n";
5784 outs() << " extreloff " << dyst.extreloff;
5785 if (dyst.extreloff > object_size)
5786 outs() << " (past end of file)\n";
5787 else
5788 outs() << "\n";
5789 outs() << " nextrel " << dyst.nextrel;
5790 big_size = dyst.nextrel;
5791 big_size *= sizeof(struct MachO::relocation_info);
5792 big_size += dyst.extreloff;
5793 if (big_size > object_size)
5794 outs() << " (past end of file)\n";
5795 else
5796 outs() << "\n";
5797 outs() << " locreloff " << dyst.locreloff;
5798 if (dyst.locreloff > object_size)
5799 outs() << " (past end of file)\n";
5800 else
5801 outs() << "\n";
5802 outs() << " nlocrel " << dyst.nlocrel;
5803 big_size = dyst.nlocrel;
5804 big_size *= sizeof(struct MachO::relocation_info);
5805 big_size += dyst.locreloff;
5806 if (big_size > object_size)
5807 outs() << " (past end of file)\n";
5808 else
5809 outs() << "\n";
5810}
5811
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005812static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
5813 uint32_t object_size) {
5814 if (dc.cmd == MachO::LC_DYLD_INFO)
5815 outs() << " cmd LC_DYLD_INFO\n";
5816 else
5817 outs() << " cmd LC_DYLD_INFO_ONLY\n";
5818 outs() << " cmdsize " << dc.cmdsize;
5819 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
5820 outs() << " Incorrect size\n";
5821 else
5822 outs() << "\n";
5823 outs() << " rebase_off " << dc.rebase_off;
5824 if (dc.rebase_off > object_size)
5825 outs() << " (past end of file)\n";
5826 else
5827 outs() << "\n";
5828 outs() << " rebase_size " << dc.rebase_size;
5829 uint64_t big_size;
5830 big_size = dc.rebase_off;
5831 big_size += dc.rebase_size;
5832 if (big_size > object_size)
5833 outs() << " (past end of file)\n";
5834 else
5835 outs() << "\n";
5836 outs() << " bind_off " << dc.bind_off;
5837 if (dc.bind_off > object_size)
5838 outs() << " (past end of file)\n";
5839 else
5840 outs() << "\n";
5841 outs() << " bind_size " << dc.bind_size;
5842 big_size = dc.bind_off;
5843 big_size += dc.bind_size;
5844 if (big_size > object_size)
5845 outs() << " (past end of file)\n";
5846 else
5847 outs() << "\n";
5848 outs() << " weak_bind_off " << dc.weak_bind_off;
5849 if (dc.weak_bind_off > object_size)
5850 outs() << " (past end of file)\n";
5851 else
5852 outs() << "\n";
5853 outs() << " weak_bind_size " << dc.weak_bind_size;
5854 big_size = dc.weak_bind_off;
5855 big_size += dc.weak_bind_size;
5856 if (big_size > object_size)
5857 outs() << " (past end of file)\n";
5858 else
5859 outs() << "\n";
5860 outs() << " lazy_bind_off " << dc.lazy_bind_off;
5861 if (dc.lazy_bind_off > object_size)
5862 outs() << " (past end of file)\n";
5863 else
5864 outs() << "\n";
5865 outs() << " lazy_bind_size " << dc.lazy_bind_size;
5866 big_size = dc.lazy_bind_off;
5867 big_size += dc.lazy_bind_size;
5868 if (big_size > object_size)
5869 outs() << " (past end of file)\n";
5870 else
5871 outs() << "\n";
5872 outs() << " export_off " << dc.export_off;
5873 if (dc.export_off > object_size)
5874 outs() << " (past end of file)\n";
5875 else
5876 outs() << "\n";
5877 outs() << " export_size " << dc.export_size;
5878 big_size = dc.export_off;
5879 big_size += dc.export_size;
5880 if (big_size > object_size)
5881 outs() << " (past end of file)\n";
5882 else
5883 outs() << "\n";
5884}
5885
5886static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
5887 const char *Ptr) {
5888 if (dyld.cmd == MachO::LC_ID_DYLINKER)
5889 outs() << " cmd LC_ID_DYLINKER\n";
5890 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
5891 outs() << " cmd LC_LOAD_DYLINKER\n";
5892 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
5893 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
5894 else
5895 outs() << " cmd ?(" << dyld.cmd << ")\n";
5896 outs() << " cmdsize " << dyld.cmdsize;
5897 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
5898 outs() << " Incorrect size\n";
5899 else
5900 outs() << "\n";
5901 if (dyld.name >= dyld.cmdsize)
5902 outs() << " name ?(bad offset " << dyld.name << ")\n";
5903 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005904 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005905 outs() << " name " << P << " (offset " << dyld.name << ")\n";
5906 }
5907}
5908
5909static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
5910 outs() << " cmd LC_UUID\n";
5911 outs() << " cmdsize " << uuid.cmdsize;
5912 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
5913 outs() << " Incorrect size\n";
5914 else
5915 outs() << "\n";
5916 outs() << " uuid ";
5917 outs() << format("%02" PRIX32, uuid.uuid[0]);
5918 outs() << format("%02" PRIX32, uuid.uuid[1]);
5919 outs() << format("%02" PRIX32, uuid.uuid[2]);
5920 outs() << format("%02" PRIX32, uuid.uuid[3]);
5921 outs() << "-";
5922 outs() << format("%02" PRIX32, uuid.uuid[4]);
5923 outs() << format("%02" PRIX32, uuid.uuid[5]);
5924 outs() << "-";
5925 outs() << format("%02" PRIX32, uuid.uuid[6]);
5926 outs() << format("%02" PRIX32, uuid.uuid[7]);
5927 outs() << "-";
5928 outs() << format("%02" PRIX32, uuid.uuid[8]);
5929 outs() << format("%02" PRIX32, uuid.uuid[9]);
5930 outs() << "-";
5931 outs() << format("%02" PRIX32, uuid.uuid[10]);
5932 outs() << format("%02" PRIX32, uuid.uuid[11]);
5933 outs() << format("%02" PRIX32, uuid.uuid[12]);
5934 outs() << format("%02" PRIX32, uuid.uuid[13]);
5935 outs() << format("%02" PRIX32, uuid.uuid[14]);
5936 outs() << format("%02" PRIX32, uuid.uuid[15]);
5937 outs() << "\n";
5938}
5939
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005940static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00005941 outs() << " cmd LC_RPATH\n";
5942 outs() << " cmdsize " << rpath.cmdsize;
5943 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
5944 outs() << " Incorrect size\n";
5945 else
5946 outs() << "\n";
5947 if (rpath.path >= rpath.cmdsize)
5948 outs() << " path ?(bad offset " << rpath.path << ")\n";
5949 else {
5950 const char *P = (const char *)(Ptr) + rpath.path;
5951 outs() << " path " << P << " (offset " << rpath.path << ")\n";
5952 }
5953}
5954
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005955static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
5956 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
5957 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
5958 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
5959 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
5960 else
5961 outs() << " cmd " << vd.cmd << " (?)\n";
5962 outs() << " cmdsize " << vd.cmdsize;
5963 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
5964 outs() << " Incorrect size\n";
5965 else
5966 outs() << "\n";
5967 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
5968 << ((vd.version >> 8) & 0xff);
5969 if ((vd.version & 0xff) != 0)
5970 outs() << "." << (vd.version & 0xff);
5971 outs() << "\n";
5972 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00005973 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005974 else {
5975 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
5976 << ((vd.sdk >> 8) & 0xff);
5977 }
5978 if ((vd.sdk & 0xff) != 0)
5979 outs() << "." << (vd.sdk & 0xff);
5980 outs() << "\n";
5981}
5982
5983static void PrintSourceVersionCommand(MachO::source_version_command sd) {
5984 outs() << " cmd LC_SOURCE_VERSION\n";
5985 outs() << " cmdsize " << sd.cmdsize;
5986 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
5987 outs() << " Incorrect size\n";
5988 else
5989 outs() << "\n";
5990 uint64_t a = (sd.version >> 40) & 0xffffff;
5991 uint64_t b = (sd.version >> 30) & 0x3ff;
5992 uint64_t c = (sd.version >> 20) & 0x3ff;
5993 uint64_t d = (sd.version >> 10) & 0x3ff;
5994 uint64_t e = sd.version & 0x3ff;
5995 outs() << " version " << a << "." << b;
5996 if (e != 0)
5997 outs() << "." << c << "." << d << "." << e;
5998 else if (d != 0)
5999 outs() << "." << c << "." << d;
6000 else if (c != 0)
6001 outs() << "." << c;
6002 outs() << "\n";
6003}
6004
6005static void PrintEntryPointCommand(MachO::entry_point_command ep) {
6006 outs() << " cmd LC_MAIN\n";
6007 outs() << " cmdsize " << ep.cmdsize;
6008 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
6009 outs() << " Incorrect size\n";
6010 else
6011 outs() << "\n";
6012 outs() << " entryoff " << ep.entryoff << "\n";
6013 outs() << " stacksize " << ep.stacksize << "\n";
6014}
6015
Kevin Enderby0804f4672014-12-16 23:25:52 +00006016static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
6017 uint32_t object_size) {
6018 outs() << " cmd LC_ENCRYPTION_INFO\n";
6019 outs() << " cmdsize " << ec.cmdsize;
6020 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
6021 outs() << " Incorrect size\n";
6022 else
6023 outs() << "\n";
6024 outs() << " cryptoff " << ec.cryptoff;
6025 if (ec.cryptoff > object_size)
6026 outs() << " (past end of file)\n";
6027 else
6028 outs() << "\n";
6029 outs() << " cryptsize " << ec.cryptsize;
6030 if (ec.cryptsize > object_size)
6031 outs() << " (past end of file)\n";
6032 else
6033 outs() << "\n";
6034 outs() << " cryptid " << ec.cryptid << "\n";
6035}
6036
Kevin Enderby57538292014-12-17 01:01:30 +00006037static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006038 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00006039 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
6040 outs() << " cmdsize " << ec.cmdsize;
6041 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
6042 outs() << " Incorrect size\n";
6043 else
6044 outs() << "\n";
6045 outs() << " cryptoff " << ec.cryptoff;
6046 if (ec.cryptoff > object_size)
6047 outs() << " (past end of file)\n";
6048 else
6049 outs() << "\n";
6050 outs() << " cryptsize " << ec.cryptsize;
6051 if (ec.cryptsize > object_size)
6052 outs() << " (past end of file)\n";
6053 else
6054 outs() << "\n";
6055 outs() << " cryptid " << ec.cryptid << "\n";
6056 outs() << " pad " << ec.pad << "\n";
6057}
6058
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006059static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
6060 const char *Ptr) {
6061 outs() << " cmd LC_LINKER_OPTION\n";
6062 outs() << " cmdsize " << lo.cmdsize;
6063 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
6064 outs() << " Incorrect size\n";
6065 else
6066 outs() << "\n";
6067 outs() << " count " << lo.count << "\n";
6068 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
6069 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
6070 uint32_t i = 0;
6071 while (left > 0) {
6072 while (*string == '\0' && left > 0) {
6073 string++;
6074 left--;
6075 }
6076 if (left > 0) {
6077 i++;
6078 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00006079 uint32_t NullPos = StringRef(string, left).find('\0');
6080 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006081 string += len;
6082 left -= len;
6083 }
6084 }
6085 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006086 outs() << " count " << lo.count << " does not match number of strings "
6087 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006088}
6089
Kevin Enderbyb4b79312014-12-18 19:24:35 +00006090static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
6091 const char *Ptr) {
6092 outs() << " cmd LC_SUB_FRAMEWORK\n";
6093 outs() << " cmdsize " << sub.cmdsize;
6094 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
6095 outs() << " Incorrect size\n";
6096 else
6097 outs() << "\n";
6098 if (sub.umbrella < sub.cmdsize) {
6099 const char *P = Ptr + sub.umbrella;
6100 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
6101 } else {
6102 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
6103 }
6104}
6105
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00006106static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
6107 const char *Ptr) {
6108 outs() << " cmd LC_SUB_UMBRELLA\n";
6109 outs() << " cmdsize " << sub.cmdsize;
6110 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
6111 outs() << " Incorrect size\n";
6112 else
6113 outs() << "\n";
6114 if (sub.sub_umbrella < sub.cmdsize) {
6115 const char *P = Ptr + sub.sub_umbrella;
6116 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
6117 } else {
6118 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
6119 }
6120}
6121
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00006122static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006123 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00006124 outs() << " cmd LC_SUB_LIBRARY\n";
6125 outs() << " cmdsize " << sub.cmdsize;
6126 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
6127 outs() << " Incorrect size\n";
6128 else
6129 outs() << "\n";
6130 if (sub.sub_library < sub.cmdsize) {
6131 const char *P = Ptr + sub.sub_library;
6132 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
6133 } else {
6134 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
6135 }
6136}
6137
Kevin Enderby186eac32014-12-19 21:06:24 +00006138static void PrintSubClientCommand(MachO::sub_client_command sub,
6139 const char *Ptr) {
6140 outs() << " cmd LC_SUB_CLIENT\n";
6141 outs() << " cmdsize " << sub.cmdsize;
6142 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
6143 outs() << " Incorrect size\n";
6144 else
6145 outs() << "\n";
6146 if (sub.client < sub.cmdsize) {
6147 const char *P = Ptr + sub.client;
6148 outs() << " client " << P << " (offset " << sub.client << ")\n";
6149 } else {
6150 outs() << " client ?(bad offset " << sub.client << ")\n";
6151 }
6152}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00006153
Kevin Enderby52e4ce42014-12-19 22:25:22 +00006154static void PrintRoutinesCommand(MachO::routines_command r) {
6155 outs() << " cmd LC_ROUTINES\n";
6156 outs() << " cmdsize " << r.cmdsize;
6157 if (r.cmdsize != sizeof(struct MachO::routines_command))
6158 outs() << " Incorrect size\n";
6159 else
6160 outs() << "\n";
6161 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
6162 outs() << " init_module " << r.init_module << "\n";
6163 outs() << " reserved1 " << r.reserved1 << "\n";
6164 outs() << " reserved2 " << r.reserved2 << "\n";
6165 outs() << " reserved3 " << r.reserved3 << "\n";
6166 outs() << " reserved4 " << r.reserved4 << "\n";
6167 outs() << " reserved5 " << r.reserved5 << "\n";
6168 outs() << " reserved6 " << r.reserved6 << "\n";
6169}
6170
6171static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
6172 outs() << " cmd LC_ROUTINES_64\n";
6173 outs() << " cmdsize " << r.cmdsize;
6174 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
6175 outs() << " Incorrect size\n";
6176 else
6177 outs() << "\n";
6178 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
6179 outs() << " init_module " << r.init_module << "\n";
6180 outs() << " reserved1 " << r.reserved1 << "\n";
6181 outs() << " reserved2 " << r.reserved2 << "\n";
6182 outs() << " reserved3 " << r.reserved3 << "\n";
6183 outs() << " reserved4 " << r.reserved4 << "\n";
6184 outs() << " reserved5 " << r.reserved5 << "\n";
6185 outs() << " reserved6 " << r.reserved6 << "\n";
6186}
6187
Kevin Enderby48ef5342014-12-23 22:56:39 +00006188static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
6189 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
6190 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
6191 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
6192 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
6193 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
6194 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
6195 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
6196 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
6197 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
6198 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
6199 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
6200 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
6201 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
6202 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
6203 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
6204 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
6205 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
6206 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
6207 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
6208 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
6209 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
6210}
6211
Kevin Enderby227df342014-12-23 23:43:59 +00006212static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006213 uint32_t f;
6214 outs() << "\t mmst_reg ";
6215 for (f = 0; f < 10; f++)
6216 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
6217 outs() << "\n";
6218 outs() << "\t mmst_rsrv ";
6219 for (f = 0; f < 6; f++)
6220 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
6221 outs() << "\n";
6222}
6223
Kevin Enderbyaefb0032014-12-24 00:16:51 +00006224static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006225 uint32_t f;
6226 outs() << "\t xmm_reg ";
6227 for (f = 0; f < 16; f++)
6228 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
6229 outs() << "\n";
6230}
6231
6232static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
6233 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
6234 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
6235 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
6236 outs() << " denorm " << fpu.fpu_fcw.denorm;
6237 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
6238 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
6239 outs() << " undfl " << fpu.fpu_fcw.undfl;
6240 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
6241 outs() << "\t\t pc ";
6242 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
6243 outs() << "FP_PREC_24B ";
6244 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
6245 outs() << "FP_PREC_53B ";
6246 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
6247 outs() << "FP_PREC_64B ";
6248 else
6249 outs() << fpu.fpu_fcw.pc << " ";
6250 outs() << "rc ";
6251 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
6252 outs() << "FP_RND_NEAR ";
6253 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
6254 outs() << "FP_RND_DOWN ";
6255 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
6256 outs() << "FP_RND_UP ";
6257 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006258 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006259 outs() << "\n";
6260 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
6261 outs() << " denorm " << fpu.fpu_fsw.denorm;
6262 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
6263 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
6264 outs() << " undfl " << fpu.fpu_fsw.undfl;
6265 outs() << " precis " << fpu.fpu_fsw.precis;
6266 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
6267 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
6268 outs() << " c0 " << fpu.fpu_fsw.c0;
6269 outs() << " c1 " << fpu.fpu_fsw.c1;
6270 outs() << " c2 " << fpu.fpu_fsw.c2;
6271 outs() << " tos " << fpu.fpu_fsw.tos;
6272 outs() << " c3 " << fpu.fpu_fsw.c3;
6273 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
6274 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
6275 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
6276 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
6277 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
6278 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
6279 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
6280 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
6281 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
6282 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
6283 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
6284 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
6285 outs() << "\n";
6286 outs() << "\t fpu_stmm0:\n";
6287 Print_mmst_reg(fpu.fpu_stmm0);
6288 outs() << "\t fpu_stmm1:\n";
6289 Print_mmst_reg(fpu.fpu_stmm1);
6290 outs() << "\t fpu_stmm2:\n";
6291 Print_mmst_reg(fpu.fpu_stmm2);
6292 outs() << "\t fpu_stmm3:\n";
6293 Print_mmst_reg(fpu.fpu_stmm3);
6294 outs() << "\t fpu_stmm4:\n";
6295 Print_mmst_reg(fpu.fpu_stmm4);
6296 outs() << "\t fpu_stmm5:\n";
6297 Print_mmst_reg(fpu.fpu_stmm5);
6298 outs() << "\t fpu_stmm6:\n";
6299 Print_mmst_reg(fpu.fpu_stmm6);
6300 outs() << "\t fpu_stmm7:\n";
6301 Print_mmst_reg(fpu.fpu_stmm7);
6302 outs() << "\t fpu_xmm0:\n";
6303 Print_xmm_reg(fpu.fpu_xmm0);
6304 outs() << "\t fpu_xmm1:\n";
6305 Print_xmm_reg(fpu.fpu_xmm1);
6306 outs() << "\t fpu_xmm2:\n";
6307 Print_xmm_reg(fpu.fpu_xmm2);
6308 outs() << "\t fpu_xmm3:\n";
6309 Print_xmm_reg(fpu.fpu_xmm3);
6310 outs() << "\t fpu_xmm4:\n";
6311 Print_xmm_reg(fpu.fpu_xmm4);
6312 outs() << "\t fpu_xmm5:\n";
6313 Print_xmm_reg(fpu.fpu_xmm5);
6314 outs() << "\t fpu_xmm6:\n";
6315 Print_xmm_reg(fpu.fpu_xmm6);
6316 outs() << "\t fpu_xmm7:\n";
6317 Print_xmm_reg(fpu.fpu_xmm7);
6318 outs() << "\t fpu_xmm8:\n";
6319 Print_xmm_reg(fpu.fpu_xmm8);
6320 outs() << "\t fpu_xmm9:\n";
6321 Print_xmm_reg(fpu.fpu_xmm9);
6322 outs() << "\t fpu_xmm10:\n";
6323 Print_xmm_reg(fpu.fpu_xmm10);
6324 outs() << "\t fpu_xmm11:\n";
6325 Print_xmm_reg(fpu.fpu_xmm11);
6326 outs() << "\t fpu_xmm12:\n";
6327 Print_xmm_reg(fpu.fpu_xmm12);
6328 outs() << "\t fpu_xmm13:\n";
6329 Print_xmm_reg(fpu.fpu_xmm13);
6330 outs() << "\t fpu_xmm14:\n";
6331 Print_xmm_reg(fpu.fpu_xmm14);
6332 outs() << "\t fpu_xmm15:\n";
6333 Print_xmm_reg(fpu.fpu_xmm15);
6334 outs() << "\t fpu_rsrv4:\n";
6335 for (uint32_t f = 0; f < 6; f++) {
6336 outs() << "\t ";
6337 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006338 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006339 outs() << "\n";
6340 }
6341 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
6342 outs() << "\n";
6343}
6344
6345static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
6346 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
6347 outs() << " err " << format("0x%08" PRIx32, exc64.err);
6348 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
6349}
6350
6351static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
6352 bool isLittleEndian, uint32_t cputype) {
6353 if (t.cmd == MachO::LC_THREAD)
6354 outs() << " cmd LC_THREAD\n";
6355 else if (t.cmd == MachO::LC_UNIXTHREAD)
6356 outs() << " cmd LC_UNIXTHREAD\n";
6357 else
6358 outs() << " cmd " << t.cmd << " (unknown)\n";
6359 outs() << " cmdsize " << t.cmdsize;
6360 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
6361 outs() << " Incorrect size\n";
6362 else
6363 outs() << "\n";
6364
6365 const char *begin = Ptr + sizeof(struct MachO::thread_command);
6366 const char *end = Ptr + t.cmdsize;
6367 uint32_t flavor, count, left;
6368 if (cputype == MachO::CPU_TYPE_X86_64) {
6369 while (begin < end) {
6370 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
6371 memcpy((char *)&flavor, begin, sizeof(uint32_t));
6372 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006373 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006374 flavor = 0;
6375 begin = end;
6376 }
6377 if (isLittleEndian != sys::IsLittleEndianHost)
6378 sys::swapByteOrder(flavor);
6379 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
6380 memcpy((char *)&count, begin, sizeof(uint32_t));
6381 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006382 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006383 count = 0;
6384 begin = end;
6385 }
6386 if (isLittleEndian != sys::IsLittleEndianHost)
6387 sys::swapByteOrder(count);
6388 if (flavor == MachO::x86_THREAD_STATE64) {
6389 outs() << " flavor x86_THREAD_STATE64\n";
6390 if (count == MachO::x86_THREAD_STATE64_COUNT)
6391 outs() << " count x86_THREAD_STATE64_COUNT\n";
6392 else
6393 outs() << " count " << count
6394 << " (not x86_THREAD_STATE64_COUNT)\n";
6395 MachO::x86_thread_state64_t cpu64;
6396 left = end - begin;
6397 if (left >= sizeof(MachO::x86_thread_state64_t)) {
6398 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
6399 begin += sizeof(MachO::x86_thread_state64_t);
6400 } else {
6401 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
6402 memcpy(&cpu64, begin, left);
6403 begin += left;
6404 }
6405 if (isLittleEndian != sys::IsLittleEndianHost)
6406 swapStruct(cpu64);
6407 Print_x86_thread_state64_t(cpu64);
6408 } else if (flavor == MachO::x86_THREAD_STATE) {
6409 outs() << " flavor x86_THREAD_STATE\n";
6410 if (count == MachO::x86_THREAD_STATE_COUNT)
6411 outs() << " count x86_THREAD_STATE_COUNT\n";
6412 else
6413 outs() << " count " << count
6414 << " (not x86_THREAD_STATE_COUNT)\n";
6415 struct MachO::x86_thread_state_t ts;
6416 left = end - begin;
6417 if (left >= sizeof(MachO::x86_thread_state_t)) {
6418 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
6419 begin += sizeof(MachO::x86_thread_state_t);
6420 } else {
6421 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
6422 memcpy(&ts, begin, left);
6423 begin += left;
6424 }
6425 if (isLittleEndian != sys::IsLittleEndianHost)
6426 swapStruct(ts);
6427 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
6428 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
6429 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
6430 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
6431 else
6432 outs() << "tsh.count " << ts.tsh.count
6433 << " (not x86_THREAD_STATE64_COUNT\n";
6434 Print_x86_thread_state64_t(ts.uts.ts64);
6435 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006436 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
6437 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006438 }
6439 } else if (flavor == MachO::x86_FLOAT_STATE) {
6440 outs() << " flavor x86_FLOAT_STATE\n";
6441 if (count == MachO::x86_FLOAT_STATE_COUNT)
6442 outs() << " count x86_FLOAT_STATE_COUNT\n";
6443 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006444 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006445 struct MachO::x86_float_state_t fs;
6446 left = end - begin;
6447 if (left >= sizeof(MachO::x86_float_state_t)) {
6448 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
6449 begin += sizeof(MachO::x86_float_state_t);
6450 } else {
6451 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
6452 memcpy(&fs, begin, left);
6453 begin += left;
6454 }
6455 if (isLittleEndian != sys::IsLittleEndianHost)
6456 swapStruct(fs);
6457 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
6458 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006459 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00006460 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
6461 else
6462 outs() << "fsh.count " << fs.fsh.count
6463 << " (not x86_FLOAT_STATE64_COUNT\n";
6464 Print_x86_float_state_t(fs.ufs.fs64);
6465 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006466 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
6467 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006468 }
6469 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
6470 outs() << " flavor x86_EXCEPTION_STATE\n";
6471 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
6472 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
6473 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006474 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00006475 << " (not x86_EXCEPTION_STATE_COUNT)\n";
6476 struct MachO::x86_exception_state_t es;
6477 left = end - begin;
6478 if (left >= sizeof(MachO::x86_exception_state_t)) {
6479 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
6480 begin += sizeof(MachO::x86_exception_state_t);
6481 } else {
6482 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
6483 memcpy(&es, begin, left);
6484 begin += left;
6485 }
6486 if (isLittleEndian != sys::IsLittleEndianHost)
6487 swapStruct(es);
6488 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
6489 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006490 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00006491 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
6492 else
6493 outs() << "\t esh.count " << es.esh.count
6494 << " (not x86_EXCEPTION_STATE64_COUNT\n";
6495 Print_x86_exception_state_t(es.ues.es64);
6496 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006497 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
6498 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00006499 }
6500 } else {
6501 outs() << " flavor " << flavor << " (unknown)\n";
6502 outs() << " count " << count << "\n";
6503 outs() << " state (unknown)\n";
6504 begin += count * sizeof(uint32_t);
6505 }
6506 }
6507 } else {
6508 while (begin < end) {
6509 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
6510 memcpy((char *)&flavor, begin, sizeof(uint32_t));
6511 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006512 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006513 flavor = 0;
6514 begin = end;
6515 }
6516 if (isLittleEndian != sys::IsLittleEndianHost)
6517 sys::swapByteOrder(flavor);
6518 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
6519 memcpy((char *)&count, begin, sizeof(uint32_t));
6520 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006521 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00006522 count = 0;
6523 begin = end;
6524 }
6525 if (isLittleEndian != sys::IsLittleEndianHost)
6526 sys::swapByteOrder(count);
6527 outs() << " flavor " << flavor << "\n";
6528 outs() << " count " << count << "\n";
6529 outs() << " state (Unknown cputype/cpusubtype)\n";
6530 begin += count * sizeof(uint32_t);
6531 }
6532 }
6533}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006534
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006535static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
6536 if (dl.cmd == MachO::LC_ID_DYLIB)
6537 outs() << " cmd LC_ID_DYLIB\n";
6538 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
6539 outs() << " cmd LC_LOAD_DYLIB\n";
6540 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
6541 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
6542 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
6543 outs() << " cmd LC_REEXPORT_DYLIB\n";
6544 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
6545 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
6546 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
6547 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
6548 else
6549 outs() << " cmd " << dl.cmd << " (unknown)\n";
6550 outs() << " cmdsize " << dl.cmdsize;
6551 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
6552 outs() << " Incorrect size\n";
6553 else
6554 outs() << "\n";
6555 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006556 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006557 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
6558 } else {
6559 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
6560 }
6561 outs() << " time stamp " << dl.dylib.timestamp << " ";
6562 time_t t = dl.dylib.timestamp;
6563 outs() << ctime(&t);
6564 outs() << " current version ";
6565 if (dl.dylib.current_version == 0xffffffff)
6566 outs() << "n/a\n";
6567 else
6568 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
6569 << ((dl.dylib.current_version >> 8) & 0xff) << "."
6570 << (dl.dylib.current_version & 0xff) << "\n";
6571 outs() << "compatibility version ";
6572 if (dl.dylib.compatibility_version == 0xffffffff)
6573 outs() << "n/a\n";
6574 else
6575 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
6576 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
6577 << (dl.dylib.compatibility_version & 0xff) << "\n";
6578}
6579
6580static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
6581 uint32_t object_size) {
6582 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
6583 outs() << " cmd LC_FUNCTION_STARTS\n";
6584 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
6585 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
6586 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
6587 outs() << " cmd LC_FUNCTION_STARTS\n";
6588 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
6589 outs() << " cmd LC_DATA_IN_CODE\n";
6590 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
6591 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
6592 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
6593 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
6594 else
6595 outs() << " cmd " << ld.cmd << " (?)\n";
6596 outs() << " cmdsize " << ld.cmdsize;
6597 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
6598 outs() << " Incorrect size\n";
6599 else
6600 outs() << "\n";
6601 outs() << " dataoff " << ld.dataoff;
6602 if (ld.dataoff > object_size)
6603 outs() << " (past end of file)\n";
6604 else
6605 outs() << "\n";
6606 outs() << " datasize " << ld.datasize;
6607 uint64_t big_size = ld.dataoff;
6608 big_size += ld.datasize;
6609 if (big_size > object_size)
6610 outs() << " (past end of file)\n";
6611 else
6612 outs() << "\n";
6613}
6614
Kevin Enderby956366c2014-08-29 22:30:52 +00006615static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
6616 uint32_t filetype, uint32_t cputype,
6617 bool verbose) {
Filipe Cabecinhase71bd0c2015-01-06 17:08:26 +00006618 if (ncmds == 0)
6619 return;
Kevin Enderby956366c2014-08-29 22:30:52 +00006620 StringRef Buf = Obj->getData();
6621 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
6622 for (unsigned i = 0;; ++i) {
6623 outs() << "Load command " << i << "\n";
6624 if (Command.C.cmd == MachO::LC_SEGMENT) {
6625 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
6626 const char *sg_segname = SLC.segname;
6627 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
6628 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
6629 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
6630 verbose);
6631 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00006632 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00006633 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
6634 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
6635 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
6636 }
6637 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
6638 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
6639 const char *sg_segname = SLC_64.segname;
6640 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
6641 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
6642 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
6643 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
6644 for (unsigned j = 0; j < SLC_64.nsects; j++) {
6645 MachO::section_64 S_64 = Obj->getSection64(Command, j);
6646 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
6647 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
6648 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
6649 sg_segname, filetype, Buf.size(), verbose);
6650 }
6651 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
6652 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00006653 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00006654 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
6655 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
6656 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00006657 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
6658 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006659 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
6660 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
6661 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
6662 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
6663 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
6664 Command.C.cmd == MachO::LC_ID_DYLINKER ||
6665 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
6666 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
6667 PrintDyldLoadCommand(Dyld, Command.Ptr);
6668 } else if (Command.C.cmd == MachO::LC_UUID) {
6669 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
6670 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00006671 } else if (Command.C.cmd == MachO::LC_RPATH) {
6672 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
6673 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00006674 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
6675 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006676 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
6677 PrintVersionMinLoadCommand(Vd);
6678 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
6679 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
6680 PrintSourceVersionCommand(Sd);
6681 } else if (Command.C.cmd == MachO::LC_MAIN) {
6682 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
6683 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00006684 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006685 MachO::encryption_info_command Ei =
6686 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00006687 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00006688 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006689 MachO::encryption_info_command_64 Ei =
6690 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00006691 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006692 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00006693 MachO::linker_option_command Lo =
6694 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00006695 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00006696 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
6697 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
6698 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00006699 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
6700 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
6701 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00006702 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
6703 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
6704 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00006705 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
6706 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
6707 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00006708 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
6709 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
6710 PrintRoutinesCommand(Rc);
6711 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
6712 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
6713 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00006714 } else if (Command.C.cmd == MachO::LC_THREAD ||
6715 Command.C.cmd == MachO::LC_UNIXTHREAD) {
6716 MachO::thread_command Tc = Obj->getThreadCommand(Command);
6717 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00006718 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
6719 Command.C.cmd == MachO::LC_ID_DYLIB ||
6720 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
6721 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
6722 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
6723 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006724 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
6725 PrintDylibCommand(Dl, Command.Ptr);
6726 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
6727 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
6728 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
6729 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
6730 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
6731 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
6732 MachO::linkedit_data_command Ld =
6733 Obj->getLinkeditDataLoadCommand(Command);
6734 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00006735 } else {
6736 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
6737 << ")\n";
6738 outs() << " cmdsize " << Command.C.cmdsize << "\n";
6739 // TODO: get and print the raw bytes of the load command.
6740 }
6741 // TODO: print all the other kinds of load commands.
6742 if (i == ncmds - 1)
6743 break;
6744 else
6745 Command = Obj->getNextLoadCommandInfo(Command);
6746 }
6747}
6748
6749static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
6750 uint32_t &filetype, uint32_t &cputype,
6751 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006752 if (Obj->is64Bit()) {
6753 MachO::mach_header_64 H_64;
6754 H_64 = Obj->getHeader64();
6755 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
6756 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00006757 ncmds = H_64.ncmds;
6758 filetype = H_64.filetype;
6759 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006760 } else {
6761 MachO::mach_header H;
6762 H = Obj->getHeader();
6763 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
6764 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00006765 ncmds = H.ncmds;
6766 filetype = H.filetype;
6767 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006768 }
6769}
6770
6771void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
6772 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00006773 uint32_t ncmds = 0;
6774 uint32_t filetype = 0;
6775 uint32_t cputype = 0;
Kevin Enderbyf0640752015-03-13 17:56:32 +00006776 getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
6777 PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006778}
Nick Kledzikd04bc352014-08-30 00:20:14 +00006779
6780//===----------------------------------------------------------------------===//
6781// export trie dumping
6782//===----------------------------------------------------------------------===//
6783
6784void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006785 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
6786 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00006787 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
6788 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
6789 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
6790 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
6791 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
6792 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
6793 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
6794 if (ReExport)
6795 outs() << "[re-export] ";
6796 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006797 outs() << format("0x%08llX ",
6798 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006799 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00006800 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006801 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00006802 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00006803 if (WeakDef) {
6804 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006805 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00006806 }
6807 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006808 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00006809 outs() << ", ";
6810 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006811 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00006812 }
6813 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006814 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00006815 outs() << ", ";
6816 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006817 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00006818 }
6819 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006820 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00006821 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006822 outs() << format("resolver=0x%08llX", Entry.other());
6823 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00006824 }
6825 outs() << "]";
6826 }
6827 if (ReExport) {
6828 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006829 int Ordinal = Entry.other() - 1;
6830 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
6831 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00006832 outs() << " (from " << DylibName << ")";
6833 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00006834 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00006835 }
6836 outs() << "\n";
6837 }
6838}
Nick Kledzikac431442014-09-12 21:34:15 +00006839
Nick Kledzikac431442014-09-12 21:34:15 +00006840//===----------------------------------------------------------------------===//
6841// rebase table dumping
6842//===----------------------------------------------------------------------===//
6843
6844namespace {
6845class SegInfo {
6846public:
6847 SegInfo(const object::MachOObjectFile *Obj);
6848
6849 StringRef segmentName(uint32_t SegIndex);
6850 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
6851 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
6852
6853private:
6854 struct SectionInfo {
6855 uint64_t Address;
6856 uint64_t Size;
6857 StringRef SectionName;
6858 StringRef SegmentName;
6859 uint64_t OffsetInSegment;
6860 uint64_t SegmentStartAddress;
6861 uint32_t SegmentIndex;
6862 };
6863 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
6864 SmallVector<SectionInfo, 32> Sections;
6865};
6866}
6867
6868SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
6869 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00006870 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00006871 StringRef CurSegName;
6872 uint64_t CurSegAddress;
6873 for (const SectionRef &Section : Obj->sections()) {
6874 SectionInfo Info;
6875 if (error(Section.getName(Info.SectionName)))
6876 return;
Rafael Espindola80291272014-10-08 15:28:58 +00006877 Info.Address = Section.getAddress();
6878 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00006879 Info.SegmentName =
6880 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
6881 if (!Info.SegmentName.equals(CurSegName)) {
6882 ++CurSegIndex;
6883 CurSegName = Info.SegmentName;
6884 CurSegAddress = Info.Address;
6885 }
6886 Info.SegmentIndex = CurSegIndex - 1;
6887 Info.OffsetInSegment = Info.Address - CurSegAddress;
6888 Info.SegmentStartAddress = CurSegAddress;
6889 Sections.push_back(Info);
6890 }
6891}
6892
6893StringRef SegInfo::segmentName(uint32_t SegIndex) {
6894 for (const SectionInfo &SI : Sections) {
6895 if (SI.SegmentIndex == SegIndex)
6896 return SI.SegmentName;
6897 }
6898 llvm_unreachable("invalid segIndex");
6899}
6900
6901const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
6902 uint64_t OffsetInSeg) {
6903 for (const SectionInfo &SI : Sections) {
6904 if (SI.SegmentIndex != SegIndex)
6905 continue;
6906 if (SI.OffsetInSegment > OffsetInSeg)
6907 continue;
6908 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
6909 continue;
6910 return SI;
6911 }
6912 llvm_unreachable("segIndex and offset not in any section");
6913}
6914
6915StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
6916 return findSection(SegIndex, OffsetInSeg).SectionName;
6917}
6918
6919uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
6920 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
6921 return SI.SegmentStartAddress + OffsetInSeg;
6922}
6923
6924void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
6925 // Build table of sections so names can used in final output.
6926 SegInfo sectionTable(Obj);
6927
6928 outs() << "segment section address type\n";
6929 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
6930 uint32_t SegIndex = Entry.segmentIndex();
6931 uint64_t OffsetInSeg = Entry.segmentOffset();
6932 StringRef SegmentName = sectionTable.segmentName(SegIndex);
6933 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
6934 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
6935
6936 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006937 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
6938 SegmentName.str().c_str(), SectionName.str().c_str(),
6939 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00006940 }
6941}
Nick Kledzik56ebef42014-09-16 01:41:51 +00006942
6943static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
6944 StringRef DylibName;
6945 switch (Ordinal) {
6946 case MachO::BIND_SPECIAL_DYLIB_SELF:
6947 return "this-image";
6948 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
6949 return "main-executable";
6950 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
6951 return "flat-namespace";
6952 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00006953 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006954 std::error_code EC =
6955 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00006956 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00006957 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00006958 return DylibName;
6959 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00006960 }
Nick Kledzikabd29872014-09-16 22:03:13 +00006961 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00006962}
6963
6964//===----------------------------------------------------------------------===//
6965// bind table dumping
6966//===----------------------------------------------------------------------===//
6967
6968void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
6969 // Build table of sections so names can used in final output.
6970 SegInfo sectionTable(Obj);
6971
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006972 outs() << "segment section address type "
6973 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00006974 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
6975 uint32_t SegIndex = Entry.segmentIndex();
6976 uint64_t OffsetInSeg = Entry.segmentOffset();
6977 StringRef SegmentName = sectionTable.segmentName(SegIndex);
6978 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
6979 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
6980
6981 // Table lines look like:
6982 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006983 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00006984 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006985 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006986 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006987 << left_justify(SectionName, 18) << " "
6988 << format_hex(Address, 10, true) << " "
6989 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006990 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00006991 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006992 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00006993 }
6994}
6995
6996//===----------------------------------------------------------------------===//
6997// lazy bind table dumping
6998//===----------------------------------------------------------------------===//
6999
7000void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
7001 // Build table of sections so names can used in final output.
7002 SegInfo sectionTable(Obj);
7003
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007004 outs() << "segment section address "
7005 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00007006 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
7007 uint32_t SegIndex = Entry.segmentIndex();
7008 uint64_t OffsetInSeg = Entry.segmentOffset();
7009 StringRef SegmentName = sectionTable.segmentName(SegIndex);
7010 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
7011 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
7012
7013 // Table lines look like:
7014 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007015 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007016 << left_justify(SectionName, 18) << " "
7017 << format_hex(Address, 10, true) << " "
7018 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00007019 << Entry.symbolName() << "\n";
7020 }
7021}
7022
Nick Kledzik56ebef42014-09-16 01:41:51 +00007023//===----------------------------------------------------------------------===//
7024// weak bind table dumping
7025//===----------------------------------------------------------------------===//
7026
7027void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
7028 // Build table of sections so names can used in final output.
7029 SegInfo sectionTable(Obj);
7030
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007031 outs() << "segment section address "
7032 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00007033 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
7034 // Strong symbols don't have a location to update.
7035 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007036 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00007037 << Entry.symbolName() << "\n";
7038 continue;
7039 }
7040 uint32_t SegIndex = Entry.segmentIndex();
7041 uint64_t OffsetInSeg = Entry.segmentOffset();
7042 StringRef SegmentName = sectionTable.segmentName(SegIndex);
7043 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
7044 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
7045
7046 // Table lines look like:
7047 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007048 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00007049 << left_justify(SectionName, 18) << " "
7050 << format_hex(Address, 10, true) << " "
7051 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007052 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
7053 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00007054 }
7055}
7056
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007057// get_dyld_bind_info_symbolname() is used for disassembly and passed an
7058// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
7059// information for that address. If the address is found its binding symbol
7060// name is returned. If not nullptr is returned.
7061static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
7062 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00007063 if (info->bindtable == nullptr) {
7064 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007065 SegInfo sectionTable(info->O);
7066 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
7067 uint32_t SegIndex = Entry.segmentIndex();
7068 uint64_t OffsetInSeg = Entry.segmentOffset();
7069 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
7070 const char *SymbolName = nullptr;
7071 StringRef name = Entry.symbolName();
7072 if (!name.empty())
7073 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00007074 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007075 }
7076 }
Kevin Enderby078be602014-10-23 19:53:12 +00007077 for (bind_table_iterator BI = info->bindtable->begin(),
7078 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007079 BI != BE; ++BI) {
7080 uint64_t Address = BI->first;
7081 if (ReferenceValue == Address) {
7082 const char *SymbolName = BI->second;
7083 return SymbolName;
7084 }
7085 }
7086 return nullptr;
7087}