blob: 12aab62fde7a051fcc8c60b48301c07cad2231f7 [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 Enderby6a221752015-03-17 17:10:57 +0000125cl::opt<std::string> llvm::DisSymName(
126 "dis-symname",
127 cl::desc("disassemble just this symbol's instructions (requires -macho"));
128
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000129static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
132
133
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000134static cl::list<std::string>
135 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
136 cl::ZeroOrMore);
137bool ArchAll = false;
138
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000139static std::string ThumbTripleName;
140
141static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000144 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000145 if (TripleName.empty()) {
146 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000147 llvm::Triple ThumbTriple = Triple();
148 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000149 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000150 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000151 }
152
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000153 // Get the target specific parser.
154 std::string Error;
155 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000156 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 return TheTarget;
158
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000159 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
160 if (*ThumbTarget)
161 return TheTarget;
162
163 errs() << "llvm-objdump: error: unable to get target for '";
164 if (!TheTarget)
165 errs() << TripleName;
166 else
167 errs() << ThumbTripleName;
168 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000169 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000170}
171
Owen Andersond9243c42011-10-17 21:37:35 +0000172struct SymbolSorter {
173 bool operator()(const SymbolRef &A, const SymbolRef &B) {
174 SymbolRef::Type AType, BType;
175 A.getType(AType);
176 B.getType(BType);
177
178 uint64_t AAddr, BAddr;
179 if (AType != SymbolRef::ST_Function)
180 AAddr = 0;
181 else
182 A.getAddress(AAddr);
183 if (BType != SymbolRef::ST_Function)
184 BAddr = 0;
185 else
186 B.getAddress(BAddr);
187 return AAddr < BAddr;
188 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000189};
190
Kevin Enderby273ae012013-06-06 17:20:50 +0000191// Types for the storted data in code table that is built before disassembly
192// and the predicate function to sort them.
193typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
194typedef std::vector<DiceTableEntry> DiceTable;
195typedef DiceTable::iterator dice_table_iterator;
196
Kevin Enderby930fdc72014-11-06 19:00:13 +0000197// This is used to search for a data in code table entry for the PC being
198// disassembled. The j parameter has the PC in j.first. A single data in code
199// table entry can cover many bytes for each of its Kind's. So if the offset,
200// aka the i.first value, of the data in code table entry plus its Length
201// covers the PC being searched for this will return true. If not it will
202// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000203static bool compareDiceTableEntries(const DiceTableEntry &i,
204 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000205 uint16_t Length;
206 i.second.getLength(Length);
207
208 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000209}
210
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000211static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000212 unsigned short Kind) {
213 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000214
215 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000216 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000217 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000218 if (Length >= 4) {
219 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000220 DumpBytes(ArrayRef<uint8_t>(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000221 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000222 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000223 Size = 4;
224 } else if (Length >= 2) {
225 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000226 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000227 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000228 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000229 Size = 2;
230 } else {
231 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000232 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
Kevin Enderby273ae012013-06-06 17:20:50 +0000233 Value = bytes[0];
234 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000235 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000236 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 if (Kind == MachO::DICE_KIND_DATA)
238 outs() << "\t@ KIND_DATA\n";
239 else
240 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000241 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000242 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000243 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000244 DumpBytes(ArrayRef<uint8_t>(bytes, 1));
Kevin Enderby273ae012013-06-06 17:20:50 +0000245 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000246 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
247 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000248 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000249 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000251 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000252 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000253 outs() << "\t.short " << format("%5u", Value & 0xffff)
254 << "\t@ KIND_JUMP_TABLE16\n";
255 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000256 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000257 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000258 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
259 if (!NoShowRawInsn)
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000260 DumpBytes(ArrayRef<uint8_t>(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000261 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000262 outs() << "\t.long " << Value;
263 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
264 outs() << "\t@ KIND_JUMP_TABLE32\n";
265 else
266 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
267 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000268 break;
269 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000270 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000271}
272
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000273static void getSectionsAndSymbols(const MachO::mach_header Header,
274 MachOObjectFile *MachOObj,
275 std::vector<SectionRef> &Sections,
276 std::vector<SymbolRef> &Symbols,
277 SmallVectorImpl<uint64_t> &FoundFns,
278 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000279 for (const SymbolRef &Symbol : MachOObj->symbols()) {
280 StringRef SymName;
281 Symbol.getName(SymName);
282 if (!SymName.startswith("ltmp"))
283 Symbols.push_back(Symbol);
284 }
Owen Andersond9243c42011-10-17 21:37:35 +0000285
Alexey Samsonov48803e52014-03-13 14:37:36 +0000286 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000287 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000288 Section.getName(SectName);
289 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000290 }
291
Rafael Espindola56f976f2013-04-18 18:08:55 +0000292 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000293 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000294 bool BaseSegmentAddressSet = false;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000295 for (unsigned i = 0;; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000296 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000297 // We found a function starts segment, parse the addresses for later
298 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000299 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000300 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000301
Charles Davis8bdfafd2013-09-01 04:28:48 +0000302 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000303 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
304 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000305 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000306 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000307 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000308 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000309 }
310 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000311
Charles Davis8bdfafd2013-09-01 04:28:48 +0000312 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000313 break;
314 else
315 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000316 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000317}
318
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000319static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
320 uint32_t n, uint32_t count,
321 uint32_t stride, uint64_t addr) {
322 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
323 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
324 if (n > nindirectsyms)
325 outs() << " (entries start past the end of the indirect symbol "
326 "table) (reserved1 field greater than the table size)";
327 else if (n + count > nindirectsyms)
328 outs() << " (entries extends past the end of the indirect symbol "
329 "table)";
330 outs() << "\n";
331 uint32_t cputype = O->getHeader().cputype;
332 if (cputype & MachO::CPU_ARCH_ABI64)
333 outs() << "address index";
334 else
335 outs() << "address index";
336 if (verbose)
337 outs() << " name\n";
338 else
339 outs() << "\n";
340 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
341 if (cputype & MachO::CPU_ARCH_ABI64)
342 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
343 else
344 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
345 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
346 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
347 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
348 outs() << "LOCAL\n";
349 continue;
350 }
351 if (indirect_symbol ==
352 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
353 outs() << "LOCAL ABSOLUTE\n";
354 continue;
355 }
356 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
357 outs() << "ABSOLUTE\n";
358 continue;
359 }
360 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000361 if (verbose) {
362 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
363 if (indirect_symbol < Symtab.nsyms) {
364 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
365 SymbolRef Symbol = *Sym;
366 StringRef SymName;
367 Symbol.getName(SymName);
368 outs() << SymName;
369 } else {
370 outs() << "?";
371 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000372 }
373 outs() << "\n";
374 }
375}
376
377static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
378 uint32_t LoadCommandCount = O->getHeader().ncmds;
379 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
380 for (unsigned I = 0;; ++I) {
381 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
382 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
383 for (unsigned J = 0; J < Seg.nsects; ++J) {
384 MachO::section_64 Sec = O->getSection64(Load, J);
385 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
386 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
387 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
388 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
389 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
390 section_type == MachO::S_SYMBOL_STUBS) {
391 uint32_t stride;
392 if (section_type == MachO::S_SYMBOL_STUBS)
393 stride = Sec.reserved2;
394 else
395 stride = 8;
396 if (stride == 0) {
397 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
398 << Sec.sectname << ") "
399 << "(size of stubs in reserved2 field is zero)\n";
400 continue;
401 }
402 uint32_t count = Sec.size / stride;
403 outs() << "Indirect symbols for (" << Sec.segname << ","
404 << Sec.sectname << ") " << count << " entries";
405 uint32_t n = Sec.reserved1;
406 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
407 }
408 }
409 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
410 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
411 for (unsigned J = 0; J < Seg.nsects; ++J) {
412 MachO::section Sec = O->getSection(Load, J);
413 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
414 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
415 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
416 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
417 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
418 section_type == MachO::S_SYMBOL_STUBS) {
419 uint32_t stride;
420 if (section_type == MachO::S_SYMBOL_STUBS)
421 stride = Sec.reserved2;
422 else
423 stride = 4;
424 if (stride == 0) {
425 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
426 << Sec.sectname << ") "
427 << "(size of stubs in reserved2 field is zero)\n";
428 continue;
429 }
430 uint32_t count = Sec.size / stride;
431 outs() << "Indirect symbols for (" << Sec.segname << ","
432 << Sec.sectname << ") " << count << " entries";
433 uint32_t n = Sec.reserved1;
434 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
435 }
436 }
437 }
438 if (I == LoadCommandCount - 1)
439 break;
440 else
441 Load = O->getNextLoadCommandInfo(Load);
442 }
443}
444
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000445static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
446 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
447 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
448 outs() << "Data in code table (" << nentries << " entries)\n";
449 outs() << "offset length kind\n";
450 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
451 ++DI) {
452 uint32_t Offset;
453 DI->getOffset(Offset);
454 outs() << format("0x%08" PRIx32, Offset) << " ";
455 uint16_t Length;
456 DI->getLength(Length);
457 outs() << format("%6u", Length) << " ";
458 uint16_t Kind;
459 DI->getKind(Kind);
460 if (verbose) {
461 switch (Kind) {
462 case MachO::DICE_KIND_DATA:
463 outs() << "DATA";
464 break;
465 case MachO::DICE_KIND_JUMP_TABLE8:
466 outs() << "JUMP_TABLE8";
467 break;
468 case MachO::DICE_KIND_JUMP_TABLE16:
469 outs() << "JUMP_TABLE16";
470 break;
471 case MachO::DICE_KIND_JUMP_TABLE32:
472 outs() << "JUMP_TABLE32";
473 break;
474 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
475 outs() << "ABS_JUMP_TABLE32";
476 break;
477 default:
478 outs() << format("0x%04" PRIx32, Kind);
479 break;
480 }
481 } else
482 outs() << format("0x%04" PRIx32, Kind);
483 outs() << "\n";
484 }
485}
486
Kevin Enderby9a509442015-01-27 21:28:24 +0000487static void PrintLinkOptHints(MachOObjectFile *O) {
488 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
489 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
490 uint32_t nloh = LohLC.datasize;
491 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
492 for (uint32_t i = 0; i < nloh;) {
493 unsigned n;
494 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
495 i += n;
496 outs() << " identifier " << identifier << " ";
497 if (i >= nloh)
498 return;
499 switch (identifier) {
500 case 1:
501 outs() << "AdrpAdrp\n";
502 break;
503 case 2:
504 outs() << "AdrpLdr\n";
505 break;
506 case 3:
507 outs() << "AdrpAddLdr\n";
508 break;
509 case 4:
510 outs() << "AdrpLdrGotLdr\n";
511 break;
512 case 5:
513 outs() << "AdrpAddStr\n";
514 break;
515 case 6:
516 outs() << "AdrpLdrGotStr\n";
517 break;
518 case 7:
519 outs() << "AdrpAdd\n";
520 break;
521 case 8:
522 outs() << "AdrpLdrGot\n";
523 break;
524 default:
525 outs() << "Unknown identifier value\n";
526 break;
527 }
528 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
529 i += n;
530 outs() << " narguments " << narguments << "\n";
531 if (i >= nloh)
532 return;
533
534 for (uint32_t j = 0; j < narguments; j++) {
535 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
536 i += n;
537 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
538 if (i >= nloh)
539 return;
540 }
541 }
542}
543
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000544static void PrintDylibs(MachOObjectFile *O, bool JustId) {
545 uint32_t LoadCommandCount = O->getHeader().ncmds;
546 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
547 for (unsigned I = 0;; ++I) {
548 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
549 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
550 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
551 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
552 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
553 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
554 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
555 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
556 if (dl.dylib.name < dl.cmdsize) {
557 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
558 if (JustId)
559 outs() << p << "\n";
560 else {
561 outs() << "\t" << p;
562 outs() << " (compatibility version "
563 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
564 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
565 << (dl.dylib.compatibility_version & 0xff) << ",";
566 outs() << " current version "
567 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
568 << ((dl.dylib.current_version >> 8) & 0xff) << "."
569 << (dl.dylib.current_version & 0xff) << ")\n";
570 }
571 } else {
572 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
573 if (Load.C.cmd == MachO::LC_ID_DYLIB)
574 outs() << "LC_ID_DYLIB ";
575 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
576 outs() << "LC_LOAD_DYLIB ";
577 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
578 outs() << "LC_LOAD_WEAK_DYLIB ";
579 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
580 outs() << "LC_LAZY_LOAD_DYLIB ";
581 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
582 outs() << "LC_REEXPORT_DYLIB ";
583 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
584 outs() << "LC_LOAD_UPWARD_DYLIB ";
585 else
586 outs() << "LC_??? ";
587 outs() << "command " << I << "\n";
588 }
589 }
590 if (I == LoadCommandCount - 1)
591 break;
592 else
593 Load = O->getNextLoadCommandInfo(Load);
594 }
595}
596
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000597typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
598
599static void CreateSymbolAddressMap(MachOObjectFile *O,
600 SymbolAddressMap *AddrMap) {
601 // Create a map of symbol addresses to symbol names.
602 for (const SymbolRef &Symbol : O->symbols()) {
603 SymbolRef::Type ST;
604 Symbol.getType(ST);
605 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
606 ST == SymbolRef::ST_Other) {
607 uint64_t Address;
608 Symbol.getAddress(Address);
609 StringRef SymName;
610 Symbol.getName(SymName);
611 (*AddrMap)[Address] = SymName;
612 }
613 }
614}
615
616// GuessSymbolName is passed the address of what might be a symbol and a
617// pointer to the SymbolAddressMap. It returns the name of a symbol
618// with that address or nullptr if no symbol is found with that address.
619static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
620 const char *SymbolName = nullptr;
621 // A DenseMap can't lookup up some values.
622 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
623 StringRef name = AddrMap->lookup(value);
624 if (!name.empty())
625 SymbolName = name.data();
626 }
627 return SymbolName;
628}
629
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000630static void DumpCstringChar(const char c) {
631 char p[2];
632 p[0] = c;
633 p[1] = '\0';
634 outs().write_escaped(p);
635}
636
Kevin Enderby10ba0412015-02-04 21:38:42 +0000637static void DumpCstringSection(MachOObjectFile *O, const char *sect,
638 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000639 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000640 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000641 if (print_addresses) {
642 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000643 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000644 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000645 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000646 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000647 for (; i < sect_size && sect[i] != '\0'; i++)
648 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000649 if (i < sect_size && sect[i] == '\0')
650 outs() << "\n";
651 }
652}
653
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000654static void DumpLiteral4(uint32_t l, float f) {
655 outs() << format("0x%08" PRIx32, l);
656 if ((l & 0x7f800000) != 0x7f800000)
657 outs() << format(" (%.16e)\n", f);
658 else {
659 if (l == 0x7f800000)
660 outs() << " (+Infinity)\n";
661 else if (l == 0xff800000)
662 outs() << " (-Infinity)\n";
663 else if ((l & 0x00400000) == 0x00400000)
664 outs() << " (non-signaling Not-a-Number)\n";
665 else
666 outs() << " (signaling Not-a-Number)\n";
667 }
668}
669
670static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
671 uint32_t sect_size, uint64_t sect_addr,
672 bool print_addresses) {
673 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
674 if (print_addresses) {
675 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000676 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000677 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000678 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000679 }
680 float f;
681 memcpy(&f, sect + i, sizeof(float));
682 if (O->isLittleEndian() != sys::IsLittleEndianHost)
683 sys::swapByteOrder(f);
684 uint32_t l;
685 memcpy(&l, sect + i, sizeof(uint32_t));
686 if (O->isLittleEndian() != sys::IsLittleEndianHost)
687 sys::swapByteOrder(l);
688 DumpLiteral4(l, f);
689 }
690}
691
692static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
693 double d) {
694 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
695 uint32_t Hi, Lo;
696 if (O->isLittleEndian()) {
697 Hi = l1;
698 Lo = l0;
699 } else {
700 Hi = l0;
701 Lo = l1;
702 }
703 // Hi is the high word, so this is equivalent to if(isfinite(d))
704 if ((Hi & 0x7ff00000) != 0x7ff00000)
705 outs() << format(" (%.16e)\n", d);
706 else {
707 if (Hi == 0x7ff00000 && Lo == 0)
708 outs() << " (+Infinity)\n";
709 else if (Hi == 0xfff00000 && Lo == 0)
710 outs() << " (-Infinity)\n";
711 else if ((Hi & 0x00080000) == 0x00080000)
712 outs() << " (non-signaling Not-a-Number)\n";
713 else
714 outs() << " (signaling Not-a-Number)\n";
715 }
716}
717
718static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
719 uint32_t sect_size, uint64_t sect_addr,
720 bool print_addresses) {
721 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
722 if (print_addresses) {
723 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000724 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000725 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000726 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000727 }
728 double d;
729 memcpy(&d, sect + i, sizeof(double));
730 if (O->isLittleEndian() != sys::IsLittleEndianHost)
731 sys::swapByteOrder(d);
732 uint32_t l0, l1;
733 memcpy(&l0, sect + i, sizeof(uint32_t));
734 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
735 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
736 sys::swapByteOrder(l0);
737 sys::swapByteOrder(l1);
738 }
739 DumpLiteral8(O, l0, l1, d);
740 }
741}
742
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000743static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
744 outs() << format("0x%08" PRIx32, l0) << " ";
745 outs() << format("0x%08" PRIx32, l1) << " ";
746 outs() << format("0x%08" PRIx32, l2) << " ";
747 outs() << format("0x%08" PRIx32, l3) << "\n";
748}
749
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000750static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
751 uint32_t sect_size, uint64_t sect_addr,
752 bool print_addresses) {
753 for (uint32_t i = 0; i < sect_size; i += 16) {
754 if (print_addresses) {
755 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000756 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000757 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000758 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000759 }
760 uint32_t l0, l1, l2, l3;
761 memcpy(&l0, sect + i, sizeof(uint32_t));
762 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
763 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
764 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
765 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
766 sys::swapByteOrder(l0);
767 sys::swapByteOrder(l1);
768 sys::swapByteOrder(l2);
769 sys::swapByteOrder(l3);
770 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000771 DumpLiteral16(l0, l1, l2, l3);
772 }
773}
774
775static void DumpLiteralPointerSection(MachOObjectFile *O,
776 const SectionRef &Section,
777 const char *sect, uint32_t sect_size,
778 uint64_t sect_addr,
779 bool print_addresses) {
780 // Collect the literal sections in this Mach-O file.
781 std::vector<SectionRef> LiteralSections;
782 for (const SectionRef &Section : O->sections()) {
783 DataRefImpl Ref = Section.getRawDataRefImpl();
784 uint32_t section_type;
785 if (O->is64Bit()) {
786 const MachO::section_64 Sec = O->getSection64(Ref);
787 section_type = Sec.flags & MachO::SECTION_TYPE;
788 } else {
789 const MachO::section Sec = O->getSection(Ref);
790 section_type = Sec.flags & MachO::SECTION_TYPE;
791 }
792 if (section_type == MachO::S_CSTRING_LITERALS ||
793 section_type == MachO::S_4BYTE_LITERALS ||
794 section_type == MachO::S_8BYTE_LITERALS ||
795 section_type == MachO::S_16BYTE_LITERALS)
796 LiteralSections.push_back(Section);
797 }
798
799 // Set the size of the literal pointer.
800 uint32_t lp_size = O->is64Bit() ? 8 : 4;
801
802 // Collect the external relocation symbols for the the literal pointers.
803 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
804 for (const RelocationRef &Reloc : Section.relocations()) {
805 DataRefImpl Rel;
806 MachO::any_relocation_info RE;
807 bool isExtern = false;
808 Rel = Reloc.getRawDataRefImpl();
809 RE = O->getRelocation(Rel);
810 isExtern = O->getPlainRelocationExternal(RE);
811 if (isExtern) {
812 uint64_t RelocOffset;
813 Reloc.getOffset(RelocOffset);
814 symbol_iterator RelocSym = Reloc.getSymbol();
815 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
816 }
817 }
818 array_pod_sort(Relocs.begin(), Relocs.end());
819
820 // Dump each literal pointer.
821 for (uint32_t i = 0; i < sect_size; i += lp_size) {
822 if (print_addresses) {
823 if (O->is64Bit())
824 outs() << format("%016" PRIx64, sect_addr + i) << " ";
825 else
826 outs() << format("%08" PRIx64, sect_addr + i) << " ";
827 }
828 uint64_t lp;
829 if (O->is64Bit()) {
830 memcpy(&lp, sect + i, sizeof(uint64_t));
831 if (O->isLittleEndian() != sys::IsLittleEndianHost)
832 sys::swapByteOrder(lp);
833 } else {
834 uint32_t li;
835 memcpy(&li, sect + i, sizeof(uint32_t));
836 if (O->isLittleEndian() != sys::IsLittleEndianHost)
837 sys::swapByteOrder(li);
838 lp = li;
839 }
840
841 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000842 auto Reloc = std::find_if(
843 Relocs.begin(), Relocs.end(),
844 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
845 if (Reloc != Relocs.end()) {
846 symbol_iterator RelocSym = Reloc->second;
847 StringRef SymName;
848 RelocSym->getName(SymName);
849 outs() << "external relocation entry for symbol:" << SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000850 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000851 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000852
853 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000854 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
855 [&](const SectionRef &R) {
856 return lp >= R.getAddress() &&
857 lp < R.getAddress() + R.getSize();
858 });
859 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000860 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000861 continue;
862 }
863
864 uint64_t SectAddress = Sect->getAddress();
865 uint64_t SectSize = Sect->getSize();
866
867 StringRef SectName;
868 Sect->getName(SectName);
869 DataRefImpl Ref = Sect->getRawDataRefImpl();
870 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
871 outs() << SegmentName << ":" << SectName << ":";
872
873 uint32_t section_type;
874 if (O->is64Bit()) {
875 const MachO::section_64 Sec = O->getSection64(Ref);
876 section_type = Sec.flags & MachO::SECTION_TYPE;
877 } else {
878 const MachO::section Sec = O->getSection(Ref);
879 section_type = Sec.flags & MachO::SECTION_TYPE;
880 }
881
882 StringRef BytesStr;
883 Sect->getContents(BytesStr);
884 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
885
886 switch (section_type) {
887 case MachO::S_CSTRING_LITERALS:
888 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
889 i++) {
890 DumpCstringChar(Contents[i]);
891 }
892 outs() << "\n";
893 break;
894 case MachO::S_4BYTE_LITERALS:
895 float f;
896 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
897 uint32_t l;
898 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
899 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
900 sys::swapByteOrder(f);
901 sys::swapByteOrder(l);
902 }
903 DumpLiteral4(l, f);
904 break;
905 case MachO::S_8BYTE_LITERALS: {
906 double d;
907 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
908 uint32_t l0, l1;
909 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
910 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
911 sizeof(uint32_t));
912 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
913 sys::swapByteOrder(f);
914 sys::swapByteOrder(l0);
915 sys::swapByteOrder(l1);
916 }
917 DumpLiteral8(O, l0, l1, d);
918 break;
919 }
920 case MachO::S_16BYTE_LITERALS: {
921 uint32_t l0, l1, l2, l3;
922 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
923 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
924 sizeof(uint32_t));
925 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
926 sizeof(uint32_t));
927 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
928 sizeof(uint32_t));
929 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
930 sys::swapByteOrder(l0);
931 sys::swapByteOrder(l1);
932 sys::swapByteOrder(l2);
933 sys::swapByteOrder(l3);
934 }
935 DumpLiteral16(l0, l1, l2, l3);
936 break;
937 }
938 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000939 }
940}
941
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000942static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
943 uint32_t sect_size, uint64_t sect_addr,
944 SymbolAddressMap *AddrMap,
945 bool verbose) {
946 uint32_t stride;
947 if (O->is64Bit())
948 stride = sizeof(uint64_t);
949 else
950 stride = sizeof(uint32_t);
951 for (uint32_t i = 0; i < sect_size; i += stride) {
952 const char *SymbolName = nullptr;
953 if (O->is64Bit()) {
954 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
955 uint64_t pointer_value;
956 memcpy(&pointer_value, sect + i, stride);
957 if (O->isLittleEndian() != sys::IsLittleEndianHost)
958 sys::swapByteOrder(pointer_value);
959 outs() << format("0x%016" PRIx64, pointer_value);
960 if (verbose)
961 SymbolName = GuessSymbolName(pointer_value, AddrMap);
962 } else {
963 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
964 uint32_t pointer_value;
965 memcpy(&pointer_value, sect + i, stride);
966 if (O->isLittleEndian() != sys::IsLittleEndianHost)
967 sys::swapByteOrder(pointer_value);
968 outs() << format("0x%08" PRIx32, pointer_value);
969 if (verbose)
970 SymbolName = GuessSymbolName(pointer_value, AddrMap);
971 }
972 if (SymbolName)
973 outs() << " " << SymbolName;
974 outs() << "\n";
975 }
976}
977
978static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
979 uint32_t size, uint64_t addr) {
980 uint32_t cputype = O->getHeader().cputype;
981 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
982 uint32_t j;
983 for (uint32_t i = 0; i < size; i += j, addr += j) {
984 if (O->is64Bit())
985 outs() << format("%016" PRIx64, addr) << "\t";
986 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000987 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000988 for (j = 0; j < 16 && i + j < size; j++) {
989 uint8_t byte_word = *(sect + i + j);
990 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
991 }
992 outs() << "\n";
993 }
994 } else {
995 uint32_t j;
996 for (uint32_t i = 0; i < size; i += j, addr += j) {
997 if (O->is64Bit())
998 outs() << format("%016" PRIx64, addr) << "\t";
999 else
1000 outs() << format("%08" PRIx64, sect) << "\t";
1001 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1002 j += sizeof(int32_t)) {
1003 if (i + j + sizeof(int32_t) < size) {
1004 uint32_t long_word;
1005 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1006 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1007 sys::swapByteOrder(long_word);
1008 outs() << format("%08" PRIx32, long_word) << " ";
1009 } else {
1010 for (uint32_t k = 0; i + j + k < size; k++) {
1011 uint8_t byte_word = *(sect + i + j);
1012 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1013 }
1014 }
1015 }
1016 outs() << "\n";
1017 }
1018 }
1019}
1020
Kevin Enderby95df54c2015-02-04 01:01:38 +00001021static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1022 StringRef DisSegName, StringRef DisSectName);
1023
1024static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1025 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001026 SymbolAddressMap AddrMap;
1027 if (verbose)
1028 CreateSymbolAddressMap(O, &AddrMap);
1029
1030 for (unsigned i = 0; i < DumpSections.size(); ++i) {
1031 StringRef DumpSection = DumpSections[i];
1032 std::pair<StringRef, StringRef> DumpSegSectName;
1033 DumpSegSectName = DumpSection.split(',');
1034 StringRef DumpSegName, DumpSectName;
1035 if (DumpSegSectName.second.size()) {
1036 DumpSegName = DumpSegSectName.first;
1037 DumpSectName = DumpSegSectName.second;
1038 } else {
1039 DumpSegName = "";
1040 DumpSectName = DumpSegSectName.first;
1041 }
1042 for (const SectionRef &Section : O->sections()) {
1043 StringRef SectName;
1044 Section.getName(SectName);
1045 DataRefImpl Ref = Section.getRawDataRefImpl();
1046 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1047 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1048 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001049
Kevin Enderby95df54c2015-02-04 01:01:38 +00001050 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001051 if (O->is64Bit()) {
1052 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001053 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001054
1055 } else {
1056 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001057 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001058 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001059 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001060
1061 StringRef BytesStr;
1062 Section.getContents(BytesStr);
1063 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1064 uint32_t sect_size = BytesStr.size();
1065 uint64_t sect_addr = Section.getAddress();
1066
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001067 if (Raw) {
1068 outs().write(BytesStr.data(), BytesStr.size());
1069 continue;
1070 }
1071
1072 outs() << "Contents of (" << SegName << "," << SectName
1073 << ") section\n";
1074
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001075 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001076 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1077 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1078 DisassembleMachO(Filename, O, SegName, SectName);
1079 continue;
1080 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001081 if (SegName == "__TEXT" && SectName == "__info_plist") {
1082 outs() << sect;
1083 continue;
1084 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001085 switch (section_type) {
1086 case MachO::S_REGULAR:
1087 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1088 break;
1089 case MachO::S_ZEROFILL:
1090 outs() << "zerofill section and has no contents in the file\n";
1091 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001092 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001093 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001094 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001095 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001096 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001097 break;
1098 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001099 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 break;
1101 case MachO::S_16BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001102 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1103 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001104 case MachO::S_LITERAL_POINTERS:
1105 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001106 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001107 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001108 case MachO::S_MOD_INIT_FUNC_POINTERS:
1109 case MachO::S_MOD_TERM_FUNC_POINTERS:
1110 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1111 verbose);
1112 break;
1113 default:
1114 outs() << "Unknown section type ("
1115 << format("0x%08" PRIx32, section_type) << ")\n";
1116 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1117 break;
1118 }
1119 } else {
1120 if (section_type == MachO::S_ZEROFILL)
1121 outs() << "zerofill section and has no contents in the file\n";
1122 else
1123 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1124 }
1125 }
1126 }
1127 }
1128}
1129
Kevin Enderbycd66be52015-03-11 22:06:32 +00001130static void DumpInfoPlistSectionContents(StringRef Filename,
1131 MachOObjectFile *O) {
1132 for (const SectionRef &Section : O->sections()) {
1133 StringRef SectName;
1134 Section.getName(SectName);
1135 DataRefImpl Ref = Section.getRawDataRefImpl();
1136 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1137 if (SegName == "__TEXT" && SectName == "__info_plist") {
1138 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1139 StringRef BytesStr;
1140 Section.getContents(BytesStr);
1141 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1142 outs() << sect;
1143 return;
1144 }
1145 }
1146}
1147
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001148// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1149// and if it is and there is a list of architecture flags is specified then
1150// check to make sure this Mach-O file is one of those architectures or all
1151// architectures were specified. If not then an error is generated and this
1152// routine returns false. Else it returns true.
1153static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1154 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1155 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1156 bool ArchFound = false;
1157 MachO::mach_header H;
1158 MachO::mach_header_64 H_64;
1159 Triple T;
1160 if (MachO->is64Bit()) {
1161 H_64 = MachO->MachOObjectFile::getHeader64();
1162 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1163 } else {
1164 H = MachO->MachOObjectFile::getHeader();
1165 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1166 }
1167 unsigned i;
1168 for (i = 0; i < ArchFlags.size(); ++i) {
1169 if (ArchFlags[i] == T.getArchName())
1170 ArchFound = true;
1171 break;
1172 }
1173 if (!ArchFound) {
1174 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1175 << "architecture: " + ArchFlags[i] + "\n";
1176 return false;
1177 }
1178 }
1179 return true;
1180}
1181
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001182// ProcessMachO() is passed a single opened Mach-O file, which may be an
1183// archive member and or in a slice of a universal file. It prints the
1184// the file name and header info and then processes it according to the
1185// command line options.
1186static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1187 StringRef ArchiveMemberName = StringRef(),
1188 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001189 // If we are doing some processing here on the Mach-O file print the header
1190 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001191 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001192 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001193 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001194 DylibsUsed || DylibId || (DumpSections.size() != 0 && !Raw)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001195 outs() << Filename;
1196 if (!ArchiveMemberName.empty())
1197 outs() << '(' << ArchiveMemberName << ')';
1198 if (!ArchitectureName.empty())
1199 outs() << " (architecture " << ArchitectureName << ")";
1200 outs() << ":\n";
1201 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001202
1203 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001204 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001205 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001206 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001207 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001208 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001209 if (LinkOptHints)
1210 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001211 if (Relocations)
1212 PrintRelocations(MachOOF);
1213 if (SectionHeaders)
1214 PrintSectionHeaders(MachOOF);
1215 if (SectionContents)
1216 PrintSectionContents(MachOOF);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001217 if (DumpSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001218 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001219 if (InfoPlist)
1220 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001221 if (DylibsUsed)
1222 PrintDylibs(MachOOF, false);
1223 if (DylibId)
1224 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001225 if (SymbolTable)
1226 PrintSymbolTable(MachOOF);
1227 if (UnwindInfo)
1228 printMachOUnwindInfo(MachOOF);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001229 if (PrivateHeaders)
1230 printMachOFileHeader(MachOOF);
1231 if (ExportsTrie)
1232 printExportsTrie(MachOOF);
1233 if (Rebase)
1234 printRebaseTable(MachOOF);
1235 if (Bind)
1236 printBindTable(MachOOF);
1237 if (LazyBind)
1238 printLazyBindTable(MachOOF);
1239 if (WeakBind)
1240 printWeakBindTable(MachOOF);
1241}
1242
Kevin Enderby131d1772015-01-09 19:22:37 +00001243// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1244static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1245 outs() << " cputype (" << cputype << ")\n";
1246 outs() << " cpusubtype (" << cpusubtype << ")\n";
1247}
1248
1249// printCPUType() helps print_fat_headers by printing the cputype and
1250// pusubtype (symbolically for the one's it knows about).
1251static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1252 switch (cputype) {
1253 case MachO::CPU_TYPE_I386:
1254 switch (cpusubtype) {
1255 case MachO::CPU_SUBTYPE_I386_ALL:
1256 outs() << " cputype CPU_TYPE_I386\n";
1257 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1258 break;
1259 default:
1260 printUnknownCPUType(cputype, cpusubtype);
1261 break;
1262 }
1263 break;
1264 case MachO::CPU_TYPE_X86_64:
1265 switch (cpusubtype) {
1266 case MachO::CPU_SUBTYPE_X86_64_ALL:
1267 outs() << " cputype CPU_TYPE_X86_64\n";
1268 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1269 break;
1270 case MachO::CPU_SUBTYPE_X86_64_H:
1271 outs() << " cputype CPU_TYPE_X86_64\n";
1272 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1273 break;
1274 default:
1275 printUnknownCPUType(cputype, cpusubtype);
1276 break;
1277 }
1278 break;
1279 case MachO::CPU_TYPE_ARM:
1280 switch (cpusubtype) {
1281 case MachO::CPU_SUBTYPE_ARM_ALL:
1282 outs() << " cputype CPU_TYPE_ARM\n";
1283 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1284 break;
1285 case MachO::CPU_SUBTYPE_ARM_V4T:
1286 outs() << " cputype CPU_TYPE_ARM\n";
1287 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1288 break;
1289 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1290 outs() << " cputype CPU_TYPE_ARM\n";
1291 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1292 break;
1293 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1294 outs() << " cputype CPU_TYPE_ARM\n";
1295 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1296 break;
1297 case MachO::CPU_SUBTYPE_ARM_V6:
1298 outs() << " cputype CPU_TYPE_ARM\n";
1299 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1300 break;
1301 case MachO::CPU_SUBTYPE_ARM_V6M:
1302 outs() << " cputype CPU_TYPE_ARM\n";
1303 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1304 break;
1305 case MachO::CPU_SUBTYPE_ARM_V7:
1306 outs() << " cputype CPU_TYPE_ARM\n";
1307 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1308 break;
1309 case MachO::CPU_SUBTYPE_ARM_V7EM:
1310 outs() << " cputype CPU_TYPE_ARM\n";
1311 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1312 break;
1313 case MachO::CPU_SUBTYPE_ARM_V7K:
1314 outs() << " cputype CPU_TYPE_ARM\n";
1315 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1316 break;
1317 case MachO::CPU_SUBTYPE_ARM_V7M:
1318 outs() << " cputype CPU_TYPE_ARM\n";
1319 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1320 break;
1321 case MachO::CPU_SUBTYPE_ARM_V7S:
1322 outs() << " cputype CPU_TYPE_ARM\n";
1323 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1324 break;
1325 default:
1326 printUnknownCPUType(cputype, cpusubtype);
1327 break;
1328 }
1329 break;
1330 case MachO::CPU_TYPE_ARM64:
1331 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1332 case MachO::CPU_SUBTYPE_ARM64_ALL:
1333 outs() << " cputype CPU_TYPE_ARM64\n";
1334 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1335 break;
1336 default:
1337 printUnknownCPUType(cputype, cpusubtype);
1338 break;
1339 }
1340 break;
1341 default:
1342 printUnknownCPUType(cputype, cpusubtype);
1343 break;
1344 }
1345}
1346
1347static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1348 bool verbose) {
1349 outs() << "Fat headers\n";
1350 if (verbose)
1351 outs() << "fat_magic FAT_MAGIC\n";
1352 else
1353 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1354
1355 uint32_t nfat_arch = UB->getNumberOfObjects();
1356 StringRef Buf = UB->getData();
1357 uint64_t size = Buf.size();
1358 uint64_t big_size = sizeof(struct MachO::fat_header) +
1359 nfat_arch * sizeof(struct MachO::fat_arch);
1360 outs() << "nfat_arch " << UB->getNumberOfObjects();
1361 if (nfat_arch == 0)
1362 outs() << " (malformed, contains zero architecture types)\n";
1363 else if (big_size > size)
1364 outs() << " (malformed, architectures past end of file)\n";
1365 else
1366 outs() << "\n";
1367
1368 for (uint32_t i = 0; i < nfat_arch; ++i) {
1369 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1370 uint32_t cputype = OFA.getCPUType();
1371 uint32_t cpusubtype = OFA.getCPUSubType();
1372 outs() << "architecture ";
1373 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1374 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1375 uint32_t other_cputype = other_OFA.getCPUType();
1376 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001377 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001378 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001379 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001380 outs() << "(illegal duplicate architecture) ";
1381 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001382 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001383 }
1384 if (verbose) {
1385 outs() << OFA.getArchTypeName() << "\n";
1386 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1387 } else {
1388 outs() << i << "\n";
1389 outs() << " cputype " << cputype << "\n";
1390 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1391 << "\n";
1392 }
1393 if (verbose &&
1394 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1395 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1396 else
1397 outs() << " capabilities "
1398 << format("0x%" PRIx32,
1399 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1400 outs() << " offset " << OFA.getOffset();
1401 if (OFA.getOffset() > size)
1402 outs() << " (past end of file)";
1403 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1404 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1405 outs() << "\n";
1406 outs() << " size " << OFA.getSize();
1407 big_size = OFA.getOffset() + OFA.getSize();
1408 if (big_size > size)
1409 outs() << " (past end of file)";
1410 outs() << "\n";
1411 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1412 << ")\n";
1413 }
1414}
1415
Kevin Enderby13023a12015-01-15 23:19:11 +00001416static void printArchiveChild(Archive::Child &C, bool verbose,
1417 bool print_offset) {
1418 if (print_offset)
1419 outs() << C.getChildOffset() << "\t";
1420 sys::fs::perms Mode = C.getAccessMode();
1421 if (verbose) {
1422 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1423 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1424 outs() << "-";
1425 if (Mode & sys::fs::owner_read)
1426 outs() << "r";
1427 else
1428 outs() << "-";
1429 if (Mode & sys::fs::owner_write)
1430 outs() << "w";
1431 else
1432 outs() << "-";
1433 if (Mode & sys::fs::owner_exe)
1434 outs() << "x";
1435 else
1436 outs() << "-";
1437 if (Mode & sys::fs::group_read)
1438 outs() << "r";
1439 else
1440 outs() << "-";
1441 if (Mode & sys::fs::group_write)
1442 outs() << "w";
1443 else
1444 outs() << "-";
1445 if (Mode & sys::fs::group_exe)
1446 outs() << "x";
1447 else
1448 outs() << "-";
1449 if (Mode & sys::fs::others_read)
1450 outs() << "r";
1451 else
1452 outs() << "-";
1453 if (Mode & sys::fs::others_write)
1454 outs() << "w";
1455 else
1456 outs() << "-";
1457 if (Mode & sys::fs::others_exe)
1458 outs() << "x";
1459 else
1460 outs() << "-";
1461 } else {
1462 outs() << format("0%o ", Mode);
1463 }
1464
1465 unsigned UID = C.getUID();
1466 outs() << format("%3d/", UID);
1467 unsigned GID = C.getGID();
1468 outs() << format("%-3d ", GID);
Kevin Enderbyc12718932015-01-16 22:10:36 +00001469 uint64_t Size = C.getRawSize();
Kevin Enderby479ee612015-01-23 21:02:44 +00001470 outs() << format("%5" PRId64, Size) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001471
1472 StringRef RawLastModified = C.getRawLastModified();
1473 if (verbose) {
1474 unsigned Seconds;
1475 if (RawLastModified.getAsInteger(10, Seconds))
1476 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1477 else {
1478 // Since cime(3) returns a 26 character string of the form:
1479 // "Sun Sep 16 01:03:52 1973\n\0"
1480 // just print 24 characters.
1481 time_t t = Seconds;
1482 outs() << format("%.24s ", ctime(&t));
1483 }
1484 } else {
1485 outs() << RawLastModified << " ";
1486 }
1487
1488 if (verbose) {
1489 ErrorOr<StringRef> NameOrErr = C.getName();
1490 if (NameOrErr.getError()) {
1491 StringRef RawName = C.getRawName();
1492 outs() << RawName << "\n";
1493 } else {
1494 StringRef Name = NameOrErr.get();
1495 outs() << Name << "\n";
1496 }
1497 } else {
1498 StringRef RawName = C.getRawName();
1499 outs() << RawName << "\n";
1500 }
1501}
1502
1503static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1504 if (A->hasSymbolTable()) {
1505 Archive::child_iterator S = A->getSymbolTableChild();
1506 Archive::Child C = *S;
1507 printArchiveChild(C, verbose, print_offset);
1508 }
1509 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1510 ++I) {
1511 Archive::Child C = *I;
1512 printArchiveChild(C, verbose, print_offset);
1513 }
1514}
1515
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001516// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1517// -arch flags selecting just those slices as specified by them and also parses
1518// archive files. Then for each individual Mach-O file ProcessMachO() is
1519// called to process the file based on the command line options.
1520void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001521 // Check for -arch all and verifiy the -arch flags are valid.
1522 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1523 if (ArchFlags[i] == "all") {
1524 ArchAll = true;
1525 } else {
1526 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1527 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1528 "'for the -arch option\n";
1529 return;
1530 }
1531 }
1532 }
1533
1534 // Attempt to open the binary.
1535 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1536 if (std::error_code EC = BinaryOrErr.getError()) {
1537 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +00001538 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001539 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001540 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001541
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001542 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1543 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001544 if (ArchiveHeaders)
1545 printArchiveHeaders(A, true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001546 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1547 I != E; ++I) {
1548 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1549 if (ChildOrErr.getError())
1550 continue;
1551 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1552 if (!checkMachOAndArchFlags(O, Filename))
1553 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001554 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001555 }
1556 }
1557 return;
1558 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001559 if (UniversalHeaders) {
1560 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001561 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001562 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001563 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1564 // If we have a list of architecture flags specified dump only those.
1565 if (!ArchAll && ArchFlags.size() != 0) {
1566 // Look for a slice in the universal binary that matches each ArchFlag.
1567 bool ArchFound;
1568 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1569 ArchFound = false;
1570 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1571 E = UB->end_objects();
1572 I != E; ++I) {
1573 if (ArchFlags[i] == I->getArchTypeName()) {
1574 ArchFound = true;
1575 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1576 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001577 std::string ArchitectureName = "";
1578 if (ArchFlags.size() > 1)
1579 ArchitectureName = I->getArchTypeName();
1580 if (ObjOrErr) {
1581 ObjectFile &O = *ObjOrErr.get();
1582 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001583 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001584 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1585 I->getAsArchive()) {
1586 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001587 outs() << "Archive : " << Filename;
1588 if (!ArchitectureName.empty())
1589 outs() << " (architecture " << ArchitectureName << ")";
1590 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001591 if (ArchiveHeaders)
1592 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001593 for (Archive::child_iterator AI = A->child_begin(),
1594 AE = A->child_end();
1595 AI != AE; ++AI) {
1596 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1597 if (ChildOrErr.getError())
1598 continue;
1599 if (MachOObjectFile *O =
1600 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001601 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001602 }
1603 }
1604 }
1605 }
1606 if (!ArchFound) {
1607 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1608 << "architecture: " + ArchFlags[i] + "\n";
1609 return;
1610 }
1611 }
1612 return;
1613 }
1614 // No architecture flags were specified so if this contains a slice that
1615 // matches the host architecture dump only that.
1616 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001617 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1618 E = UB->end_objects();
1619 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001620 if (MachOObjectFile::getHostArch().getArchName() ==
1621 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001622 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001623 std::string ArchiveName;
1624 ArchiveName.clear();
1625 if (ObjOrErr) {
1626 ObjectFile &O = *ObjOrErr.get();
1627 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001628 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001629 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1630 I->getAsArchive()) {
1631 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001632 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001633 if (ArchiveHeaders)
1634 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001635 for (Archive::child_iterator AI = A->child_begin(),
1636 AE = A->child_end();
1637 AI != AE; ++AI) {
1638 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1639 if (ChildOrErr.getError())
1640 continue;
1641 if (MachOObjectFile *O =
1642 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001643 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001644 }
1645 }
1646 return;
1647 }
1648 }
1649 }
1650 // Either all architectures have been specified or none have been specified
1651 // and this does not contain the host architecture so dump all the slices.
1652 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1653 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1654 E = UB->end_objects();
1655 I != E; ++I) {
1656 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001657 std::string ArchitectureName = "";
1658 if (moreThanOneArch)
1659 ArchitectureName = I->getArchTypeName();
1660 if (ObjOrErr) {
1661 ObjectFile &Obj = *ObjOrErr.get();
1662 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001663 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001664 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1665 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001666 outs() << "Archive : " << Filename;
1667 if (!ArchitectureName.empty())
1668 outs() << " (architecture " << ArchitectureName << ")";
1669 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001670 if (ArchiveHeaders)
1671 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001672 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1673 AI != AE; ++AI) {
1674 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1675 if (ChildOrErr.getError())
1676 continue;
1677 if (MachOObjectFile *O =
1678 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1679 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001680 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1681 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001682 }
1683 }
1684 }
1685 }
1686 return;
1687 }
1688 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1689 if (!checkMachOAndArchFlags(O, Filename))
1690 return;
1691 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001692 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001693 } else
1694 errs() << "llvm-objdump: '" << Filename << "': "
1695 << "Object is not a Mach-O file type.\n";
1696 } else
1697 errs() << "llvm-objdump: '" << Filename << "': "
1698 << "Unrecognized file type.\n";
Rafael Espindola9b709252013-04-13 01:45:40 +00001699}
1700
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001701typedef std::pair<uint64_t, const char *> BindInfoEntry;
1702typedef std::vector<BindInfoEntry> BindTable;
1703typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001704
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001705// The block of info used by the Symbolizer call backs.
1706struct DisassembleInfo {
1707 bool verbose;
1708 MachOObjectFile *O;
1709 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001710 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001711 std::vector<SectionRef> *Sections;
1712 const char *class_name;
1713 const char *selector_name;
1714 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001715 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001716 uint64_t adrp_addr;
1717 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001718 BindTable *bindtable;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001719};
1720
1721// SymbolizerGetOpInfo() is the operand information call back function.
1722// This is called to get the symbolic information for operand(s) of an
1723// instruction when it is being done. This routine does this from
1724// the relocation information, symbol table, etc. That block of information
1725// is a pointer to the struct DisassembleInfo that was passed when the
1726// disassembler context was created and passed to back to here when
1727// called back by the disassembler for instruction operands that could have
1728// relocation information. The address of the instruction containing operand is
1729// at the Pc parameter. The immediate value the operand has is passed in
1730// op_info->Value and is at Offset past the start of the instruction and has a
1731// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1732// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1733// names and addends of the symbolic expression to add for the operand. The
1734// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1735// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001736static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1737 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001738 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1739 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001740 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001741
1742 // Make sure all fields returned are zero if we don't set them.
1743 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1744 op_info->Value = value;
1745
1746 // If the TagType is not the value 1 which it code knows about or if no
1747 // verbose symbolic information is wanted then just return 0, indicating no
1748 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001749 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001750 return 0;
1751
1752 unsigned int Arch = info->O->getArch();
1753 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001754 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1755 return 0;
1756 // First search the section's relocation entries (if any) for an entry
1757 // for this section offset.
1758 uint32_t sect_addr = info->S.getAddress();
1759 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1760 bool reloc_found = false;
1761 DataRefImpl Rel;
1762 MachO::any_relocation_info RE;
1763 bool isExtern = false;
1764 SymbolRef Symbol;
1765 bool r_scattered = false;
1766 uint32_t r_value, pair_r_value, r_type;
1767 for (const RelocationRef &Reloc : info->S.relocations()) {
1768 uint64_t RelocOffset;
1769 Reloc.getOffset(RelocOffset);
1770 if (RelocOffset == sect_offset) {
1771 Rel = Reloc.getRawDataRefImpl();
1772 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001773 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001774 r_scattered = info->O->isRelocationScattered(RE);
1775 if (r_scattered) {
1776 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001777 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1778 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1779 DataRefImpl RelNext = Rel;
1780 info->O->moveRelocationNext(RelNext);
1781 MachO::any_relocation_info RENext;
1782 RENext = info->O->getRelocation(RelNext);
1783 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001784 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001785 else
1786 return 0;
1787 }
1788 } else {
1789 isExtern = info->O->getPlainRelocationExternal(RE);
1790 if (isExtern) {
1791 symbol_iterator RelocSym = Reloc.getSymbol();
1792 Symbol = *RelocSym;
1793 }
1794 }
1795 reloc_found = true;
1796 break;
1797 }
1798 }
1799 if (reloc_found && isExtern) {
1800 StringRef SymName;
1801 Symbol.getName(SymName);
1802 const char *name = SymName.data();
1803 op_info->AddSymbol.Present = 1;
1804 op_info->AddSymbol.Name = name;
1805 // For i386 extern relocation entries the value in the instruction is
1806 // the offset from the symbol, and value is already set in op_info->Value.
1807 return 1;
1808 }
1809 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1810 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001811 const char *add = GuessSymbolName(r_value, info->AddrMap);
1812 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001813 uint32_t offset = value - (r_value - pair_r_value);
1814 op_info->AddSymbol.Present = 1;
1815 if (add != nullptr)
1816 op_info->AddSymbol.Name = add;
1817 else
1818 op_info->AddSymbol.Value = r_value;
1819 op_info->SubtractSymbol.Present = 1;
1820 if (sub != nullptr)
1821 op_info->SubtractSymbol.Name = sub;
1822 else
1823 op_info->SubtractSymbol.Value = pair_r_value;
1824 op_info->Value = offset;
1825 return 1;
1826 }
1827 // TODO:
1828 // Second search the external relocation entries of a fully linked image
1829 // (if any) for an entry that matches this segment offset.
1830 // uint32_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001831 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001832 }
1833 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001834 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1835 return 0;
1836 // First search the section's relocation entries (if any) for an entry
1837 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001838 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001839 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1840 bool reloc_found = false;
1841 DataRefImpl Rel;
1842 MachO::any_relocation_info RE;
1843 bool isExtern = false;
1844 SymbolRef Symbol;
1845 for (const RelocationRef &Reloc : info->S.relocations()) {
1846 uint64_t RelocOffset;
1847 Reloc.getOffset(RelocOffset);
1848 if (RelocOffset == sect_offset) {
1849 Rel = Reloc.getRawDataRefImpl();
1850 RE = info->O->getRelocation(Rel);
1851 // NOTE: Scattered relocations don't exist on x86_64.
1852 isExtern = info->O->getPlainRelocationExternal(RE);
1853 if (isExtern) {
1854 symbol_iterator RelocSym = Reloc.getSymbol();
1855 Symbol = *RelocSym;
1856 }
1857 reloc_found = true;
1858 break;
1859 }
1860 }
1861 if (reloc_found && isExtern) {
1862 // The Value passed in will be adjusted by the Pc if the instruction
1863 // adds the Pc. But for x86_64 external relocation entries the Value
1864 // is the offset from the external symbol.
1865 if (info->O->getAnyRelocationPCRel(RE))
1866 op_info->Value -= Pc + Offset + Size;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001867 StringRef SymName;
1868 Symbol.getName(SymName);
1869 const char *name = SymName.data();
1870 unsigned Type = info->O->getAnyRelocationType(RE);
1871 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1872 DataRefImpl RelNext = Rel;
1873 info->O->moveRelocationNext(RelNext);
1874 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1875 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1876 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1877 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1878 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1879 op_info->SubtractSymbol.Present = 1;
1880 op_info->SubtractSymbol.Name = name;
1881 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1882 Symbol = *RelocSymNext;
1883 StringRef SymNameNext;
1884 Symbol.getName(SymNameNext);
1885 name = SymNameNext.data();
1886 }
1887 }
1888 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1889 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1890 op_info->AddSymbol.Present = 1;
1891 op_info->AddSymbol.Name = name;
1892 return 1;
1893 }
1894 // TODO:
1895 // Second search the external relocation entries of a fully linked image
1896 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001897 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001898 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001899 }
1900 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001901 if (Offset != 0 || (Size != 4 && Size != 2))
1902 return 0;
1903 // First search the section's relocation entries (if any) for an entry
1904 // for this section offset.
1905 uint32_t sect_addr = info->S.getAddress();
1906 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001907 DataRefImpl Rel;
1908 MachO::any_relocation_info RE;
1909 bool isExtern = false;
1910 SymbolRef Symbol;
1911 bool r_scattered = false;
1912 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001913 auto Reloc =
1914 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1915 [&](const RelocationRef &Reloc) {
1916 uint64_t RelocOffset;
1917 Reloc.getOffset(RelocOffset);
1918 return RelocOffset == sect_offset;
1919 });
1920
1921 if (Reloc == info->S.relocations().end())
1922 return 0;
1923
1924 Rel = Reloc->getRawDataRefImpl();
1925 RE = info->O->getRelocation(Rel);
1926 r_length = info->O->getAnyRelocationLength(RE);
1927 r_scattered = info->O->isRelocationScattered(RE);
1928 if (r_scattered) {
1929 r_value = info->O->getScatteredRelocationValue(RE);
1930 r_type = info->O->getScatteredRelocationType(RE);
1931 } else {
1932 r_type = info->O->getAnyRelocationType(RE);
1933 isExtern = info->O->getPlainRelocationExternal(RE);
1934 if (isExtern) {
1935 symbol_iterator RelocSym = Reloc->getSymbol();
1936 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001937 }
1938 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001939 if (r_type == MachO::ARM_RELOC_HALF ||
1940 r_type == MachO::ARM_RELOC_SECTDIFF ||
1941 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1942 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1943 DataRefImpl RelNext = Rel;
1944 info->O->moveRelocationNext(RelNext);
1945 MachO::any_relocation_info RENext;
1946 RENext = info->O->getRelocation(RelNext);
1947 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1948 if (info->O->isRelocationScattered(RENext))
1949 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1950 }
1951
1952 if (isExtern) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001953 StringRef SymName;
1954 Symbol.getName(SymName);
1955 const char *name = SymName.data();
1956 op_info->AddSymbol.Present = 1;
1957 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001958 switch (r_type) {
1959 case MachO::ARM_RELOC_HALF:
1960 if ((r_length & 0x1) == 1) {
1961 op_info->Value = value << 16 | other_half;
1962 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1963 } else {
1964 op_info->Value = other_half << 16 | value;
1965 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001966 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001967 break;
1968 default:
1969 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001970 }
1971 return 1;
1972 }
1973 // If we have a branch that is not an external relocation entry then
1974 // return 0 so the code in tryAddingSymbolicOperand() can use the
1975 // SymbolLookUp call back with the branch target address to look up the
1976 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00001977 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1978 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001979 return 0;
1980
1981 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001982 if (r_type == MachO::ARM_RELOC_HALF ||
1983 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1984 if ((r_length & 0x1) == 1)
1985 value = value << 16 | other_half;
1986 else
1987 value = other_half << 16 | value;
1988 }
1989 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1990 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1991 offset = value - r_value;
1992 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001993 }
1994
David Blaikie33dd45d02015-03-23 18:39:02 +00001995 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001996 if ((r_length & 0x1) == 1)
1997 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1998 else
1999 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002000 const char *add = GuessSymbolName(r_value, info->AddrMap);
2001 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002002 int32_t offset = value - (r_value - pair_r_value);
2003 op_info->AddSymbol.Present = 1;
2004 if (add != nullptr)
2005 op_info->AddSymbol.Name = add;
2006 else
2007 op_info->AddSymbol.Value = r_value;
2008 op_info->SubtractSymbol.Present = 1;
2009 if (sub != nullptr)
2010 op_info->SubtractSymbol.Name = sub;
2011 else
2012 op_info->SubtractSymbol.Value = pair_r_value;
2013 op_info->Value = offset;
2014 return 1;
2015 }
2016
Kevin Enderby930fdc72014-11-06 19:00:13 +00002017 op_info->AddSymbol.Present = 1;
2018 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002019 if (r_type == MachO::ARM_RELOC_HALF) {
2020 if ((r_length & 0x1) == 1)
2021 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2022 else
2023 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002024 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002025 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002026 if (add != nullptr) {
2027 op_info->AddSymbol.Name = add;
2028 return 1;
2029 }
2030 op_info->AddSymbol.Value = value;
2031 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002032 }
2033 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002034 if (Offset != 0 || Size != 4)
2035 return 0;
2036 // First search the section's relocation entries (if any) for an entry
2037 // for this section offset.
2038 uint64_t sect_addr = info->S.getAddress();
2039 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002040 auto Reloc =
2041 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2042 [&](const RelocationRef &Reloc) {
2043 uint64_t RelocOffset;
2044 Reloc.getOffset(RelocOffset);
2045 return RelocOffset == sect_offset;
2046 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002047
David Blaikie33dd45d02015-03-23 18:39:02 +00002048 if (Reloc == info->S.relocations().end())
2049 return 0;
2050
2051 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2052 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2053 uint32_t r_type = info->O->getAnyRelocationType(RE);
2054 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2055 DataRefImpl RelNext = Rel;
2056 info->O->moveRelocationNext(RelNext);
2057 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2058 if (value == 0) {
2059 value = info->O->getPlainRelocationSymbolNum(RENext);
2060 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002061 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002062 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002063 // NOTE: Scattered relocations don't exist on arm64.
2064 if (!info->O->getPlainRelocationExternal(RE))
2065 return 0;
2066 StringRef SymName;
2067 Reloc->getSymbol()->getName(SymName);
2068 const char *name = SymName.data();
2069 op_info->AddSymbol.Present = 1;
2070 op_info->AddSymbol.Name = name;
2071
2072 switch (r_type) {
2073 case MachO::ARM64_RELOC_PAGE21:
2074 /* @page */
2075 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2076 break;
2077 case MachO::ARM64_RELOC_PAGEOFF12:
2078 /* @pageoff */
2079 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2080 break;
2081 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2082 /* @gotpage */
2083 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2084 break;
2085 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2086 /* @gotpageoff */
2087 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2088 break;
2089 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2090 /* @tvlppage is not implemented in llvm-mc */
2091 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2092 break;
2093 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2094 /* @tvlppageoff is not implemented in llvm-mc */
2095 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2096 break;
2097 default:
2098 case MachO::ARM64_RELOC_BRANCH26:
2099 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2100 break;
2101 }
2102 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002103 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002104 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002105}
2106
Kevin Enderbybf246f52014-09-24 23:08:22 +00002107// GuessCstringPointer is passed the address of what might be a pointer to a
2108// literal string in a cstring section. If that address is in a cstring section
2109// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002110static const char *GuessCstringPointer(uint64_t ReferenceValue,
2111 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002112 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2113 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2114 for (unsigned I = 0;; ++I) {
2115 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2116 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2117 for (unsigned J = 0; J < Seg.nsects; ++J) {
2118 MachO::section_64 Sec = info->O->getSection64(Load, J);
2119 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2120 if (section_type == MachO::S_CSTRING_LITERALS &&
2121 ReferenceValue >= Sec.addr &&
2122 ReferenceValue < Sec.addr + Sec.size) {
2123 uint64_t sect_offset = ReferenceValue - Sec.addr;
2124 uint64_t object_offset = Sec.offset + sect_offset;
2125 StringRef MachOContents = info->O->getData();
2126 uint64_t object_size = MachOContents.size();
2127 const char *object_addr = (const char *)MachOContents.data();
2128 if (object_offset < object_size) {
2129 const char *name = object_addr + object_offset;
2130 return name;
2131 } else {
2132 return nullptr;
2133 }
2134 }
2135 }
2136 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2137 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2138 for (unsigned J = 0; J < Seg.nsects; ++J) {
2139 MachO::section Sec = info->O->getSection(Load, J);
2140 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2141 if (section_type == MachO::S_CSTRING_LITERALS &&
2142 ReferenceValue >= Sec.addr &&
2143 ReferenceValue < Sec.addr + Sec.size) {
2144 uint64_t sect_offset = ReferenceValue - Sec.addr;
2145 uint64_t object_offset = Sec.offset + sect_offset;
2146 StringRef MachOContents = info->O->getData();
2147 uint64_t object_size = MachOContents.size();
2148 const char *object_addr = (const char *)MachOContents.data();
2149 if (object_offset < object_size) {
2150 const char *name = object_addr + object_offset;
2151 return name;
2152 } else {
2153 return nullptr;
2154 }
2155 }
2156 }
2157 }
2158 if (I == LoadCommandCount - 1)
2159 break;
2160 else
2161 Load = info->O->getNextLoadCommandInfo(Load);
2162 }
2163 return nullptr;
2164}
2165
Kevin Enderby85974882014-09-26 22:20:44 +00002166// GuessIndirectSymbol returns the name of the indirect symbol for the
2167// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2168// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2169// symbol name being referenced by the stub or pointer.
2170static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2171 struct DisassembleInfo *info) {
2172 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2173 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2174 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2175 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2176 for (unsigned I = 0;; ++I) {
2177 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2178 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2179 for (unsigned J = 0; J < Seg.nsects; ++J) {
2180 MachO::section_64 Sec = info->O->getSection64(Load, J);
2181 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2182 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2183 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2184 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2185 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2186 section_type == MachO::S_SYMBOL_STUBS) &&
2187 ReferenceValue >= Sec.addr &&
2188 ReferenceValue < Sec.addr + Sec.size) {
2189 uint32_t stride;
2190 if (section_type == MachO::S_SYMBOL_STUBS)
2191 stride = Sec.reserved2;
2192 else
2193 stride = 8;
2194 if (stride == 0)
2195 return nullptr;
2196 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2197 if (index < Dysymtab.nindirectsyms) {
2198 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002199 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002200 if (indirect_symbol < Symtab.nsyms) {
2201 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2202 SymbolRef Symbol = *Sym;
2203 StringRef SymName;
2204 Symbol.getName(SymName);
2205 const char *name = SymName.data();
2206 return name;
2207 }
2208 }
2209 }
2210 }
2211 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2212 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2213 for (unsigned J = 0; J < Seg.nsects; ++J) {
2214 MachO::section Sec = info->O->getSection(Load, J);
2215 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2216 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2217 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2218 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2219 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2220 section_type == MachO::S_SYMBOL_STUBS) &&
2221 ReferenceValue >= Sec.addr &&
2222 ReferenceValue < Sec.addr + Sec.size) {
2223 uint32_t stride;
2224 if (section_type == MachO::S_SYMBOL_STUBS)
2225 stride = Sec.reserved2;
2226 else
2227 stride = 4;
2228 if (stride == 0)
2229 return nullptr;
2230 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2231 if (index < Dysymtab.nindirectsyms) {
2232 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002233 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002234 if (indirect_symbol < Symtab.nsyms) {
2235 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2236 SymbolRef Symbol = *Sym;
2237 StringRef SymName;
2238 Symbol.getName(SymName);
2239 const char *name = SymName.data();
2240 return name;
2241 }
2242 }
2243 }
2244 }
2245 }
2246 if (I == LoadCommandCount - 1)
2247 break;
2248 else
2249 Load = info->O->getNextLoadCommandInfo(Load);
2250 }
2251 return nullptr;
2252}
2253
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002254// method_reference() is called passing it the ReferenceName that might be
2255// a reference it to an Objective-C method call. If so then it allocates and
2256// assembles a method call string with the values last seen and saved in
2257// the DisassembleInfo's class_name and selector_name fields. This is saved
2258// into the method field of the info and any previous string is free'ed.
2259// Then the class_name field in the info is set to nullptr. The method call
2260// string is set into ReferenceName and ReferenceType is set to
2261// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2262// then both ReferenceType and ReferenceName are left unchanged.
2263static void method_reference(struct DisassembleInfo *info,
2264 uint64_t *ReferenceType,
2265 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002266 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002267 if (*ReferenceName != nullptr) {
2268 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002269 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002270 if (info->method != nullptr)
2271 free(info->method);
2272 if (info->class_name != nullptr) {
2273 info->method = (char *)malloc(5 + strlen(info->class_name) +
2274 strlen(info->selector_name));
2275 if (info->method != nullptr) {
2276 strcpy(info->method, "+[");
2277 strcat(info->method, info->class_name);
2278 strcat(info->method, " ");
2279 strcat(info->method, info->selector_name);
2280 strcat(info->method, "]");
2281 *ReferenceName = info->method;
2282 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2283 }
2284 } else {
2285 info->method = (char *)malloc(9 + strlen(info->selector_name));
2286 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002287 if (Arch == Triple::x86_64)
2288 strcpy(info->method, "-[%rdi ");
2289 else if (Arch == Triple::aarch64)
2290 strcpy(info->method, "-[x0 ");
2291 else
2292 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002293 strcat(info->method, info->selector_name);
2294 strcat(info->method, "]");
2295 *ReferenceName = info->method;
2296 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2297 }
2298 }
2299 info->class_name = nullptr;
2300 }
2301 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002302 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002303 if (info->method != nullptr)
2304 free(info->method);
2305 info->method = (char *)malloc(17 + strlen(info->selector_name));
2306 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002307 if (Arch == Triple::x86_64)
2308 strcpy(info->method, "-[[%rdi super] ");
2309 else if (Arch == Triple::aarch64)
2310 strcpy(info->method, "-[[x0 super] ");
2311 else
2312 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002313 strcat(info->method, info->selector_name);
2314 strcat(info->method, "]");
2315 *ReferenceName = info->method;
2316 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2317 }
2318 info->class_name = nullptr;
2319 }
2320 }
2321 }
2322}
2323
2324// GuessPointerPointer() is passed the address of what might be a pointer to
2325// a reference to an Objective-C class, selector, message ref or cfstring.
2326// If so the value of the pointer is returned and one of the booleans are set
2327// to true. If not zero is returned and all the booleans are set to false.
2328static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2329 struct DisassembleInfo *info,
2330 bool &classref, bool &selref, bool &msgref,
2331 bool &cfstring) {
2332 classref = false;
2333 selref = false;
2334 msgref = false;
2335 cfstring = false;
2336 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2337 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2338 for (unsigned I = 0;; ++I) {
2339 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2340 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2341 for (unsigned J = 0; J < Seg.nsects; ++J) {
2342 MachO::section_64 Sec = info->O->getSection64(Load, J);
2343 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2344 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2345 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2346 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2347 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2348 ReferenceValue >= Sec.addr &&
2349 ReferenceValue < Sec.addr + Sec.size) {
2350 uint64_t sect_offset = ReferenceValue - Sec.addr;
2351 uint64_t object_offset = Sec.offset + sect_offset;
2352 StringRef MachOContents = info->O->getData();
2353 uint64_t object_size = MachOContents.size();
2354 const char *object_addr = (const char *)MachOContents.data();
2355 if (object_offset < object_size) {
2356 uint64_t pointer_value;
2357 memcpy(&pointer_value, object_addr + object_offset,
2358 sizeof(uint64_t));
2359 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2360 sys::swapByteOrder(pointer_value);
2361 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2362 selref = true;
2363 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2364 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2365 classref = true;
2366 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2367 ReferenceValue + 8 < Sec.addr + Sec.size) {
2368 msgref = true;
2369 memcpy(&pointer_value, object_addr + object_offset + 8,
2370 sizeof(uint64_t));
2371 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2372 sys::swapByteOrder(pointer_value);
2373 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2374 cfstring = true;
2375 return pointer_value;
2376 } else {
2377 return 0;
2378 }
2379 }
2380 }
2381 }
2382 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2383 if (I == LoadCommandCount - 1)
2384 break;
2385 else
2386 Load = info->O->getNextLoadCommandInfo(Load);
2387 }
2388 return 0;
2389}
2390
2391// get_pointer_64 returns a pointer to the bytes in the object file at the
2392// Address from a section in the Mach-O file. And indirectly returns the
2393// offset into the section, number of bytes left in the section past the offset
2394// and which section is was being referenced. If the Address is not in a
2395// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002396static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2397 uint32_t &left, SectionRef &S,
2398 DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002399 offset = 0;
2400 left = 0;
2401 S = SectionRef();
2402 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2403 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2404 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2405 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2406 S = (*(info->Sections))[SectIdx];
2407 offset = Address - SectAddress;
2408 left = SectSize - offset;
2409 StringRef SectContents;
2410 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2411 return SectContents.data() + offset;
2412 }
2413 }
2414 return nullptr;
2415}
2416
2417// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2418// the symbol indirectly through n_value. Based on the relocation information
2419// for the specified section offset in the specified section reference.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002420static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2421 DisassembleInfo *info, uint64_t &n_value) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002422 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002423 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002424 return nullptr;
2425
2426 // See if there is an external relocation entry at the sect_offset.
2427 bool reloc_found = false;
2428 DataRefImpl Rel;
2429 MachO::any_relocation_info RE;
2430 bool isExtern = false;
2431 SymbolRef Symbol;
2432 for (const RelocationRef &Reloc : S.relocations()) {
2433 uint64_t RelocOffset;
2434 Reloc.getOffset(RelocOffset);
2435 if (RelocOffset == sect_offset) {
2436 Rel = Reloc.getRawDataRefImpl();
2437 RE = info->O->getRelocation(Rel);
2438 if (info->O->isRelocationScattered(RE))
2439 continue;
2440 isExtern = info->O->getPlainRelocationExternal(RE);
2441 if (isExtern) {
2442 symbol_iterator RelocSym = Reloc.getSymbol();
2443 Symbol = *RelocSym;
2444 }
2445 reloc_found = true;
2446 break;
2447 }
2448 }
2449 // If there is an external relocation entry for a symbol in this section
2450 // at this section_offset then use that symbol's value for the n_value
2451 // and return its name.
2452 const char *SymbolName = nullptr;
2453 if (reloc_found && isExtern) {
2454 Symbol.getAddress(n_value);
2455 StringRef name;
2456 Symbol.getName(name);
2457 if (!name.empty()) {
2458 SymbolName = name.data();
2459 return SymbolName;
2460 }
2461 }
2462
2463 // TODO: For fully linked images, look through the external relocation
2464 // entries off the dynamic symtab command. For these the r_offset is from the
2465 // start of the first writeable segment in the Mach-O file. So the offset
2466 // to this section from that segment is passed to this routine by the caller,
2467 // as the database_offset. Which is the difference of the section's starting
2468 // address and the first writable segment.
2469 //
2470 // NOTE: need add passing the database_offset to this routine.
2471
2472 // TODO: We did not find an external relocation entry so look up the
2473 // ReferenceValue as an address of a symbol and if found return that symbol's
2474 // name.
2475 //
2476 // NOTE: need add passing the ReferenceValue to this routine. Then that code
2477 // would simply be this:
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002478 // SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002479
2480 return SymbolName;
2481}
2482
2483// These are structs in the Objective-C meta data and read to produce the
2484// comments for disassembly. While these are part of the ABI they are no
2485// public defintions. So the are here not in include/llvm/Support/MachO.h .
2486
2487// The cfstring object in a 64-bit Mach-O file.
2488struct cfstring64_t {
2489 uint64_t isa; // class64_t * (64-bit pointer)
2490 uint64_t flags; // flag bits
2491 uint64_t characters; // char * (64-bit pointer)
2492 uint64_t length; // number of non-NULL characters in above
2493};
2494
2495// The class object in a 64-bit Mach-O file.
2496struct class64_t {
2497 uint64_t isa; // class64_t * (64-bit pointer)
2498 uint64_t superclass; // class64_t * (64-bit pointer)
2499 uint64_t cache; // Cache (64-bit pointer)
2500 uint64_t vtable; // IMP * (64-bit pointer)
2501 uint64_t data; // class_ro64_t * (64-bit pointer)
2502};
2503
2504struct class_ro64_t {
2505 uint32_t flags;
2506 uint32_t instanceStart;
2507 uint32_t instanceSize;
2508 uint32_t reserved;
2509 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2510 uint64_t name; // const char * (64-bit pointer)
2511 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2512 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2513 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2514 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2515 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2516};
2517
2518inline void swapStruct(struct cfstring64_t &cfs) {
2519 sys::swapByteOrder(cfs.isa);
2520 sys::swapByteOrder(cfs.flags);
2521 sys::swapByteOrder(cfs.characters);
2522 sys::swapByteOrder(cfs.length);
2523}
2524
2525inline void swapStruct(struct class64_t &c) {
2526 sys::swapByteOrder(c.isa);
2527 sys::swapByteOrder(c.superclass);
2528 sys::swapByteOrder(c.cache);
2529 sys::swapByteOrder(c.vtable);
2530 sys::swapByteOrder(c.data);
2531}
2532
2533inline void swapStruct(struct class_ro64_t &cro) {
2534 sys::swapByteOrder(cro.flags);
2535 sys::swapByteOrder(cro.instanceStart);
2536 sys::swapByteOrder(cro.instanceSize);
2537 sys::swapByteOrder(cro.reserved);
2538 sys::swapByteOrder(cro.ivarLayout);
2539 sys::swapByteOrder(cro.name);
2540 sys::swapByteOrder(cro.baseMethods);
2541 sys::swapByteOrder(cro.baseProtocols);
2542 sys::swapByteOrder(cro.ivars);
2543 sys::swapByteOrder(cro.weakIvarLayout);
2544 sys::swapByteOrder(cro.baseProperties);
2545}
2546
2547static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2548 struct DisassembleInfo *info);
2549
2550// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2551// to an Objective-C class and returns the class name. It is also passed the
2552// address of the pointer, so when the pointer is zero as it can be in an .o
2553// file, that is used to look for an external relocation entry with a symbol
2554// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002555static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2556 uint64_t ReferenceValue,
2557 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002558 const char *r;
2559 uint32_t offset, left;
2560 SectionRef S;
2561
2562 // The pointer_value can be 0 in an object file and have a relocation
2563 // entry for the class symbol at the ReferenceValue (the address of the
2564 // pointer).
2565 if (pointer_value == 0) {
2566 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2567 if (r == nullptr || left < sizeof(uint64_t))
2568 return nullptr;
2569 uint64_t n_value;
2570 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2571 if (symbol_name == nullptr)
2572 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00002573 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002574 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2575 return class_name + 2;
2576 else
2577 return nullptr;
2578 }
2579
2580 // The case were the pointer_value is non-zero and points to a class defined
2581 // in this Mach-O file.
2582 r = get_pointer_64(pointer_value, offset, left, S, info);
2583 if (r == nullptr || left < sizeof(struct class64_t))
2584 return nullptr;
2585 struct class64_t c;
2586 memcpy(&c, r, sizeof(struct class64_t));
2587 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2588 swapStruct(c);
2589 if (c.data == 0)
2590 return nullptr;
2591 r = get_pointer_64(c.data, offset, left, S, info);
2592 if (r == nullptr || left < sizeof(struct class_ro64_t))
2593 return nullptr;
2594 struct class_ro64_t cro;
2595 memcpy(&cro, r, sizeof(struct class_ro64_t));
2596 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2597 swapStruct(cro);
2598 if (cro.name == 0)
2599 return nullptr;
2600 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2601 return name;
2602}
2603
2604// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2605// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002606static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2607 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002608 const char *r, *name;
2609 uint32_t offset, left;
2610 SectionRef S;
2611 struct cfstring64_t cfs;
2612 uint64_t cfs_characters;
2613
2614 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2615 if (r == nullptr || left < sizeof(struct cfstring64_t))
2616 return nullptr;
2617 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2618 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2619 swapStruct(cfs);
2620 if (cfs.characters == 0) {
2621 uint64_t n_value;
2622 const char *symbol_name = get_symbol_64(
2623 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2624 if (symbol_name == nullptr)
2625 return nullptr;
2626 cfs_characters = n_value;
2627 } else
2628 cfs_characters = cfs.characters;
2629 name = get_pointer_64(cfs_characters, offset, left, S, info);
2630
2631 return name;
2632}
2633
2634// get_objc2_64bit_selref() is used for disassembly and is passed a the address
2635// of a pointer to an Objective-C selector reference when the pointer value is
2636// zero as in a .o file and is likely to have a external relocation entry with
2637// who's symbol's n_value is the real pointer to the selector name. If that is
2638// the case the real pointer to the selector name is returned else 0 is
2639// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002640static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2641 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002642 uint32_t offset, left;
2643 SectionRef S;
2644
2645 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2646 if (r == nullptr || left < sizeof(uint64_t))
2647 return 0;
2648 uint64_t n_value;
2649 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2650 if (symbol_name == nullptr)
2651 return 0;
2652 return n_value;
2653}
2654
Kevin Enderbybf246f52014-09-24 23:08:22 +00002655// GuessLiteralPointer returns a string which for the item in the Mach-O file
2656// for the address passed in as ReferenceValue for printing as a comment with
2657// the instruction and also returns the corresponding type of that item
2658// indirectly through ReferenceType.
2659//
2660// If ReferenceValue is an address of literal cstring then a pointer to the
2661// cstring is returned and ReferenceType is set to
2662// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2663//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002664// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2665// Class ref that name is returned and the ReferenceType is set accordingly.
2666//
2667// Lastly, literals which are Symbol address in a literal pool are looked for
2668// and if found the symbol name is returned and ReferenceType is set to
2669// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2670//
2671// If there is no item in the Mach-O file for the address passed in as
2672// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002673static const char *GuessLiteralPointer(uint64_t ReferenceValue,
2674 uint64_t ReferencePC,
2675 uint64_t *ReferenceType,
2676 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002677 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00002678 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00002679 uint64_t sect_offset = ReferencePC - sect_addr;
2680 bool reloc_found = false;
2681 DataRefImpl Rel;
2682 MachO::any_relocation_info RE;
2683 bool isExtern = false;
2684 SymbolRef Symbol;
2685 for (const RelocationRef &Reloc : info->S.relocations()) {
2686 uint64_t RelocOffset;
2687 Reloc.getOffset(RelocOffset);
2688 if (RelocOffset == sect_offset) {
2689 Rel = Reloc.getRawDataRefImpl();
2690 RE = info->O->getRelocation(Rel);
2691 if (info->O->isRelocationScattered(RE))
2692 continue;
2693 isExtern = info->O->getPlainRelocationExternal(RE);
2694 if (isExtern) {
2695 symbol_iterator RelocSym = Reloc.getSymbol();
2696 Symbol = *RelocSym;
2697 }
2698 reloc_found = true;
2699 break;
2700 }
2701 }
2702 // If there is an external relocation entry for a symbol in a section
2703 // then used that symbol's value for the value of the reference.
2704 if (reloc_found && isExtern) {
2705 if (info->O->getAnyRelocationPCRel(RE)) {
2706 unsigned Type = info->O->getAnyRelocationType(RE);
2707 if (Type == MachO::X86_64_RELOC_SIGNED) {
2708 Symbol.getAddress(ReferenceValue);
2709 }
2710 }
2711 }
2712
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002713 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2714 // Message refs and Class refs.
2715 bool classref, selref, msgref, cfstring;
2716 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2717 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00002718 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002719 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2720 // And the pointer_value in that section is typically zero as it will be
2721 // set by dyld as part of the "bind information".
2722 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2723 if (name != nullptr) {
2724 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00002725 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002726 if (class_name != nullptr && class_name[1] == '_' &&
2727 class_name[2] != '\0') {
2728 info->class_name = class_name + 2;
2729 return name;
2730 }
2731 }
2732 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002733
David Blaikie33dd45d02015-03-23 18:39:02 +00002734 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002735 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2736 const char *name =
2737 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2738 if (name != nullptr)
2739 info->class_name = name;
2740 else
2741 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00002742 return name;
2743 }
2744
David Blaikie33dd45d02015-03-23 18:39:02 +00002745 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002746 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2747 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2748 return name;
2749 }
2750
David Blaikie33dd45d02015-03-23 18:39:02 +00002751 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002752 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2753
2754 if (pointer_value != 0)
2755 ReferenceValue = pointer_value;
2756
2757 const char *name = GuessCstringPointer(ReferenceValue, info);
2758 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00002759 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002760 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2761 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00002762 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002763 info->class_name = nullptr;
2764 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2765 info->selector_name = name;
2766 } else
2767 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2768 return name;
2769 }
2770
2771 // Lastly look for an indirect symbol with this ReferenceValue which is in
2772 // a literal pool. If found return that symbol name.
2773 name = GuessIndirectSymbol(ReferenceValue, info);
2774 if (name) {
2775 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2776 return name;
2777 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002778
2779 return nullptr;
2780}
2781
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002782// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00002783// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002784// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2785// is created and returns the symbol name that matches the ReferenceValue or
2786// nullptr if none. The ReferenceType is passed in for the IN type of
2787// reference the instruction is making from the values in defined in the header
2788// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2789// Out type and the ReferenceName will also be set which is added as a comment
2790// to the disassembled instruction.
2791//
Kevin Enderby04bf6932014-10-28 23:39:46 +00002792#if HAVE_CXXABI_H
2793// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002794// returned through ReferenceName and ReferenceType is set to
2795// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00002796#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002797//
2798// When this is called to get a symbol name for a branch target then the
2799// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2800// SymbolValue will be looked for in the indirect symbol table to determine if
2801// it is an address for a symbol stub. If so then the symbol name for that
2802// stub is returned indirectly through ReferenceName and then ReferenceType is
2803// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2804//
Kevin Enderbybf246f52014-09-24 23:08:22 +00002805// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002806// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2807// SymbolValue is checked to be an address of literal pointer, symbol pointer,
2808// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002809// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002810static const char *SymbolizerSymbolLookUp(void *DisInfo,
2811 uint64_t ReferenceValue,
2812 uint64_t *ReferenceType,
2813 uint64_t ReferencePC,
2814 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002815 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002816 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00002817 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002818 *ReferenceName = nullptr;
2819 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002820 return nullptr;
2821 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002822
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002823 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00002824
Kevin Enderby85974882014-09-26 22:20:44 +00002825 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2826 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002827 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002828 method_reference(info, ReferenceType, ReferenceName);
2829 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2830 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2831 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00002832#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002833 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00002834 if (info->demangled_name != nullptr)
2835 free(info->demangled_name);
2836 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002837 info->demangled_name =
2838 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002839 if (info->demangled_name != nullptr) {
2840 *ReferenceName = info->demangled_name;
2841 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2842 } else
2843 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2844 } else
2845#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002846 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2847 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2848 *ReferenceName =
2849 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00002850 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002851 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00002852 else
2853 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002854 // If this is arm64 and the reference is an adrp instruction save the
2855 // instruction, passed in ReferenceValue and the address of the instruction
2856 // for use later if we see and add immediate instruction.
2857 } else if (info->O->getArch() == Triple::aarch64 &&
2858 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2859 info->adrp_inst = ReferenceValue;
2860 info->adrp_addr = ReferencePC;
2861 SymbolName = nullptr;
2862 *ReferenceName = nullptr;
2863 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2864 // If this is arm64 and reference is an add immediate instruction and we
2865 // have
2866 // seen an adrp instruction just before it and the adrp's Xd register
2867 // matches
2868 // this add's Xn register reconstruct the value being referenced and look to
2869 // see if it is a literal pointer. Note the add immediate instruction is
2870 // passed in ReferenceValue.
2871 } else if (info->O->getArch() == Triple::aarch64 &&
2872 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2873 ReferencePC - 4 == info->adrp_addr &&
2874 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2875 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2876 uint32_t addxri_inst;
2877 uint64_t adrp_imm, addxri_imm;
2878
2879 adrp_imm =
2880 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2881 if (info->adrp_inst & 0x0200000)
2882 adrp_imm |= 0xfffffffffc000000LL;
2883
2884 addxri_inst = ReferenceValue;
2885 addxri_imm = (addxri_inst >> 10) & 0xfff;
2886 if (((addxri_inst >> 22) & 0x3) == 1)
2887 addxri_imm <<= 12;
2888
2889 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2890 (adrp_imm << 12) + addxri_imm;
2891
2892 *ReferenceName =
2893 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2894 if (*ReferenceName == nullptr)
2895 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2896 // If this is arm64 and the reference is a load register instruction and we
2897 // have seen an adrp instruction just before it and the adrp's Xd register
2898 // matches this add's Xn register reconstruct the value being referenced and
2899 // look to see if it is a literal pointer. Note the load register
2900 // instruction is passed in ReferenceValue.
2901 } else if (info->O->getArch() == Triple::aarch64 &&
2902 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2903 ReferencePC - 4 == info->adrp_addr &&
2904 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2905 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2906 uint32_t ldrxui_inst;
2907 uint64_t adrp_imm, ldrxui_imm;
2908
2909 adrp_imm =
2910 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2911 if (info->adrp_inst & 0x0200000)
2912 adrp_imm |= 0xfffffffffc000000LL;
2913
2914 ldrxui_inst = ReferenceValue;
2915 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2916
2917 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2918 (adrp_imm << 12) + (ldrxui_imm << 3);
2919
2920 *ReferenceName =
2921 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2922 if (*ReferenceName == nullptr)
2923 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2924 }
2925 // If this arm64 and is an load register (PC-relative) instruction the
2926 // ReferenceValue is the PC plus the immediate value.
2927 else if (info->O->getArch() == Triple::aarch64 &&
2928 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2929 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2930 *ReferenceName =
2931 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2932 if (*ReferenceName == nullptr)
2933 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00002934 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00002935#if HAVE_CXXABI_H
2936 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2937 if (info->demangled_name != nullptr)
2938 free(info->demangled_name);
2939 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002940 info->demangled_name =
2941 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002942 if (info->demangled_name != nullptr) {
2943 *ReferenceName = info->demangled_name;
2944 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2945 }
2946 }
2947#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002948 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002949 *ReferenceName = nullptr;
2950 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2951 }
2952
2953 return SymbolName;
2954}
2955
Kevin Enderbybf246f52014-09-24 23:08:22 +00002956/// \brief Emits the comments that are stored in the CommentStream.
2957/// Each comment in the CommentStream must end with a newline.
2958static void emitComments(raw_svector_ostream &CommentStream,
2959 SmallString<128> &CommentsToEmit,
2960 formatted_raw_ostream &FormattedOS,
2961 const MCAsmInfo &MAI) {
2962 // Flush the stream before taking its content.
2963 CommentStream.flush();
2964 StringRef Comments = CommentsToEmit.str();
2965 // Get the default information for printing a comment.
2966 const char *CommentBegin = MAI.getCommentString();
2967 unsigned CommentColumn = MAI.getCommentColumn();
2968 bool IsFirst = true;
2969 while (!Comments.empty()) {
2970 if (!IsFirst)
2971 FormattedOS << '\n';
2972 // Emit a line of comments.
2973 FormattedOS.PadToColumn(CommentColumn);
2974 size_t Position = Comments.find('\n');
2975 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2976 // Move after the newline character.
2977 Comments = Comments.substr(Position + 1);
2978 IsFirst = false;
2979 }
2980 FormattedOS.flush();
2981
2982 // Tell the comment stream that the vector changed underneath it.
2983 CommentsToEmit.clear();
2984 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002985}
2986
Kevin Enderby95df54c2015-02-04 01:01:38 +00002987static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
2988 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002989 const char *McpuDefault = nullptr;
2990 const Target *ThumbTarget = nullptr;
2991 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002992 if (!TheTarget) {
2993 // GetTarget prints out stuff.
2994 return;
2995 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002996 if (MCPU.empty() && McpuDefault)
2997 MCPU = McpuDefault;
2998
Ahmed Charles56440fd2014-03-06 05:51:42 +00002999 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003000 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003001 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003002 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003003
Kevin Enderbyc9595622014-08-06 23:24:41 +00003004 // Package up features to be passed to target/subtarget
3005 std::string FeaturesStr;
3006 if (MAttrs.size()) {
3007 SubtargetFeatures Features;
3008 for (unsigned i = 0; i != MAttrs.size(); ++i)
3009 Features.AddFeature(MAttrs[i]);
3010 FeaturesStr = Features.getString();
3011 }
3012
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003013 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00003014 std::unique_ptr<const MCRegisterInfo> MRI(
3015 TheTarget->createMCRegInfo(TripleName));
3016 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00003017 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00003018 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00003019 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00003020 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003021 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003022 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003023 std::unique_ptr<MCSymbolizer> Symbolizer;
3024 struct DisassembleInfo SymbolizerInfo;
3025 std::unique_ptr<MCRelocationInfo> RelInfo(
3026 TheTarget->createMCRelocationInfo(TripleName, Ctx));
3027 if (RelInfo) {
3028 Symbolizer.reset(TheTarget->createMCSymbolizer(
3029 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00003030 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003031 DisAsm->setSymbolizer(std::move(Symbolizer));
3032 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003033 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00003034 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +00003035 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00003036 // Set the display preference for hex vs. decimal immediates.
3037 IP->setPrintImmHex(PrintImmHex);
3038 // Comment stream and backing vector.
3039 SmallString<128> CommentsToEmit;
3040 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00003041 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
3042 // if it is done then arm64 comments for string literals don't get printed
3043 // and some constant get printed instead and not setting it causes intel
3044 // (32-bit and 64-bit) comments printed with different spacing before the
3045 // comment causing different diffs with the 'C' disassembler library API.
3046 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003047
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003048 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00003049 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003050 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003051 return;
3052 }
3053
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003054 // Set up thumb disassembler.
3055 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
3056 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
3057 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00003058 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003059 std::unique_ptr<MCInstPrinter> ThumbIP;
3060 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00003061 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
3062 struct DisassembleInfo ThumbSymbolizerInfo;
3063 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003064 if (ThumbTarget) {
3065 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
3066 ThumbAsmInfo.reset(
3067 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
3068 ThumbSTI.reset(
3069 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
3070 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
3071 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00003072 MCContext *PtrThumbCtx = ThumbCtx.get();
3073 ThumbRelInfo.reset(
3074 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
3075 if (ThumbRelInfo) {
3076 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
3077 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00003078 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00003079 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
3080 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003081 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
3082 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +00003083 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
3084 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00003085 // Set the display preference for hex vs. decimal immediates.
3086 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003087 }
3088
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003089 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003090 errs() << "error: couldn't initialize disassembler for target "
3091 << ThumbTripleName << '\n';
3092 return;
3093 }
3094
Charles Davis8bdfafd2013-09-01 04:28:48 +00003095 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003096
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003097 // FIXME: Using the -cfg command line option, this code used to be able to
3098 // annotate relocations with the referenced symbol's name, and if this was
3099 // inside a __[cf]string section, the data it points to. This is now replaced
3100 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00003101 std::vector<SectionRef> Sections;
3102 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003103 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00003104 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003105
Kevin Enderby273ae012013-06-06 17:20:50 +00003106 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
3107 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003108
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003109 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00003110 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003111
Kevin Enderby273ae012013-06-06 17:20:50 +00003112 // Build a data in code table that is sorted on by the address of each entry.
3113 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00003114 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00003115 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00003116 else
3117 BaseAddress = BaseSegmentAddress;
3118 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00003119 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00003120 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00003121 uint32_t Offset;
3122 DI->getOffset(Offset);
3123 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
3124 }
3125 array_pod_sort(Dices.begin(), Dices.end());
3126
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003127#ifndef NDEBUG
3128 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
3129#else
3130 raw_ostream &DebugOut = nulls();
3131#endif
3132
Ahmed Charles56440fd2014-03-06 05:51:42 +00003133 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00003134 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00003135 // Try to find debug info and set up the DIContext for it.
3136 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00003137 // A separate DSym file path was specified, parse it as a macho file,
3138 // get the sections and supply it to the section name parsing machinery.
3139 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00003140 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00003141 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00003142 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00003143 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00003144 return;
3145 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00003146 DbgObj =
3147 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
3148 .get()
3149 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00003150 }
3151
Eric Christopher7370b552012-11-12 21:40:38 +00003152 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00003153 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00003154 }
3155
Kevin Enderby95df54c2015-02-04 01:01:38 +00003156 if (DumpSections.size() == 0)
3157 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00003158
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003159 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00003160 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00003161 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
3162 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003163
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00003164 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003165
Rafael Espindolab0f76a42013-04-05 15:15:22 +00003166 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00003167 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00003168 continue;
3169
Rafael Espindola7fc5b872014-11-12 02:04:27 +00003170 StringRef BytesStr;
3171 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00003172 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
3173 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00003174 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00003175
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003176 bool symbolTableWorked = false;
3177
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003178 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00003179 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
3180 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00003181 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00003182 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00003183 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00003184 RelocOffset -= SectionAddress;
3185
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00003186 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00003187
Rafael Espindola806f0062013-06-05 01:33:53 +00003188 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003189 }
3190 array_pod_sort(Relocs.begin(), Relocs.end());
3191
Kevin Enderbybf246f52014-09-24 23:08:22 +00003192 // Create a map of symbol addresses to symbol names for use by
3193 // the SymbolizerSymbolLookUp() routine.
3194 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00003195 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00003196 for (const SymbolRef &Symbol : MachOOF->symbols()) {
3197 SymbolRef::Type ST;
3198 Symbol.getType(ST);
3199 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
3200 ST == SymbolRef::ST_Other) {
3201 uint64_t Address;
3202 Symbol.getAddress(Address);
3203 StringRef SymName;
3204 Symbol.getName(SymName);
3205 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00003206 if (!DisSymName.empty() && DisSymName == SymName)
3207 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00003208 }
3209 }
David Blaikie33dd45d02015-03-23 18:39:02 +00003210 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00003211 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
3212 return;
3213 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003214 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00003215 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003216 SymbolizerInfo.O = MachOOF;
3217 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00003218 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003219 SymbolizerInfo.Sections = &Sections;
3220 SymbolizerInfo.class_name = nullptr;
3221 SymbolizerInfo.selector_name = nullptr;
3222 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00003223 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00003224 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00003225 SymbolizerInfo.adrp_addr = 0;
3226 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00003227 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00003228 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00003229 ThumbSymbolizerInfo.O = MachOOF;
3230 ThumbSymbolizerInfo.S = Sections[SectIdx];
3231 ThumbSymbolizerInfo.AddrMap = &AddrMap;
3232 ThumbSymbolizerInfo.Sections = &Sections;
3233 ThumbSymbolizerInfo.class_name = nullptr;
3234 ThumbSymbolizerInfo.selector_name = nullptr;
3235 ThumbSymbolizerInfo.method = nullptr;
3236 ThumbSymbolizerInfo.demangled_name = nullptr;
3237 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00003238 ThumbSymbolizerInfo.adrp_addr = 0;
3239 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003240
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003241 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003242 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00003243 StringRef SymName;
3244 Symbols[SymIdx].getName(SymName);
3245
3246 SymbolRef::Type ST;
3247 Symbols[SymIdx].getType(ST);
3248 if (ST != SymbolRef::ST_Function)
3249 continue;
3250
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003251 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00003252 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00003253 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003254 continue;
3255
Kevin Enderby6a221752015-03-17 17:10:57 +00003256 // If we are only disassembling one symbol see if this is that symbol.
3257 if (!DisSymName.empty() && DisSymName != SymName)
3258 continue;
3259
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003260 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00003261 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00003262 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00003263 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00003264 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00003265
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003266 // Stop disassembling either at the beginning of the next symbol or at
3267 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00003268 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00003269 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003270 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00003271 while (Symbols.size() > NextSymIdx) {
3272 SymbolRef::Type NextSymType;
3273 Symbols[NextSymIdx].getType(NextSymType);
3274 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00003275 containsNextSym =
3276 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00003277 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00003278 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00003279 break;
3280 }
3281 ++NextSymIdx;
3282 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003283
Rafael Espindola80291272014-10-08 15:28:58 +00003284 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003285 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00003286 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003287
3288 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00003289
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003290 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
3291 bool isThumb =
3292 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
3293
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003294 outs() << SymName << ":\n";
3295 DILineInfo lastLine;
3296 for (uint64_t Index = Start; Index < End; Index += Size) {
3297 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00003298
Kevin Enderbybf246f52014-09-24 23:08:22 +00003299 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00003300 if (!NoLeadingAddr) {
3301 if (FullLeadingAddr) {
3302 if (MachOOF->is64Bit())
3303 outs() << format("%016" PRIx64, PC);
3304 else
3305 outs() << format("%08" PRIx64, PC);
3306 } else {
3307 outs() << format("%8" PRIx64 ":", PC);
3308 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00003309 }
3310 if (!NoShowRawInsn)
3311 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00003312
3313 // Check the data in code table here to see if this is data not an
3314 // instruction to be disassembled.
3315 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00003316 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003317 dice_table_iterator DTI =
3318 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
3319 compareDiceTableEntries);
3320 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00003321 uint16_t Length;
3322 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00003323 uint16_t Kind;
3324 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00003325 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00003326 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3327 (PC == (DTI->first + Length - 1)) && (Length & 1))
3328 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00003329 continue;
3330 }
3331
Kevin Enderbybf246f52014-09-24 23:08:22 +00003332 SmallVector<char, 64> AnnotationsBytes;
3333 raw_svector_ostream Annotations(AnnotationsBytes);
3334
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003335 bool gotInst;
3336 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00003337 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003338 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003339 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00003340 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00003341 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003342 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00003343 if (!NoShowRawInsn) {
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00003344 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size));
Kevin Enderbybf246f52014-09-24 23:08:22 +00003345 }
3346 formatted_raw_ostream FormattedOS(outs());
3347 Annotations.flush();
3348 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003349 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00003350 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003351 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00003352 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00003353 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00003354
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003355 // Print debug info.
3356 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003357 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003358 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00003359 if (dli != lastLine && dli.Line != 0)
3360 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3361 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003362 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003363 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003364 outs() << "\n";
3365 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003366 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003367 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003368 outs() << format("\t.byte 0x%02x #bad opcode\n",
3369 *(Bytes.data() + Index) & 0xff);
3370 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003371 } else if (Arch == Triple::aarch64) {
3372 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3373 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3374 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3375 (*(Bytes.data() + Index + 3) & 0xff) << 24;
3376 outs() << format("\t.long\t0x%08x\n", opcode);
3377 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003378 } else {
3379 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3380 if (Size == 0)
3381 Size = 1; // skip illegible bytes
3382 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003383 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003384 }
3385 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003386 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00003387 // Reading the symbol table didn't work, disassemble the whole section.
3388 uint64_t SectAddress = Sections[SectIdx].getAddress();
3389 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00003390 uint64_t InstSize;
3391 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00003392 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00003393
Kevin Enderbybf246f52014-09-24 23:08:22 +00003394 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00003395 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3396 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00003397 if (!NoLeadingAddr) {
3398 if (FullLeadingAddr) {
3399 if (MachOOF->is64Bit())
3400 outs() << format("%016" PRIx64, PC);
3401 else
3402 outs() << format("%08" PRIx64, PC);
3403 } else {
3404 outs() << format("%8" PRIx64 ":", PC);
3405 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00003406 }
3407 if (!NoShowRawInsn) {
3408 outs() << "\t";
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00003409 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize));
Kevin Enderbybf246f52014-09-24 23:08:22 +00003410 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00003411 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00003412 outs() << "\n";
3413 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003414 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003415 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003416 outs() << format("\t.byte 0x%02x #bad opcode\n",
3417 *(Bytes.data() + Index) & 0xff);
3418 InstSize = 1; // skip exactly one illegible byte and move on.
3419 } else {
3420 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3421 if (InstSize == 0)
3422 InstSize = 1; // skip illegible bytes
3423 }
Bill Wendling4e68e062012-07-19 00:17:40 +00003424 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00003425 }
3426 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00003427 // The TripleName's need to be reset if we are called again for a different
3428 // archtecture.
3429 TripleName = "";
3430 ThumbTripleName = "";
3431
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003432 if (SymbolizerInfo.method != nullptr)
3433 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00003434 if (SymbolizerInfo.demangled_name != nullptr)
3435 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00003436 if (SymbolizerInfo.bindtable != nullptr)
3437 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00003438 if (ThumbSymbolizerInfo.method != nullptr)
3439 free(ThumbSymbolizerInfo.method);
3440 if (ThumbSymbolizerInfo.demangled_name != nullptr)
3441 free(ThumbSymbolizerInfo.demangled_name);
3442 if (ThumbSymbolizerInfo.bindtable != nullptr)
3443 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003444 }
3445}
Tim Northover4bd286a2014-08-01 13:07:19 +00003446
Tim Northover39c70bb2014-08-12 11:52:59 +00003447//===----------------------------------------------------------------------===//
3448// __compact_unwind section dumping
3449//===----------------------------------------------------------------------===//
3450
Tim Northover4bd286a2014-08-01 13:07:19 +00003451namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00003452
3453template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003454 using llvm::support::little;
3455 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00003456
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003457 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3458 Buf += sizeof(T);
3459 return Val;
3460}
Tim Northover39c70bb2014-08-12 11:52:59 +00003461
Tim Northover4bd286a2014-08-01 13:07:19 +00003462struct CompactUnwindEntry {
3463 uint32_t OffsetInSection;
3464
3465 uint64_t FunctionAddr;
3466 uint32_t Length;
3467 uint32_t CompactEncoding;
3468 uint64_t PersonalityAddr;
3469 uint64_t LSDAAddr;
3470
3471 RelocationRef FunctionReloc;
3472 RelocationRef PersonalityReloc;
3473 RelocationRef LSDAReloc;
3474
3475 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003476 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00003477 if (Is64)
3478 read<uint64_t>(Contents.data() + Offset);
3479 else
3480 read<uint32_t>(Contents.data() + Offset);
3481 }
3482
3483private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003484 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00003485 FunctionAddr = readNext<UIntPtr>(Buf);
3486 Length = readNext<uint32_t>(Buf);
3487 CompactEncoding = readNext<uint32_t>(Buf);
3488 PersonalityAddr = readNext<UIntPtr>(Buf);
3489 LSDAAddr = readNext<UIntPtr>(Buf);
3490 }
3491};
3492}
3493
3494/// Given a relocation from __compact_unwind, consisting of the RelocationRef
3495/// and data being relocated, determine the best base Name and Addend to use for
3496/// display purposes.
3497///
3498/// 1. An Extern relocation will directly reference a symbol (and the data is
3499/// then already an addend), so use that.
3500/// 2. Otherwise the data is an offset in the object file's layout; try to find
3501// a symbol before it in the same section, and use the offset from there.
3502/// 3. Finally, if all that fails, fall back to an offset from the start of the
3503/// referenced section.
3504static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3505 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003506 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00003507 StringRef &Name, uint64_t &Addend) {
3508 if (Reloc.getSymbol() != Obj->symbol_end()) {
3509 Reloc.getSymbol()->getName(Name);
3510 Addend = Addr;
3511 return;
3512 }
3513
3514 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3515 SectionRef RelocSection = Obj->getRelocationSection(RE);
3516
Rafael Espindola80291272014-10-08 15:28:58 +00003517 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00003518
3519 auto Sym = Symbols.upper_bound(Addr);
3520 if (Sym == Symbols.begin()) {
3521 // The first symbol in the object is after this reference, the best we can
3522 // do is section-relative notation.
3523 RelocSection.getName(Name);
3524 Addend = Addr - SectionAddr;
3525 return;
3526 }
3527
3528 // Go back one so that SymbolAddress <= Addr.
3529 --Sym;
3530
3531 section_iterator SymSection = Obj->section_end();
3532 Sym->second.getSection(SymSection);
3533 if (RelocSection == *SymSection) {
3534 // There's a valid symbol in the same section before this reference.
3535 Sym->second.getName(Name);
3536 Addend = Addr - Sym->first;
3537 return;
3538 }
3539
3540 // There is a symbol before this reference, but it's in a different
3541 // section. Probably not helpful to mention it, so use the section name.
3542 RelocSection.getName(Name);
3543 Addend = Addr - SectionAddr;
3544}
3545
3546static void printUnwindRelocDest(const MachOObjectFile *Obj,
3547 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003548 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00003549 StringRef Name;
3550 uint64_t Addend;
3551
Tim Northover0b0add52014-09-09 10:45:06 +00003552 if (!Reloc.getObjectFile())
3553 return;
3554
Tim Northover4bd286a2014-08-01 13:07:19 +00003555 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3556
3557 outs() << Name;
3558 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00003559 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00003560}
3561
3562static void
3563printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3564 std::map<uint64_t, SymbolRef> &Symbols,
3565 const SectionRef &CompactUnwind) {
3566
3567 assert(Obj->isLittleEndian() &&
3568 "There should not be a big-endian .o with __compact_unwind");
3569
3570 bool Is64 = Obj->is64Bit();
3571 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3572 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3573
3574 StringRef Contents;
3575 CompactUnwind.getContents(Contents);
3576
3577 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3578
3579 // First populate the initial raw offsets, encodings and so on from the entry.
3580 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3581 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3582 CompactUnwinds.push_back(Entry);
3583 }
3584
3585 // Next we need to look at the relocations to find out what objects are
3586 // actually being referred to.
3587 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3588 uint64_t RelocAddress;
3589 Reloc.getOffset(RelocAddress);
3590
3591 uint32_t EntryIdx = RelocAddress / EntrySize;
3592 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3593 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3594
3595 if (OffsetInEntry == 0)
3596 Entry.FunctionReloc = Reloc;
3597 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3598 Entry.PersonalityReloc = Reloc;
3599 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3600 Entry.LSDAReloc = Reloc;
3601 else
3602 llvm_unreachable("Unexpected relocation in __compact_unwind section");
3603 }
3604
3605 // Finally, we're ready to print the data we've gathered.
3606 outs() << "Contents of __compact_unwind section:\n";
3607 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00003608 outs() << " Entry at offset "
3609 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00003610
3611 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003612 outs() << " start: " << format("0x%" PRIx64,
3613 Entry.FunctionAddr) << ' ';
3614 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00003615 outs() << '\n';
3616
3617 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003618 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3619 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00003620 // 3. The 32-bit compact encoding.
3621 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00003622 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00003623
3624 // 4. The personality function, if present.
3625 if (Entry.PersonalityReloc.getObjectFile()) {
3626 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00003627 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00003628 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3629 Entry.PersonalityAddr);
3630 outs() << '\n';
3631 }
3632
3633 // 5. This entry's language-specific data area.
3634 if (Entry.LSDAReloc.getObjectFile()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003635 outs() << " LSDA: " << format("0x%" PRIx64,
3636 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00003637 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3638 outs() << '\n';
3639 }
3640 }
3641}
3642
Tim Northover39c70bb2014-08-12 11:52:59 +00003643//===----------------------------------------------------------------------===//
3644// __unwind_info section dumping
3645//===----------------------------------------------------------------------===//
3646
3647static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3648 const char *Pos = PageStart;
3649 uint32_t Kind = readNext<uint32_t>(Pos);
3650 (void)Kind;
3651 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3652
3653 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3654 uint16_t NumEntries = readNext<uint16_t>(Pos);
3655
3656 Pos = PageStart + EntriesStart;
3657 for (unsigned i = 0; i < NumEntries; ++i) {
3658 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3659 uint32_t Encoding = readNext<uint32_t>(Pos);
3660
3661 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003662 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3663 << ", "
3664 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003665 }
3666}
3667
3668static void printCompressedSecondLevelUnwindPage(
3669 const char *PageStart, uint32_t FunctionBase,
3670 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3671 const char *Pos = PageStart;
3672 uint32_t Kind = readNext<uint32_t>(Pos);
3673 (void)Kind;
3674 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3675
3676 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3677 uint16_t NumEntries = readNext<uint16_t>(Pos);
3678
3679 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3680 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00003681 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3682 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00003683
3684 Pos = PageStart + EntriesStart;
3685 for (unsigned i = 0; i < NumEntries; ++i) {
3686 uint32_t Entry = readNext<uint32_t>(Pos);
3687 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3688 uint32_t EncodingIdx = Entry >> 24;
3689
3690 uint32_t Encoding;
3691 if (EncodingIdx < CommonEncodings.size())
3692 Encoding = CommonEncodings[EncodingIdx];
3693 else
3694 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3695
3696 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003697 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3698 << ", "
3699 << "encoding[" << EncodingIdx
3700 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003701 }
3702}
3703
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003704static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3705 std::map<uint64_t, SymbolRef> &Symbols,
3706 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00003707
3708 assert(Obj->isLittleEndian() &&
3709 "There should not be a big-endian .o with __unwind_info");
3710
3711 outs() << "Contents of __unwind_info section:\n";
3712
3713 StringRef Contents;
3714 UnwindInfo.getContents(Contents);
3715 const char *Pos = Contents.data();
3716
3717 //===----------------------------------
3718 // Section header
3719 //===----------------------------------
3720
3721 uint32_t Version = readNext<uint32_t>(Pos);
3722 outs() << " Version: "
3723 << format("0x%" PRIx32, Version) << '\n';
3724 assert(Version == 1 && "only understand version 1");
3725
3726 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3727 outs() << " Common encodings array section offset: "
3728 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3729 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3730 outs() << " Number of common encodings in array: "
3731 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3732
3733 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3734 outs() << " Personality function array section offset: "
3735 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3736 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3737 outs() << " Number of personality functions in array: "
3738 << format("0x%" PRIx32, NumPersonalities) << '\n';
3739
3740 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3741 outs() << " Index array section offset: "
3742 << format("0x%" PRIx32, IndicesStart) << '\n';
3743 uint32_t NumIndices = readNext<uint32_t>(Pos);
3744 outs() << " Number of indices in array: "
3745 << format("0x%" PRIx32, NumIndices) << '\n';
3746
3747 //===----------------------------------
3748 // A shared list of common encodings
3749 //===----------------------------------
3750
3751 // These occupy indices in the range [0, N] whenever an encoding is referenced
3752 // from a compressed 2nd level index table. In practice the linker only
3753 // creates ~128 of these, so that indices are available to embed encodings in
3754 // the 2nd level index.
3755
3756 SmallVector<uint32_t, 64> CommonEncodings;
3757 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3758 Pos = Contents.data() + CommonEncodingsStart;
3759 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3760 uint32_t Encoding = readNext<uint32_t>(Pos);
3761 CommonEncodings.push_back(Encoding);
3762
3763 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3764 << '\n';
3765 }
3766
Tim Northover39c70bb2014-08-12 11:52:59 +00003767 //===----------------------------------
3768 // Personality functions used in this executable
3769 //===----------------------------------
3770
3771 // There should be only a handful of these (one per source language,
3772 // roughly). Particularly since they only get 2 bits in the compact encoding.
3773
3774 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3775 Pos = Contents.data() + PersonalitiesStart;
3776 for (unsigned i = 0; i < NumPersonalities; ++i) {
3777 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3778 outs() << " personality[" << i + 1
3779 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3780 }
3781
3782 //===----------------------------------
3783 // The level 1 index entries
3784 //===----------------------------------
3785
3786 // These specify an approximate place to start searching for the more detailed
3787 // information, sorted by PC.
3788
3789 struct IndexEntry {
3790 uint32_t FunctionOffset;
3791 uint32_t SecondLevelPageStart;
3792 uint32_t LSDAStart;
3793 };
3794
3795 SmallVector<IndexEntry, 4> IndexEntries;
3796
3797 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3798 Pos = Contents.data() + IndicesStart;
3799 for (unsigned i = 0; i < NumIndices; ++i) {
3800 IndexEntry Entry;
3801
3802 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3803 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3804 Entry.LSDAStart = readNext<uint32_t>(Pos);
3805 IndexEntries.push_back(Entry);
3806
3807 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003808 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3809 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00003810 << "2nd level page offset="
3811 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003812 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003813 }
3814
Tim Northover39c70bb2014-08-12 11:52:59 +00003815 //===----------------------------------
3816 // Next come the LSDA tables
3817 //===----------------------------------
3818
3819 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3820 // the first top-level index's LSDAOffset to the last (sentinel).
3821
3822 outs() << " LSDA descriptors:\n";
3823 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3824 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3825 (2 * sizeof(uint32_t));
3826 for (int i = 0; i < NumLSDAs; ++i) {
3827 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3828 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3829 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003830 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3831 << ", "
3832 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003833 }
3834
3835 //===----------------------------------
3836 // Finally, the 2nd level indices
3837 //===----------------------------------
3838
3839 // Generally these are 4K in size, and have 2 possible forms:
3840 // + Regular stores up to 511 entries with disparate encodings
3841 // + Compressed stores up to 1021 entries if few enough compact encoding
3842 // values are used.
3843 outs() << " Second level indices:\n";
3844 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3845 // The final sentinel top-level index has no associated 2nd level page
3846 if (IndexEntries[i].SecondLevelPageStart == 0)
3847 break;
3848
3849 outs() << " Second level index[" << i << "]: "
3850 << "offset in section="
3851 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3852 << ", "
3853 << "base function offset="
3854 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3855
3856 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00003857 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00003858 if (Kind == 2)
3859 printRegularSecondLevelUnwindPage(Pos);
3860 else if (Kind == 3)
3861 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3862 CommonEncodings);
3863 else
3864 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00003865 }
3866}
3867
Tim Northover4bd286a2014-08-01 13:07:19 +00003868void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3869 std::map<uint64_t, SymbolRef> Symbols;
3870 for (const SymbolRef &SymRef : Obj->symbols()) {
3871 // Discard any undefined or absolute symbols. They're not going to take part
3872 // in the convenience lookup for unwind info and just take up resources.
3873 section_iterator Section = Obj->section_end();
3874 SymRef.getSection(Section);
3875 if (Section == Obj->section_end())
3876 continue;
3877
3878 uint64_t Addr;
3879 SymRef.getAddress(Addr);
3880 Symbols.insert(std::make_pair(Addr, SymRef));
3881 }
3882
3883 for (const SectionRef &Section : Obj->sections()) {
3884 StringRef SectName;
3885 Section.getName(SectName);
3886 if (SectName == "__compact_unwind")
3887 printMachOCompactUnwindSection(Obj, Symbols, Section);
3888 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00003889 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00003890 else if (SectName == "__eh_frame")
3891 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00003892 }
3893}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003894
3895static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3896 uint32_t cpusubtype, uint32_t filetype,
3897 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3898 bool verbose) {
3899 outs() << "Mach header\n";
3900 outs() << " magic cputype cpusubtype caps filetype ncmds "
3901 "sizeofcmds flags\n";
3902 if (verbose) {
3903 if (magic == MachO::MH_MAGIC)
3904 outs() << " MH_MAGIC";
3905 else if (magic == MachO::MH_MAGIC_64)
3906 outs() << "MH_MAGIC_64";
3907 else
3908 outs() << format(" 0x%08" PRIx32, magic);
3909 switch (cputype) {
3910 case MachO::CPU_TYPE_I386:
3911 outs() << " I386";
3912 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3913 case MachO::CPU_SUBTYPE_I386_ALL:
3914 outs() << " ALL";
3915 break;
3916 default:
3917 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3918 break;
3919 }
3920 break;
3921 case MachO::CPU_TYPE_X86_64:
3922 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00003923 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3924 case MachO::CPU_SUBTYPE_X86_64_ALL:
3925 outs() << " ALL";
3926 break;
3927 case MachO::CPU_SUBTYPE_X86_64_H:
3928 outs() << " Haswell";
3929 break;
3930 default:
3931 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3932 break;
3933 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003934 break;
3935 case MachO::CPU_TYPE_ARM:
3936 outs() << " ARM";
3937 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3938 case MachO::CPU_SUBTYPE_ARM_ALL:
3939 outs() << " ALL";
3940 break;
3941 case MachO::CPU_SUBTYPE_ARM_V4T:
3942 outs() << " V4T";
3943 break;
3944 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3945 outs() << " V5TEJ";
3946 break;
3947 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3948 outs() << " XSCALE";
3949 break;
3950 case MachO::CPU_SUBTYPE_ARM_V6:
3951 outs() << " V6";
3952 break;
3953 case MachO::CPU_SUBTYPE_ARM_V6M:
3954 outs() << " V6M";
3955 break;
3956 case MachO::CPU_SUBTYPE_ARM_V7:
3957 outs() << " V7";
3958 break;
3959 case MachO::CPU_SUBTYPE_ARM_V7EM:
3960 outs() << " V7EM";
3961 break;
3962 case MachO::CPU_SUBTYPE_ARM_V7K:
3963 outs() << " V7K";
3964 break;
3965 case MachO::CPU_SUBTYPE_ARM_V7M:
3966 outs() << " V7M";
3967 break;
3968 case MachO::CPU_SUBTYPE_ARM_V7S:
3969 outs() << " V7S";
3970 break;
3971 default:
3972 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3973 break;
3974 }
3975 break;
3976 case MachO::CPU_TYPE_ARM64:
3977 outs() << " ARM64";
3978 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3979 case MachO::CPU_SUBTYPE_ARM64_ALL:
3980 outs() << " ALL";
3981 break;
3982 default:
3983 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3984 break;
3985 }
3986 break;
3987 case MachO::CPU_TYPE_POWERPC:
3988 outs() << " PPC";
3989 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3990 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3991 outs() << " ALL";
3992 break;
3993 default:
3994 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3995 break;
3996 }
3997 break;
3998 case MachO::CPU_TYPE_POWERPC64:
3999 outs() << " PPC64";
4000 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
4001 case MachO::CPU_SUBTYPE_POWERPC_ALL:
4002 outs() << " ALL";
4003 break;
4004 default:
4005 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4006 break;
4007 }
4008 break;
4009 }
4010 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004011 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004012 } else {
4013 outs() << format(" 0x%02" PRIx32,
4014 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4015 }
4016 switch (filetype) {
4017 case MachO::MH_OBJECT:
4018 outs() << " OBJECT";
4019 break;
4020 case MachO::MH_EXECUTE:
4021 outs() << " EXECUTE";
4022 break;
4023 case MachO::MH_FVMLIB:
4024 outs() << " FVMLIB";
4025 break;
4026 case MachO::MH_CORE:
4027 outs() << " CORE";
4028 break;
4029 case MachO::MH_PRELOAD:
4030 outs() << " PRELOAD";
4031 break;
4032 case MachO::MH_DYLIB:
4033 outs() << " DYLIB";
4034 break;
4035 case MachO::MH_DYLIB_STUB:
4036 outs() << " DYLIB_STUB";
4037 break;
4038 case MachO::MH_DYLINKER:
4039 outs() << " DYLINKER";
4040 break;
4041 case MachO::MH_BUNDLE:
4042 outs() << " BUNDLE";
4043 break;
4044 case MachO::MH_DSYM:
4045 outs() << " DSYM";
4046 break;
4047 case MachO::MH_KEXT_BUNDLE:
4048 outs() << " KEXTBUNDLE";
4049 break;
4050 default:
4051 outs() << format(" %10u", filetype);
4052 break;
4053 }
4054 outs() << format(" %5u", ncmds);
4055 outs() << format(" %10u", sizeofcmds);
4056 uint32_t f = flags;
4057 if (f & MachO::MH_NOUNDEFS) {
4058 outs() << " NOUNDEFS";
4059 f &= ~MachO::MH_NOUNDEFS;
4060 }
4061 if (f & MachO::MH_INCRLINK) {
4062 outs() << " INCRLINK";
4063 f &= ~MachO::MH_INCRLINK;
4064 }
4065 if (f & MachO::MH_DYLDLINK) {
4066 outs() << " DYLDLINK";
4067 f &= ~MachO::MH_DYLDLINK;
4068 }
4069 if (f & MachO::MH_BINDATLOAD) {
4070 outs() << " BINDATLOAD";
4071 f &= ~MachO::MH_BINDATLOAD;
4072 }
4073 if (f & MachO::MH_PREBOUND) {
4074 outs() << " PREBOUND";
4075 f &= ~MachO::MH_PREBOUND;
4076 }
4077 if (f & MachO::MH_SPLIT_SEGS) {
4078 outs() << " SPLIT_SEGS";
4079 f &= ~MachO::MH_SPLIT_SEGS;
4080 }
4081 if (f & MachO::MH_LAZY_INIT) {
4082 outs() << " LAZY_INIT";
4083 f &= ~MachO::MH_LAZY_INIT;
4084 }
4085 if (f & MachO::MH_TWOLEVEL) {
4086 outs() << " TWOLEVEL";
4087 f &= ~MachO::MH_TWOLEVEL;
4088 }
4089 if (f & MachO::MH_FORCE_FLAT) {
4090 outs() << " FORCE_FLAT";
4091 f &= ~MachO::MH_FORCE_FLAT;
4092 }
4093 if (f & MachO::MH_NOMULTIDEFS) {
4094 outs() << " NOMULTIDEFS";
4095 f &= ~MachO::MH_NOMULTIDEFS;
4096 }
4097 if (f & MachO::MH_NOFIXPREBINDING) {
4098 outs() << " NOFIXPREBINDING";
4099 f &= ~MachO::MH_NOFIXPREBINDING;
4100 }
4101 if (f & MachO::MH_PREBINDABLE) {
4102 outs() << " PREBINDABLE";
4103 f &= ~MachO::MH_PREBINDABLE;
4104 }
4105 if (f & MachO::MH_ALLMODSBOUND) {
4106 outs() << " ALLMODSBOUND";
4107 f &= ~MachO::MH_ALLMODSBOUND;
4108 }
4109 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
4110 outs() << " SUBSECTIONS_VIA_SYMBOLS";
4111 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
4112 }
4113 if (f & MachO::MH_CANONICAL) {
4114 outs() << " CANONICAL";
4115 f &= ~MachO::MH_CANONICAL;
4116 }
4117 if (f & MachO::MH_WEAK_DEFINES) {
4118 outs() << " WEAK_DEFINES";
4119 f &= ~MachO::MH_WEAK_DEFINES;
4120 }
4121 if (f & MachO::MH_BINDS_TO_WEAK) {
4122 outs() << " BINDS_TO_WEAK";
4123 f &= ~MachO::MH_BINDS_TO_WEAK;
4124 }
4125 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
4126 outs() << " ALLOW_STACK_EXECUTION";
4127 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
4128 }
4129 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
4130 outs() << " DEAD_STRIPPABLE_DYLIB";
4131 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
4132 }
4133 if (f & MachO::MH_PIE) {
4134 outs() << " PIE";
4135 f &= ~MachO::MH_PIE;
4136 }
4137 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
4138 outs() << " NO_REEXPORTED_DYLIBS";
4139 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
4140 }
4141 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
4142 outs() << " MH_HAS_TLV_DESCRIPTORS";
4143 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
4144 }
4145 if (f & MachO::MH_NO_HEAP_EXECUTION) {
4146 outs() << " MH_NO_HEAP_EXECUTION";
4147 f &= ~MachO::MH_NO_HEAP_EXECUTION;
4148 }
4149 if (f & MachO::MH_APP_EXTENSION_SAFE) {
4150 outs() << " APP_EXTENSION_SAFE";
4151 f &= ~MachO::MH_APP_EXTENSION_SAFE;
4152 }
4153 if (f != 0 || flags == 0)
4154 outs() << format(" 0x%08" PRIx32, f);
4155 } else {
4156 outs() << format(" 0x%08" PRIx32, magic);
4157 outs() << format(" %7d", cputype);
4158 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4159 outs() << format(" 0x%02" PRIx32,
4160 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4161 outs() << format(" %10u", filetype);
4162 outs() << format(" %5u", ncmds);
4163 outs() << format(" %10u", sizeofcmds);
4164 outs() << format(" 0x%08" PRIx32, flags);
4165 }
4166 outs() << "\n";
4167}
4168
Kevin Enderby956366c2014-08-29 22:30:52 +00004169static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
4170 StringRef SegName, uint64_t vmaddr,
4171 uint64_t vmsize, uint64_t fileoff,
4172 uint64_t filesize, uint32_t maxprot,
4173 uint32_t initprot, uint32_t nsects,
4174 uint32_t flags, uint32_t object_size,
4175 bool verbose) {
4176 uint64_t expected_cmdsize;
4177 if (cmd == MachO::LC_SEGMENT) {
4178 outs() << " cmd LC_SEGMENT\n";
4179 expected_cmdsize = nsects;
4180 expected_cmdsize *= sizeof(struct MachO::section);
4181 expected_cmdsize += sizeof(struct MachO::segment_command);
4182 } else {
4183 outs() << " cmd LC_SEGMENT_64\n";
4184 expected_cmdsize = nsects;
4185 expected_cmdsize *= sizeof(struct MachO::section_64);
4186 expected_cmdsize += sizeof(struct MachO::segment_command_64);
4187 }
4188 outs() << " cmdsize " << cmdsize;
4189 if (cmdsize != expected_cmdsize)
4190 outs() << " Inconsistent size\n";
4191 else
4192 outs() << "\n";
4193 outs() << " segname " << SegName << "\n";
4194 if (cmd == MachO::LC_SEGMENT_64) {
4195 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
4196 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
4197 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00004198 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
4199 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00004200 }
4201 outs() << " fileoff " << fileoff;
4202 if (fileoff > object_size)
4203 outs() << " (past end of file)\n";
4204 else
4205 outs() << "\n";
4206 outs() << " filesize " << filesize;
4207 if (fileoff + filesize > object_size)
4208 outs() << " (past end of file)\n";
4209 else
4210 outs() << "\n";
4211 if (verbose) {
4212 if ((maxprot &
4213 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4214 MachO::VM_PROT_EXECUTE)) != 0)
4215 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
4216 else {
4217 if (maxprot & MachO::VM_PROT_READ)
4218 outs() << " maxprot r";
4219 else
4220 outs() << " maxprot -";
4221 if (maxprot & MachO::VM_PROT_WRITE)
4222 outs() << "w";
4223 else
4224 outs() << "-";
4225 if (maxprot & MachO::VM_PROT_EXECUTE)
4226 outs() << "x\n";
4227 else
4228 outs() << "-\n";
4229 }
4230 if ((initprot &
4231 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4232 MachO::VM_PROT_EXECUTE)) != 0)
4233 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
4234 else {
4235 if (initprot & MachO::VM_PROT_READ)
4236 outs() << " initprot r";
4237 else
4238 outs() << " initprot -";
4239 if (initprot & MachO::VM_PROT_WRITE)
4240 outs() << "w";
4241 else
4242 outs() << "-";
4243 if (initprot & MachO::VM_PROT_EXECUTE)
4244 outs() << "x\n";
4245 else
4246 outs() << "-\n";
4247 }
4248 } else {
4249 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
4250 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
4251 }
4252 outs() << " nsects " << nsects << "\n";
4253 if (verbose) {
4254 outs() << " flags";
4255 if (flags == 0)
4256 outs() << " (none)\n";
4257 else {
4258 if (flags & MachO::SG_HIGHVM) {
4259 outs() << " HIGHVM";
4260 flags &= ~MachO::SG_HIGHVM;
4261 }
4262 if (flags & MachO::SG_FVMLIB) {
4263 outs() << " FVMLIB";
4264 flags &= ~MachO::SG_FVMLIB;
4265 }
4266 if (flags & MachO::SG_NORELOC) {
4267 outs() << " NORELOC";
4268 flags &= ~MachO::SG_NORELOC;
4269 }
4270 if (flags & MachO::SG_PROTECTED_VERSION_1) {
4271 outs() << " PROTECTED_VERSION_1";
4272 flags &= ~MachO::SG_PROTECTED_VERSION_1;
4273 }
4274 if (flags)
4275 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
4276 else
4277 outs() << "\n";
4278 }
4279 } else {
4280 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
4281 }
4282}
4283
4284static void PrintSection(const char *sectname, const char *segname,
4285 uint64_t addr, uint64_t size, uint32_t offset,
4286 uint32_t align, uint32_t reloff, uint32_t nreloc,
4287 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
4288 uint32_t cmd, const char *sg_segname,
4289 uint32_t filetype, uint32_t object_size,
4290 bool verbose) {
4291 outs() << "Section\n";
4292 outs() << " sectname " << format("%.16s\n", sectname);
4293 outs() << " segname " << format("%.16s", segname);
4294 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
4295 outs() << " (does not match segment)\n";
4296 else
4297 outs() << "\n";
4298 if (cmd == MachO::LC_SEGMENT_64) {
4299 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
4300 outs() << " size " << format("0x%016" PRIx64, size);
4301 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00004302 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
4303 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00004304 }
4305 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4306 outs() << " (past end of file)\n";
4307 else
4308 outs() << "\n";
4309 outs() << " offset " << offset;
4310 if (offset > object_size)
4311 outs() << " (past end of file)\n";
4312 else
4313 outs() << "\n";
4314 uint32_t align_shifted = 1 << align;
4315 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
4316 outs() << " reloff " << reloff;
4317 if (reloff > object_size)
4318 outs() << " (past end of file)\n";
4319 else
4320 outs() << "\n";
4321 outs() << " nreloc " << nreloc;
4322 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4323 outs() << " (past end of file)\n";
4324 else
4325 outs() << "\n";
4326 uint32_t section_type = flags & MachO::SECTION_TYPE;
4327 if (verbose) {
4328 outs() << " type";
4329 if (section_type == MachO::S_REGULAR)
4330 outs() << " S_REGULAR\n";
4331 else if (section_type == MachO::S_ZEROFILL)
4332 outs() << " S_ZEROFILL\n";
4333 else if (section_type == MachO::S_CSTRING_LITERALS)
4334 outs() << " S_CSTRING_LITERALS\n";
4335 else if (section_type == MachO::S_4BYTE_LITERALS)
4336 outs() << " S_4BYTE_LITERALS\n";
4337 else if (section_type == MachO::S_8BYTE_LITERALS)
4338 outs() << " S_8BYTE_LITERALS\n";
4339 else if (section_type == MachO::S_16BYTE_LITERALS)
4340 outs() << " S_16BYTE_LITERALS\n";
4341 else if (section_type == MachO::S_LITERAL_POINTERS)
4342 outs() << " S_LITERAL_POINTERS\n";
4343 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4344 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4345 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4346 outs() << " S_LAZY_SYMBOL_POINTERS\n";
4347 else if (section_type == MachO::S_SYMBOL_STUBS)
4348 outs() << " S_SYMBOL_STUBS\n";
4349 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4350 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4351 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4352 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4353 else if (section_type == MachO::S_COALESCED)
4354 outs() << " S_COALESCED\n";
4355 else if (section_type == MachO::S_INTERPOSING)
4356 outs() << " S_INTERPOSING\n";
4357 else if (section_type == MachO::S_DTRACE_DOF)
4358 outs() << " S_DTRACE_DOF\n";
4359 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4360 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4361 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4362 outs() << " S_THREAD_LOCAL_REGULAR\n";
4363 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4364 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4365 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4366 outs() << " S_THREAD_LOCAL_VARIABLES\n";
4367 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4368 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4369 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4370 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4371 else
4372 outs() << format("0x%08" PRIx32, section_type) << "\n";
4373 outs() << "attributes";
4374 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4375 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4376 outs() << " PURE_INSTRUCTIONS";
4377 if (section_attributes & MachO::S_ATTR_NO_TOC)
4378 outs() << " NO_TOC";
4379 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4380 outs() << " STRIP_STATIC_SYMS";
4381 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4382 outs() << " NO_DEAD_STRIP";
4383 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4384 outs() << " LIVE_SUPPORT";
4385 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4386 outs() << " SELF_MODIFYING_CODE";
4387 if (section_attributes & MachO::S_ATTR_DEBUG)
4388 outs() << " DEBUG";
4389 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4390 outs() << " SOME_INSTRUCTIONS";
4391 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4392 outs() << " EXT_RELOC";
4393 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4394 outs() << " LOC_RELOC";
4395 if (section_attributes == 0)
4396 outs() << " (none)";
4397 outs() << "\n";
4398 } else
4399 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
4400 outs() << " reserved1 " << reserved1;
4401 if (section_type == MachO::S_SYMBOL_STUBS ||
4402 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4403 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4404 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4405 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4406 outs() << " (index into indirect symbol table)\n";
4407 else
4408 outs() << "\n";
4409 outs() << " reserved2 " << reserved2;
4410 if (section_type == MachO::S_SYMBOL_STUBS)
4411 outs() << " (size of stubs)\n";
4412 else
4413 outs() << "\n";
4414}
4415
David Majnemer73cc6ff2014-11-13 19:48:56 +00004416static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00004417 uint32_t object_size) {
4418 outs() << " cmd LC_SYMTAB\n";
4419 outs() << " cmdsize " << st.cmdsize;
4420 if (st.cmdsize != sizeof(struct MachO::symtab_command))
4421 outs() << " Incorrect size\n";
4422 else
4423 outs() << "\n";
4424 outs() << " symoff " << st.symoff;
4425 if (st.symoff > object_size)
4426 outs() << " (past end of file)\n";
4427 else
4428 outs() << "\n";
4429 outs() << " nsyms " << st.nsyms;
4430 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00004431 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00004432 big_size = st.nsyms;
4433 big_size *= sizeof(struct MachO::nlist_64);
4434 big_size += st.symoff;
4435 if (big_size > object_size)
4436 outs() << " (past end of file)\n";
4437 else
4438 outs() << "\n";
4439 } else {
4440 big_size = st.nsyms;
4441 big_size *= sizeof(struct MachO::nlist);
4442 big_size += st.symoff;
4443 if (big_size > object_size)
4444 outs() << " (past end of file)\n";
4445 else
4446 outs() << "\n";
4447 }
4448 outs() << " stroff " << st.stroff;
4449 if (st.stroff > object_size)
4450 outs() << " (past end of file)\n";
4451 else
4452 outs() << "\n";
4453 outs() << " strsize " << st.strsize;
4454 big_size = st.stroff;
4455 big_size += st.strsize;
4456 if (big_size > object_size)
4457 outs() << " (past end of file)\n";
4458 else
4459 outs() << "\n";
4460}
4461
4462static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4463 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00004464 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00004465 outs() << " cmd LC_DYSYMTAB\n";
4466 outs() << " cmdsize " << dyst.cmdsize;
4467 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4468 outs() << " Incorrect size\n";
4469 else
4470 outs() << "\n";
4471 outs() << " ilocalsym " << dyst.ilocalsym;
4472 if (dyst.ilocalsym > nsyms)
4473 outs() << " (greater than the number of symbols)\n";
4474 else
4475 outs() << "\n";
4476 outs() << " nlocalsym " << dyst.nlocalsym;
4477 uint64_t big_size;
4478 big_size = dyst.ilocalsym;
4479 big_size += dyst.nlocalsym;
4480 if (big_size > nsyms)
4481 outs() << " (past the end of the symbol table)\n";
4482 else
4483 outs() << "\n";
4484 outs() << " iextdefsym " << dyst.iextdefsym;
4485 if (dyst.iextdefsym > nsyms)
4486 outs() << " (greater than the number of symbols)\n";
4487 else
4488 outs() << "\n";
4489 outs() << " nextdefsym " << dyst.nextdefsym;
4490 big_size = dyst.iextdefsym;
4491 big_size += dyst.nextdefsym;
4492 if (big_size > nsyms)
4493 outs() << " (past the end of the symbol table)\n";
4494 else
4495 outs() << "\n";
4496 outs() << " iundefsym " << dyst.iundefsym;
4497 if (dyst.iundefsym > nsyms)
4498 outs() << " (greater than the number of symbols)\n";
4499 else
4500 outs() << "\n";
4501 outs() << " nundefsym " << dyst.nundefsym;
4502 big_size = dyst.iundefsym;
4503 big_size += dyst.nundefsym;
4504 if (big_size > nsyms)
4505 outs() << " (past the end of the symbol table)\n";
4506 else
4507 outs() << "\n";
4508 outs() << " tocoff " << dyst.tocoff;
4509 if (dyst.tocoff > object_size)
4510 outs() << " (past end of file)\n";
4511 else
4512 outs() << "\n";
4513 outs() << " ntoc " << dyst.ntoc;
4514 big_size = dyst.ntoc;
4515 big_size *= sizeof(struct MachO::dylib_table_of_contents);
4516 big_size += dyst.tocoff;
4517 if (big_size > object_size)
4518 outs() << " (past end of file)\n";
4519 else
4520 outs() << "\n";
4521 outs() << " modtaboff " << dyst.modtaboff;
4522 if (dyst.modtaboff > object_size)
4523 outs() << " (past end of file)\n";
4524 else
4525 outs() << "\n";
4526 outs() << " nmodtab " << dyst.nmodtab;
4527 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00004528 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00004529 modtabend = dyst.nmodtab;
4530 modtabend *= sizeof(struct MachO::dylib_module_64);
4531 modtabend += dyst.modtaboff;
4532 } else {
4533 modtabend = dyst.nmodtab;
4534 modtabend *= sizeof(struct MachO::dylib_module);
4535 modtabend += dyst.modtaboff;
4536 }
4537 if (modtabend > object_size)
4538 outs() << " (past end of file)\n";
4539 else
4540 outs() << "\n";
4541 outs() << " extrefsymoff " << dyst.extrefsymoff;
4542 if (dyst.extrefsymoff > object_size)
4543 outs() << " (past end of file)\n";
4544 else
4545 outs() << "\n";
4546 outs() << " nextrefsyms " << dyst.nextrefsyms;
4547 big_size = dyst.nextrefsyms;
4548 big_size *= sizeof(struct MachO::dylib_reference);
4549 big_size += dyst.extrefsymoff;
4550 if (big_size > object_size)
4551 outs() << " (past end of file)\n";
4552 else
4553 outs() << "\n";
4554 outs() << " indirectsymoff " << dyst.indirectsymoff;
4555 if (dyst.indirectsymoff > object_size)
4556 outs() << " (past end of file)\n";
4557 else
4558 outs() << "\n";
4559 outs() << " nindirectsyms " << dyst.nindirectsyms;
4560 big_size = dyst.nindirectsyms;
4561 big_size *= sizeof(uint32_t);
4562 big_size += dyst.indirectsymoff;
4563 if (big_size > object_size)
4564 outs() << " (past end of file)\n";
4565 else
4566 outs() << "\n";
4567 outs() << " extreloff " << dyst.extreloff;
4568 if (dyst.extreloff > object_size)
4569 outs() << " (past end of file)\n";
4570 else
4571 outs() << "\n";
4572 outs() << " nextrel " << dyst.nextrel;
4573 big_size = dyst.nextrel;
4574 big_size *= sizeof(struct MachO::relocation_info);
4575 big_size += dyst.extreloff;
4576 if (big_size > object_size)
4577 outs() << " (past end of file)\n";
4578 else
4579 outs() << "\n";
4580 outs() << " locreloff " << dyst.locreloff;
4581 if (dyst.locreloff > object_size)
4582 outs() << " (past end of file)\n";
4583 else
4584 outs() << "\n";
4585 outs() << " nlocrel " << dyst.nlocrel;
4586 big_size = dyst.nlocrel;
4587 big_size *= sizeof(struct MachO::relocation_info);
4588 big_size += dyst.locreloff;
4589 if (big_size > object_size)
4590 outs() << " (past end of file)\n";
4591 else
4592 outs() << "\n";
4593}
4594
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004595static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4596 uint32_t object_size) {
4597 if (dc.cmd == MachO::LC_DYLD_INFO)
4598 outs() << " cmd LC_DYLD_INFO\n";
4599 else
4600 outs() << " cmd LC_DYLD_INFO_ONLY\n";
4601 outs() << " cmdsize " << dc.cmdsize;
4602 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4603 outs() << " Incorrect size\n";
4604 else
4605 outs() << "\n";
4606 outs() << " rebase_off " << dc.rebase_off;
4607 if (dc.rebase_off > object_size)
4608 outs() << " (past end of file)\n";
4609 else
4610 outs() << "\n";
4611 outs() << " rebase_size " << dc.rebase_size;
4612 uint64_t big_size;
4613 big_size = dc.rebase_off;
4614 big_size += dc.rebase_size;
4615 if (big_size > object_size)
4616 outs() << " (past end of file)\n";
4617 else
4618 outs() << "\n";
4619 outs() << " bind_off " << dc.bind_off;
4620 if (dc.bind_off > object_size)
4621 outs() << " (past end of file)\n";
4622 else
4623 outs() << "\n";
4624 outs() << " bind_size " << dc.bind_size;
4625 big_size = dc.bind_off;
4626 big_size += dc.bind_size;
4627 if (big_size > object_size)
4628 outs() << " (past end of file)\n";
4629 else
4630 outs() << "\n";
4631 outs() << " weak_bind_off " << dc.weak_bind_off;
4632 if (dc.weak_bind_off > object_size)
4633 outs() << " (past end of file)\n";
4634 else
4635 outs() << "\n";
4636 outs() << " weak_bind_size " << dc.weak_bind_size;
4637 big_size = dc.weak_bind_off;
4638 big_size += dc.weak_bind_size;
4639 if (big_size > object_size)
4640 outs() << " (past end of file)\n";
4641 else
4642 outs() << "\n";
4643 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4644 if (dc.lazy_bind_off > object_size)
4645 outs() << " (past end of file)\n";
4646 else
4647 outs() << "\n";
4648 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4649 big_size = dc.lazy_bind_off;
4650 big_size += dc.lazy_bind_size;
4651 if (big_size > object_size)
4652 outs() << " (past end of file)\n";
4653 else
4654 outs() << "\n";
4655 outs() << " export_off " << dc.export_off;
4656 if (dc.export_off > object_size)
4657 outs() << " (past end of file)\n";
4658 else
4659 outs() << "\n";
4660 outs() << " export_size " << dc.export_size;
4661 big_size = dc.export_off;
4662 big_size += dc.export_size;
4663 if (big_size > object_size)
4664 outs() << " (past end of file)\n";
4665 else
4666 outs() << "\n";
4667}
4668
4669static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4670 const char *Ptr) {
4671 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4672 outs() << " cmd LC_ID_DYLINKER\n";
4673 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4674 outs() << " cmd LC_LOAD_DYLINKER\n";
4675 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4676 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4677 else
4678 outs() << " cmd ?(" << dyld.cmd << ")\n";
4679 outs() << " cmdsize " << dyld.cmdsize;
4680 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4681 outs() << " Incorrect size\n";
4682 else
4683 outs() << "\n";
4684 if (dyld.name >= dyld.cmdsize)
4685 outs() << " name ?(bad offset " << dyld.name << ")\n";
4686 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004687 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004688 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4689 }
4690}
4691
4692static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4693 outs() << " cmd LC_UUID\n";
4694 outs() << " cmdsize " << uuid.cmdsize;
4695 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4696 outs() << " Incorrect size\n";
4697 else
4698 outs() << "\n";
4699 outs() << " uuid ";
4700 outs() << format("%02" PRIX32, uuid.uuid[0]);
4701 outs() << format("%02" PRIX32, uuid.uuid[1]);
4702 outs() << format("%02" PRIX32, uuid.uuid[2]);
4703 outs() << format("%02" PRIX32, uuid.uuid[3]);
4704 outs() << "-";
4705 outs() << format("%02" PRIX32, uuid.uuid[4]);
4706 outs() << format("%02" PRIX32, uuid.uuid[5]);
4707 outs() << "-";
4708 outs() << format("%02" PRIX32, uuid.uuid[6]);
4709 outs() << format("%02" PRIX32, uuid.uuid[7]);
4710 outs() << "-";
4711 outs() << format("%02" PRIX32, uuid.uuid[8]);
4712 outs() << format("%02" PRIX32, uuid.uuid[9]);
4713 outs() << "-";
4714 outs() << format("%02" PRIX32, uuid.uuid[10]);
4715 outs() << format("%02" PRIX32, uuid.uuid[11]);
4716 outs() << format("%02" PRIX32, uuid.uuid[12]);
4717 outs() << format("%02" PRIX32, uuid.uuid[13]);
4718 outs() << format("%02" PRIX32, uuid.uuid[14]);
4719 outs() << format("%02" PRIX32, uuid.uuid[15]);
4720 outs() << "\n";
4721}
4722
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004723static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00004724 outs() << " cmd LC_RPATH\n";
4725 outs() << " cmdsize " << rpath.cmdsize;
4726 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4727 outs() << " Incorrect size\n";
4728 else
4729 outs() << "\n";
4730 if (rpath.path >= rpath.cmdsize)
4731 outs() << " path ?(bad offset " << rpath.path << ")\n";
4732 else {
4733 const char *P = (const char *)(Ptr) + rpath.path;
4734 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4735 }
4736}
4737
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004738static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4739 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4740 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4741 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4742 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4743 else
4744 outs() << " cmd " << vd.cmd << " (?)\n";
4745 outs() << " cmdsize " << vd.cmdsize;
4746 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4747 outs() << " Incorrect size\n";
4748 else
4749 outs() << "\n";
4750 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4751 << ((vd.version >> 8) & 0xff);
4752 if ((vd.version & 0xff) != 0)
4753 outs() << "." << (vd.version & 0xff);
4754 outs() << "\n";
4755 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00004756 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004757 else {
4758 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4759 << ((vd.sdk >> 8) & 0xff);
4760 }
4761 if ((vd.sdk & 0xff) != 0)
4762 outs() << "." << (vd.sdk & 0xff);
4763 outs() << "\n";
4764}
4765
4766static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4767 outs() << " cmd LC_SOURCE_VERSION\n";
4768 outs() << " cmdsize " << sd.cmdsize;
4769 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4770 outs() << " Incorrect size\n";
4771 else
4772 outs() << "\n";
4773 uint64_t a = (sd.version >> 40) & 0xffffff;
4774 uint64_t b = (sd.version >> 30) & 0x3ff;
4775 uint64_t c = (sd.version >> 20) & 0x3ff;
4776 uint64_t d = (sd.version >> 10) & 0x3ff;
4777 uint64_t e = sd.version & 0x3ff;
4778 outs() << " version " << a << "." << b;
4779 if (e != 0)
4780 outs() << "." << c << "." << d << "." << e;
4781 else if (d != 0)
4782 outs() << "." << c << "." << d;
4783 else if (c != 0)
4784 outs() << "." << c;
4785 outs() << "\n";
4786}
4787
4788static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4789 outs() << " cmd LC_MAIN\n";
4790 outs() << " cmdsize " << ep.cmdsize;
4791 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4792 outs() << " Incorrect size\n";
4793 else
4794 outs() << "\n";
4795 outs() << " entryoff " << ep.entryoff << "\n";
4796 outs() << " stacksize " << ep.stacksize << "\n";
4797}
4798
Kevin Enderby0804f4672014-12-16 23:25:52 +00004799static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4800 uint32_t object_size) {
4801 outs() << " cmd LC_ENCRYPTION_INFO\n";
4802 outs() << " cmdsize " << ec.cmdsize;
4803 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4804 outs() << " Incorrect size\n";
4805 else
4806 outs() << "\n";
4807 outs() << " cryptoff " << ec.cryptoff;
4808 if (ec.cryptoff > object_size)
4809 outs() << " (past end of file)\n";
4810 else
4811 outs() << "\n";
4812 outs() << " cryptsize " << ec.cryptsize;
4813 if (ec.cryptsize > object_size)
4814 outs() << " (past end of file)\n";
4815 else
4816 outs() << "\n";
4817 outs() << " cryptid " << ec.cryptid << "\n";
4818}
4819
Kevin Enderby57538292014-12-17 01:01:30 +00004820static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004821 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00004822 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4823 outs() << " cmdsize " << ec.cmdsize;
4824 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4825 outs() << " Incorrect size\n";
4826 else
4827 outs() << "\n";
4828 outs() << " cryptoff " << ec.cryptoff;
4829 if (ec.cryptoff > object_size)
4830 outs() << " (past end of file)\n";
4831 else
4832 outs() << "\n";
4833 outs() << " cryptsize " << ec.cryptsize;
4834 if (ec.cryptsize > object_size)
4835 outs() << " (past end of file)\n";
4836 else
4837 outs() << "\n";
4838 outs() << " cryptid " << ec.cryptid << "\n";
4839 outs() << " pad " << ec.pad << "\n";
4840}
4841
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004842static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4843 const char *Ptr) {
4844 outs() << " cmd LC_LINKER_OPTION\n";
4845 outs() << " cmdsize " << lo.cmdsize;
4846 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4847 outs() << " Incorrect size\n";
4848 else
4849 outs() << "\n";
4850 outs() << " count " << lo.count << "\n";
4851 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4852 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4853 uint32_t i = 0;
4854 while (left > 0) {
4855 while (*string == '\0' && left > 0) {
4856 string++;
4857 left--;
4858 }
4859 if (left > 0) {
4860 i++;
4861 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00004862 uint32_t NullPos = StringRef(string, left).find('\0');
4863 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004864 string += len;
4865 left -= len;
4866 }
4867 }
4868 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004869 outs() << " count " << lo.count << " does not match number of strings "
4870 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004871}
4872
Kevin Enderbyb4b79312014-12-18 19:24:35 +00004873static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4874 const char *Ptr) {
4875 outs() << " cmd LC_SUB_FRAMEWORK\n";
4876 outs() << " cmdsize " << sub.cmdsize;
4877 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4878 outs() << " Incorrect size\n";
4879 else
4880 outs() << "\n";
4881 if (sub.umbrella < sub.cmdsize) {
4882 const char *P = Ptr + sub.umbrella;
4883 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4884 } else {
4885 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4886 }
4887}
4888
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00004889static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4890 const char *Ptr) {
4891 outs() << " cmd LC_SUB_UMBRELLA\n";
4892 outs() << " cmdsize " << sub.cmdsize;
4893 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4894 outs() << " Incorrect size\n";
4895 else
4896 outs() << "\n";
4897 if (sub.sub_umbrella < sub.cmdsize) {
4898 const char *P = Ptr + sub.sub_umbrella;
4899 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4900 } else {
4901 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4902 }
4903}
4904
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004905static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004906 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004907 outs() << " cmd LC_SUB_LIBRARY\n";
4908 outs() << " cmdsize " << sub.cmdsize;
4909 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4910 outs() << " Incorrect size\n";
4911 else
4912 outs() << "\n";
4913 if (sub.sub_library < sub.cmdsize) {
4914 const char *P = Ptr + sub.sub_library;
4915 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4916 } else {
4917 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4918 }
4919}
4920
Kevin Enderby186eac32014-12-19 21:06:24 +00004921static void PrintSubClientCommand(MachO::sub_client_command sub,
4922 const char *Ptr) {
4923 outs() << " cmd LC_SUB_CLIENT\n";
4924 outs() << " cmdsize " << sub.cmdsize;
4925 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4926 outs() << " Incorrect size\n";
4927 else
4928 outs() << "\n";
4929 if (sub.client < sub.cmdsize) {
4930 const char *P = Ptr + sub.client;
4931 outs() << " client " << P << " (offset " << sub.client << ")\n";
4932 } else {
4933 outs() << " client ?(bad offset " << sub.client << ")\n";
4934 }
4935}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004936
Kevin Enderby52e4ce42014-12-19 22:25:22 +00004937static void PrintRoutinesCommand(MachO::routines_command r) {
4938 outs() << " cmd LC_ROUTINES\n";
4939 outs() << " cmdsize " << r.cmdsize;
4940 if (r.cmdsize != sizeof(struct MachO::routines_command))
4941 outs() << " Incorrect size\n";
4942 else
4943 outs() << "\n";
4944 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4945 outs() << " init_module " << r.init_module << "\n";
4946 outs() << " reserved1 " << r.reserved1 << "\n";
4947 outs() << " reserved2 " << r.reserved2 << "\n";
4948 outs() << " reserved3 " << r.reserved3 << "\n";
4949 outs() << " reserved4 " << r.reserved4 << "\n";
4950 outs() << " reserved5 " << r.reserved5 << "\n";
4951 outs() << " reserved6 " << r.reserved6 << "\n";
4952}
4953
4954static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4955 outs() << " cmd LC_ROUTINES_64\n";
4956 outs() << " cmdsize " << r.cmdsize;
4957 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4958 outs() << " Incorrect size\n";
4959 else
4960 outs() << "\n";
4961 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4962 outs() << " init_module " << r.init_module << "\n";
4963 outs() << " reserved1 " << r.reserved1 << "\n";
4964 outs() << " reserved2 " << r.reserved2 << "\n";
4965 outs() << " reserved3 " << r.reserved3 << "\n";
4966 outs() << " reserved4 " << r.reserved4 << "\n";
4967 outs() << " reserved5 " << r.reserved5 << "\n";
4968 outs() << " reserved6 " << r.reserved6 << "\n";
4969}
4970
Kevin Enderby48ef5342014-12-23 22:56:39 +00004971static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4972 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4973 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4974 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4975 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4976 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4977 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4978 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4979 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4980 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4981 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4982 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4983 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4984 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4985 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4986 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4987 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4988 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4989 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4990 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4991 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4992 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4993}
4994
Kevin Enderby227df342014-12-23 23:43:59 +00004995static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004996 uint32_t f;
4997 outs() << "\t mmst_reg ";
4998 for (f = 0; f < 10; f++)
4999 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
5000 outs() << "\n";
5001 outs() << "\t mmst_rsrv ";
5002 for (f = 0; f < 6; f++)
5003 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
5004 outs() << "\n";
5005}
5006
Kevin Enderbyaefb0032014-12-24 00:16:51 +00005007static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005008 uint32_t f;
5009 outs() << "\t xmm_reg ";
5010 for (f = 0; f < 16; f++)
5011 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
5012 outs() << "\n";
5013}
5014
5015static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
5016 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
5017 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
5018 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
5019 outs() << " denorm " << fpu.fpu_fcw.denorm;
5020 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
5021 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
5022 outs() << " undfl " << fpu.fpu_fcw.undfl;
5023 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
5024 outs() << "\t\t pc ";
5025 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
5026 outs() << "FP_PREC_24B ";
5027 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
5028 outs() << "FP_PREC_53B ";
5029 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
5030 outs() << "FP_PREC_64B ";
5031 else
5032 outs() << fpu.fpu_fcw.pc << " ";
5033 outs() << "rc ";
5034 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
5035 outs() << "FP_RND_NEAR ";
5036 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
5037 outs() << "FP_RND_DOWN ";
5038 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
5039 outs() << "FP_RND_UP ";
5040 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005041 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005042 outs() << "\n";
5043 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
5044 outs() << " denorm " << fpu.fpu_fsw.denorm;
5045 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
5046 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
5047 outs() << " undfl " << fpu.fpu_fsw.undfl;
5048 outs() << " precis " << fpu.fpu_fsw.precis;
5049 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
5050 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
5051 outs() << " c0 " << fpu.fpu_fsw.c0;
5052 outs() << " c1 " << fpu.fpu_fsw.c1;
5053 outs() << " c2 " << fpu.fpu_fsw.c2;
5054 outs() << " tos " << fpu.fpu_fsw.tos;
5055 outs() << " c3 " << fpu.fpu_fsw.c3;
5056 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
5057 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
5058 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
5059 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
5060 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
5061 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
5062 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
5063 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
5064 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
5065 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
5066 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
5067 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
5068 outs() << "\n";
5069 outs() << "\t fpu_stmm0:\n";
5070 Print_mmst_reg(fpu.fpu_stmm0);
5071 outs() << "\t fpu_stmm1:\n";
5072 Print_mmst_reg(fpu.fpu_stmm1);
5073 outs() << "\t fpu_stmm2:\n";
5074 Print_mmst_reg(fpu.fpu_stmm2);
5075 outs() << "\t fpu_stmm3:\n";
5076 Print_mmst_reg(fpu.fpu_stmm3);
5077 outs() << "\t fpu_stmm4:\n";
5078 Print_mmst_reg(fpu.fpu_stmm4);
5079 outs() << "\t fpu_stmm5:\n";
5080 Print_mmst_reg(fpu.fpu_stmm5);
5081 outs() << "\t fpu_stmm6:\n";
5082 Print_mmst_reg(fpu.fpu_stmm6);
5083 outs() << "\t fpu_stmm7:\n";
5084 Print_mmst_reg(fpu.fpu_stmm7);
5085 outs() << "\t fpu_xmm0:\n";
5086 Print_xmm_reg(fpu.fpu_xmm0);
5087 outs() << "\t fpu_xmm1:\n";
5088 Print_xmm_reg(fpu.fpu_xmm1);
5089 outs() << "\t fpu_xmm2:\n";
5090 Print_xmm_reg(fpu.fpu_xmm2);
5091 outs() << "\t fpu_xmm3:\n";
5092 Print_xmm_reg(fpu.fpu_xmm3);
5093 outs() << "\t fpu_xmm4:\n";
5094 Print_xmm_reg(fpu.fpu_xmm4);
5095 outs() << "\t fpu_xmm5:\n";
5096 Print_xmm_reg(fpu.fpu_xmm5);
5097 outs() << "\t fpu_xmm6:\n";
5098 Print_xmm_reg(fpu.fpu_xmm6);
5099 outs() << "\t fpu_xmm7:\n";
5100 Print_xmm_reg(fpu.fpu_xmm7);
5101 outs() << "\t fpu_xmm8:\n";
5102 Print_xmm_reg(fpu.fpu_xmm8);
5103 outs() << "\t fpu_xmm9:\n";
5104 Print_xmm_reg(fpu.fpu_xmm9);
5105 outs() << "\t fpu_xmm10:\n";
5106 Print_xmm_reg(fpu.fpu_xmm10);
5107 outs() << "\t fpu_xmm11:\n";
5108 Print_xmm_reg(fpu.fpu_xmm11);
5109 outs() << "\t fpu_xmm12:\n";
5110 Print_xmm_reg(fpu.fpu_xmm12);
5111 outs() << "\t fpu_xmm13:\n";
5112 Print_xmm_reg(fpu.fpu_xmm13);
5113 outs() << "\t fpu_xmm14:\n";
5114 Print_xmm_reg(fpu.fpu_xmm14);
5115 outs() << "\t fpu_xmm15:\n";
5116 Print_xmm_reg(fpu.fpu_xmm15);
5117 outs() << "\t fpu_rsrv4:\n";
5118 for (uint32_t f = 0; f < 6; f++) {
5119 outs() << "\t ";
5120 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005121 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005122 outs() << "\n";
5123 }
5124 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
5125 outs() << "\n";
5126}
5127
5128static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
5129 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
5130 outs() << " err " << format("0x%08" PRIx32, exc64.err);
5131 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
5132}
5133
5134static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
5135 bool isLittleEndian, uint32_t cputype) {
5136 if (t.cmd == MachO::LC_THREAD)
5137 outs() << " cmd LC_THREAD\n";
5138 else if (t.cmd == MachO::LC_UNIXTHREAD)
5139 outs() << " cmd LC_UNIXTHREAD\n";
5140 else
5141 outs() << " cmd " << t.cmd << " (unknown)\n";
5142 outs() << " cmdsize " << t.cmdsize;
5143 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
5144 outs() << " Incorrect size\n";
5145 else
5146 outs() << "\n";
5147
5148 const char *begin = Ptr + sizeof(struct MachO::thread_command);
5149 const char *end = Ptr + t.cmdsize;
5150 uint32_t flavor, count, left;
5151 if (cputype == MachO::CPU_TYPE_X86_64) {
5152 while (begin < end) {
5153 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5154 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5155 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005156 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005157 flavor = 0;
5158 begin = end;
5159 }
5160 if (isLittleEndian != sys::IsLittleEndianHost)
5161 sys::swapByteOrder(flavor);
5162 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5163 memcpy((char *)&count, begin, sizeof(uint32_t));
5164 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005165 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005166 count = 0;
5167 begin = end;
5168 }
5169 if (isLittleEndian != sys::IsLittleEndianHost)
5170 sys::swapByteOrder(count);
5171 if (flavor == MachO::x86_THREAD_STATE64) {
5172 outs() << " flavor x86_THREAD_STATE64\n";
5173 if (count == MachO::x86_THREAD_STATE64_COUNT)
5174 outs() << " count x86_THREAD_STATE64_COUNT\n";
5175 else
5176 outs() << " count " << count
5177 << " (not x86_THREAD_STATE64_COUNT)\n";
5178 MachO::x86_thread_state64_t cpu64;
5179 left = end - begin;
5180 if (left >= sizeof(MachO::x86_thread_state64_t)) {
5181 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
5182 begin += sizeof(MachO::x86_thread_state64_t);
5183 } else {
5184 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
5185 memcpy(&cpu64, begin, left);
5186 begin += left;
5187 }
5188 if (isLittleEndian != sys::IsLittleEndianHost)
5189 swapStruct(cpu64);
5190 Print_x86_thread_state64_t(cpu64);
5191 } else if (flavor == MachO::x86_THREAD_STATE) {
5192 outs() << " flavor x86_THREAD_STATE\n";
5193 if (count == MachO::x86_THREAD_STATE_COUNT)
5194 outs() << " count x86_THREAD_STATE_COUNT\n";
5195 else
5196 outs() << " count " << count
5197 << " (not x86_THREAD_STATE_COUNT)\n";
5198 struct MachO::x86_thread_state_t ts;
5199 left = end - begin;
5200 if (left >= sizeof(MachO::x86_thread_state_t)) {
5201 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
5202 begin += sizeof(MachO::x86_thread_state_t);
5203 } else {
5204 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
5205 memcpy(&ts, begin, left);
5206 begin += left;
5207 }
5208 if (isLittleEndian != sys::IsLittleEndianHost)
5209 swapStruct(ts);
5210 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
5211 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
5212 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
5213 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
5214 else
5215 outs() << "tsh.count " << ts.tsh.count
5216 << " (not x86_THREAD_STATE64_COUNT\n";
5217 Print_x86_thread_state64_t(ts.uts.ts64);
5218 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005219 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
5220 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005221 }
5222 } else if (flavor == MachO::x86_FLOAT_STATE) {
5223 outs() << " flavor x86_FLOAT_STATE\n";
5224 if (count == MachO::x86_FLOAT_STATE_COUNT)
5225 outs() << " count x86_FLOAT_STATE_COUNT\n";
5226 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005227 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005228 struct MachO::x86_float_state_t fs;
5229 left = end - begin;
5230 if (left >= sizeof(MachO::x86_float_state_t)) {
5231 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
5232 begin += sizeof(MachO::x86_float_state_t);
5233 } else {
5234 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
5235 memcpy(&fs, begin, left);
5236 begin += left;
5237 }
5238 if (isLittleEndian != sys::IsLittleEndianHost)
5239 swapStruct(fs);
5240 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
5241 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005242 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00005243 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
5244 else
5245 outs() << "fsh.count " << fs.fsh.count
5246 << " (not x86_FLOAT_STATE64_COUNT\n";
5247 Print_x86_float_state_t(fs.ufs.fs64);
5248 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005249 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
5250 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005251 }
5252 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
5253 outs() << " flavor x86_EXCEPTION_STATE\n";
5254 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
5255 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
5256 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005257 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00005258 << " (not x86_EXCEPTION_STATE_COUNT)\n";
5259 struct MachO::x86_exception_state_t es;
5260 left = end - begin;
5261 if (left >= sizeof(MachO::x86_exception_state_t)) {
5262 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
5263 begin += sizeof(MachO::x86_exception_state_t);
5264 } else {
5265 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
5266 memcpy(&es, begin, left);
5267 begin += left;
5268 }
5269 if (isLittleEndian != sys::IsLittleEndianHost)
5270 swapStruct(es);
5271 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
5272 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005273 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00005274 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
5275 else
5276 outs() << "\t esh.count " << es.esh.count
5277 << " (not x86_EXCEPTION_STATE64_COUNT\n";
5278 Print_x86_exception_state_t(es.ues.es64);
5279 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005280 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
5281 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005282 }
5283 } else {
5284 outs() << " flavor " << flavor << " (unknown)\n";
5285 outs() << " count " << count << "\n";
5286 outs() << " state (unknown)\n";
5287 begin += count * sizeof(uint32_t);
5288 }
5289 }
5290 } else {
5291 while (begin < end) {
5292 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5293 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5294 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005295 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005296 flavor = 0;
5297 begin = end;
5298 }
5299 if (isLittleEndian != sys::IsLittleEndianHost)
5300 sys::swapByteOrder(flavor);
5301 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5302 memcpy((char *)&count, begin, sizeof(uint32_t));
5303 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005304 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005305 count = 0;
5306 begin = end;
5307 }
5308 if (isLittleEndian != sys::IsLittleEndianHost)
5309 sys::swapByteOrder(count);
5310 outs() << " flavor " << flavor << "\n";
5311 outs() << " count " << count << "\n";
5312 outs() << " state (Unknown cputype/cpusubtype)\n";
5313 begin += count * sizeof(uint32_t);
5314 }
5315 }
5316}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005317
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005318static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5319 if (dl.cmd == MachO::LC_ID_DYLIB)
5320 outs() << " cmd LC_ID_DYLIB\n";
5321 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5322 outs() << " cmd LC_LOAD_DYLIB\n";
5323 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5324 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
5325 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5326 outs() << " cmd LC_REEXPORT_DYLIB\n";
5327 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5328 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
5329 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5330 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
5331 else
5332 outs() << " cmd " << dl.cmd << " (unknown)\n";
5333 outs() << " cmdsize " << dl.cmdsize;
5334 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5335 outs() << " Incorrect size\n";
5336 else
5337 outs() << "\n";
5338 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005339 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005340 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
5341 } else {
5342 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
5343 }
5344 outs() << " time stamp " << dl.dylib.timestamp << " ";
5345 time_t t = dl.dylib.timestamp;
5346 outs() << ctime(&t);
5347 outs() << " current version ";
5348 if (dl.dylib.current_version == 0xffffffff)
5349 outs() << "n/a\n";
5350 else
5351 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5352 << ((dl.dylib.current_version >> 8) & 0xff) << "."
5353 << (dl.dylib.current_version & 0xff) << "\n";
5354 outs() << "compatibility version ";
5355 if (dl.dylib.compatibility_version == 0xffffffff)
5356 outs() << "n/a\n";
5357 else
5358 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5359 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5360 << (dl.dylib.compatibility_version & 0xff) << "\n";
5361}
5362
5363static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5364 uint32_t object_size) {
5365 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5366 outs() << " cmd LC_FUNCTION_STARTS\n";
5367 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5368 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
5369 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5370 outs() << " cmd LC_FUNCTION_STARTS\n";
5371 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5372 outs() << " cmd LC_DATA_IN_CODE\n";
5373 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5374 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
5375 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5376 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
5377 else
5378 outs() << " cmd " << ld.cmd << " (?)\n";
5379 outs() << " cmdsize " << ld.cmdsize;
5380 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5381 outs() << " Incorrect size\n";
5382 else
5383 outs() << "\n";
5384 outs() << " dataoff " << ld.dataoff;
5385 if (ld.dataoff > object_size)
5386 outs() << " (past end of file)\n";
5387 else
5388 outs() << "\n";
5389 outs() << " datasize " << ld.datasize;
5390 uint64_t big_size = ld.dataoff;
5391 big_size += ld.datasize;
5392 if (big_size > object_size)
5393 outs() << " (past end of file)\n";
5394 else
5395 outs() << "\n";
5396}
5397
Kevin Enderby956366c2014-08-29 22:30:52 +00005398static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5399 uint32_t filetype, uint32_t cputype,
5400 bool verbose) {
Filipe Cabecinhase71bd0c2015-01-06 17:08:26 +00005401 if (ncmds == 0)
5402 return;
Kevin Enderby956366c2014-08-29 22:30:52 +00005403 StringRef Buf = Obj->getData();
5404 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5405 for (unsigned i = 0;; ++i) {
5406 outs() << "Load command " << i << "\n";
5407 if (Command.C.cmd == MachO::LC_SEGMENT) {
5408 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5409 const char *sg_segname = SLC.segname;
5410 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5411 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5412 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5413 verbose);
5414 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00005415 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00005416 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5417 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5418 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5419 }
5420 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5421 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5422 const char *sg_segname = SLC_64.segname;
5423 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5424 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5425 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5426 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5427 for (unsigned j = 0; j < SLC_64.nsects; j++) {
5428 MachO::section_64 S_64 = Obj->getSection64(Command, j);
5429 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5430 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5431 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5432 sg_segname, filetype, Buf.size(), verbose);
5433 }
5434 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5435 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00005436 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00005437 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5438 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5439 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00005440 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5441 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005442 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5443 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5444 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5445 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5446 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5447 Command.C.cmd == MachO::LC_ID_DYLINKER ||
5448 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5449 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5450 PrintDyldLoadCommand(Dyld, Command.Ptr);
5451 } else if (Command.C.cmd == MachO::LC_UUID) {
5452 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5453 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00005454 } else if (Command.C.cmd == MachO::LC_RPATH) {
5455 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5456 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00005457 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5458 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005459 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5460 PrintVersionMinLoadCommand(Vd);
5461 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5462 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5463 PrintSourceVersionCommand(Sd);
5464 } else if (Command.C.cmd == MachO::LC_MAIN) {
5465 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5466 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00005467 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005468 MachO::encryption_info_command Ei =
5469 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00005470 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00005471 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005472 MachO::encryption_info_command_64 Ei =
5473 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00005474 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00005475 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005476 MachO::linker_option_command Lo =
5477 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00005478 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00005479 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5480 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5481 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00005482 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5483 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5484 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00005485 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5486 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5487 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00005488 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5489 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5490 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00005491 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5492 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5493 PrintRoutinesCommand(Rc);
5494 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5495 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5496 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00005497 } else if (Command.C.cmd == MachO::LC_THREAD ||
5498 Command.C.cmd == MachO::LC_UNIXTHREAD) {
5499 MachO::thread_command Tc = Obj->getThreadCommand(Command);
5500 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00005501 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5502 Command.C.cmd == MachO::LC_ID_DYLIB ||
5503 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5504 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5505 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5506 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005507 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5508 PrintDylibCommand(Dl, Command.Ptr);
5509 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5510 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5511 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5512 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5513 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5514 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5515 MachO::linkedit_data_command Ld =
5516 Obj->getLinkeditDataLoadCommand(Command);
5517 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00005518 } else {
5519 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5520 << ")\n";
5521 outs() << " cmdsize " << Command.C.cmdsize << "\n";
5522 // TODO: get and print the raw bytes of the load command.
5523 }
5524 // TODO: print all the other kinds of load commands.
5525 if (i == ncmds - 1)
5526 break;
5527 else
5528 Command = Obj->getNextLoadCommandInfo(Command);
5529 }
5530}
5531
5532static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5533 uint32_t &filetype, uint32_t &cputype,
5534 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005535 if (Obj->is64Bit()) {
5536 MachO::mach_header_64 H_64;
5537 H_64 = Obj->getHeader64();
5538 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5539 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00005540 ncmds = H_64.ncmds;
5541 filetype = H_64.filetype;
5542 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005543 } else {
5544 MachO::mach_header H;
5545 H = Obj->getHeader();
5546 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5547 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00005548 ncmds = H.ncmds;
5549 filetype = H.filetype;
5550 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005551 }
5552}
5553
5554void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5555 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00005556 uint32_t ncmds = 0;
5557 uint32_t filetype = 0;
5558 uint32_t cputype = 0;
Kevin Enderbyf0640752015-03-13 17:56:32 +00005559 getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
5560 PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005561}
Nick Kledzikd04bc352014-08-30 00:20:14 +00005562
5563//===----------------------------------------------------------------------===//
5564// export trie dumping
5565//===----------------------------------------------------------------------===//
5566
5567void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005568 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5569 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00005570 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5571 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5572 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5573 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5574 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5575 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5576 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5577 if (ReExport)
5578 outs() << "[re-export] ";
5579 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005580 outs() << format("0x%08llX ",
5581 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005582 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00005583 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005584 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00005585 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00005586 if (WeakDef) {
5587 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005588 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00005589 }
5590 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005591 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00005592 outs() << ", ";
5593 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005594 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00005595 }
5596 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005597 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00005598 outs() << ", ";
5599 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005600 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00005601 }
5602 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005603 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00005604 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005605 outs() << format("resolver=0x%08llX", Entry.other());
5606 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00005607 }
5608 outs() << "]";
5609 }
5610 if (ReExport) {
5611 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005612 int Ordinal = Entry.other() - 1;
5613 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5614 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00005615 outs() << " (from " << DylibName << ")";
5616 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005617 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00005618 }
5619 outs() << "\n";
5620 }
5621}
Nick Kledzikac431442014-09-12 21:34:15 +00005622
Nick Kledzikac431442014-09-12 21:34:15 +00005623//===----------------------------------------------------------------------===//
5624// rebase table dumping
5625//===----------------------------------------------------------------------===//
5626
5627namespace {
5628class SegInfo {
5629public:
5630 SegInfo(const object::MachOObjectFile *Obj);
5631
5632 StringRef segmentName(uint32_t SegIndex);
5633 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5634 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5635
5636private:
5637 struct SectionInfo {
5638 uint64_t Address;
5639 uint64_t Size;
5640 StringRef SectionName;
5641 StringRef SegmentName;
5642 uint64_t OffsetInSegment;
5643 uint64_t SegmentStartAddress;
5644 uint32_t SegmentIndex;
5645 };
5646 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5647 SmallVector<SectionInfo, 32> Sections;
5648};
5649}
5650
5651SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5652 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00005653 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00005654 StringRef CurSegName;
5655 uint64_t CurSegAddress;
5656 for (const SectionRef &Section : Obj->sections()) {
5657 SectionInfo Info;
5658 if (error(Section.getName(Info.SectionName)))
5659 return;
Rafael Espindola80291272014-10-08 15:28:58 +00005660 Info.Address = Section.getAddress();
5661 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00005662 Info.SegmentName =
5663 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5664 if (!Info.SegmentName.equals(CurSegName)) {
5665 ++CurSegIndex;
5666 CurSegName = Info.SegmentName;
5667 CurSegAddress = Info.Address;
5668 }
5669 Info.SegmentIndex = CurSegIndex - 1;
5670 Info.OffsetInSegment = Info.Address - CurSegAddress;
5671 Info.SegmentStartAddress = CurSegAddress;
5672 Sections.push_back(Info);
5673 }
5674}
5675
5676StringRef SegInfo::segmentName(uint32_t SegIndex) {
5677 for (const SectionInfo &SI : Sections) {
5678 if (SI.SegmentIndex == SegIndex)
5679 return SI.SegmentName;
5680 }
5681 llvm_unreachable("invalid segIndex");
5682}
5683
5684const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5685 uint64_t OffsetInSeg) {
5686 for (const SectionInfo &SI : Sections) {
5687 if (SI.SegmentIndex != SegIndex)
5688 continue;
5689 if (SI.OffsetInSegment > OffsetInSeg)
5690 continue;
5691 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5692 continue;
5693 return SI;
5694 }
5695 llvm_unreachable("segIndex and offset not in any section");
5696}
5697
5698StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5699 return findSection(SegIndex, OffsetInSeg).SectionName;
5700}
5701
5702uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5703 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5704 return SI.SegmentStartAddress + OffsetInSeg;
5705}
5706
5707void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5708 // Build table of sections so names can used in final output.
5709 SegInfo sectionTable(Obj);
5710
5711 outs() << "segment section address type\n";
5712 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5713 uint32_t SegIndex = Entry.segmentIndex();
5714 uint64_t OffsetInSeg = Entry.segmentOffset();
5715 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5716 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5717 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5718
5719 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005720 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5721 SegmentName.str().c_str(), SectionName.str().c_str(),
5722 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00005723 }
5724}
Nick Kledzik56ebef42014-09-16 01:41:51 +00005725
5726static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5727 StringRef DylibName;
5728 switch (Ordinal) {
5729 case MachO::BIND_SPECIAL_DYLIB_SELF:
5730 return "this-image";
5731 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5732 return "main-executable";
5733 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5734 return "flat-namespace";
5735 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00005736 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005737 std::error_code EC =
5738 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00005739 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00005740 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00005741 return DylibName;
5742 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00005743 }
Nick Kledzikabd29872014-09-16 22:03:13 +00005744 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005745}
5746
5747//===----------------------------------------------------------------------===//
5748// bind table dumping
5749//===----------------------------------------------------------------------===//
5750
5751void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5752 // Build table of sections so names can used in final output.
5753 SegInfo sectionTable(Obj);
5754
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005755 outs() << "segment section address type "
5756 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005757 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5758 uint32_t SegIndex = Entry.segmentIndex();
5759 uint64_t OffsetInSeg = Entry.segmentOffset();
5760 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5761 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5762 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5763
5764 // Table lines look like:
5765 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005766 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00005767 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005768 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005769 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005770 << left_justify(SectionName, 18) << " "
5771 << format_hex(Address, 10, true) << " "
5772 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005773 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005774 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005775 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005776 }
5777}
5778
5779//===----------------------------------------------------------------------===//
5780// lazy bind table dumping
5781//===----------------------------------------------------------------------===//
5782
5783void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5784 // Build table of sections so names can used in final output.
5785 SegInfo sectionTable(Obj);
5786
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005787 outs() << "segment section address "
5788 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005789 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5790 uint32_t SegIndex = Entry.segmentIndex();
5791 uint64_t OffsetInSeg = Entry.segmentOffset();
5792 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5793 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5794 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5795
5796 // Table lines look like:
5797 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005798 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005799 << left_justify(SectionName, 18) << " "
5800 << format_hex(Address, 10, true) << " "
5801 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00005802 << Entry.symbolName() << "\n";
5803 }
5804}
5805
Nick Kledzik56ebef42014-09-16 01:41:51 +00005806//===----------------------------------------------------------------------===//
5807// weak bind table dumping
5808//===----------------------------------------------------------------------===//
5809
5810void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5811 // Build table of sections so names can used in final output.
5812 SegInfo sectionTable(Obj);
5813
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005814 outs() << "segment section address "
5815 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005816 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5817 // Strong symbols don't have a location to update.
5818 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005819 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00005820 << Entry.symbolName() << "\n";
5821 continue;
5822 }
5823 uint32_t SegIndex = Entry.segmentIndex();
5824 uint64_t OffsetInSeg = Entry.segmentOffset();
5825 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5826 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5827 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5828
5829 // Table lines look like:
5830 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005831 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005832 << left_justify(SectionName, 18) << " "
5833 << format_hex(Address, 10, true) << " "
5834 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005835 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5836 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005837 }
5838}
5839
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005840// get_dyld_bind_info_symbolname() is used for disassembly and passed an
5841// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5842// information for that address. If the address is found its binding symbol
5843// name is returned. If not nullptr is returned.
5844static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5845 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00005846 if (info->bindtable == nullptr) {
5847 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005848 SegInfo sectionTable(info->O);
5849 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5850 uint32_t SegIndex = Entry.segmentIndex();
5851 uint64_t OffsetInSeg = Entry.segmentOffset();
5852 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5853 const char *SymbolName = nullptr;
5854 StringRef name = Entry.symbolName();
5855 if (!name.empty())
5856 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00005857 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005858 }
5859 }
Kevin Enderby078be602014-10-23 19:53:12 +00005860 for (bind_table_iterator BI = info->bindtable->begin(),
5861 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005862 BI != BE; ++BI) {
5863 uint64_t Address = BI->first;
5864 if (ReferenceValue == Address) {
5865 const char *SymbolName = BI->second;
5866 return SymbolName;
5867 }
5868 }
5869 return nullptr;
5870}