blob: 3281b321fe7fcf16e1b09bb2f6083108275d21d0 [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
66static cl::opt<bool>
67 PrintImmHex("print-imm-hex",
68 cl::desc("Use hex format for immediate values"));
69
Kevin Enderby13023a12015-01-15 23:19:11 +000070cl::opt<bool> llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers "
72 "(requires -macho)"));
73
Kevin Enderby131d1772015-01-09 19:22:37 +000074cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000075 llvm::ArchiveHeaders("archive-headers",
76 cl::desc("Print archive headers for Mach-O archives "
77 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000078
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000079cl::opt<bool>
80 llvm::IndirectSymbols("indirect-symbols",
81 cl::desc("Print indirect symbol table for Mach-O "
82 "objects (requires -macho)"));
83
Kevin Enderby69fe98d2015-01-23 18:52:17 +000084cl::opt<bool>
85 llvm::DataInCode("data-in-code",
86 cl::desc("Print the data in code table for Mach-O objects "
87 "(requires -macho)"));
88
Kevin Enderby9a509442015-01-27 21:28:24 +000089cl::opt<bool>
90 llvm::LinkOptHints("link-opt-hints",
91 cl::desc("Print the linker optimization hints for "
92 "Mach-O objects (requires -macho)"));
93
Kevin Enderbyf6d25852015-01-31 00:37:11 +000094cl::list<std::string>
95 llvm::DumpSections("section",
96 cl::desc("Prints the specified segment,section for "
97 "Mach-O objects (requires -macho)"));
98
Kevin Enderbycd66be52015-03-11 22:06:32 +000099cl::opt<bool>
100 llvm::InfoPlist("info-plist",
101 cl::desc("Print the info plist section as strings for "
102 "Mach-O objects (requires -macho)"));
103
Kevin Enderbyf0640752015-03-13 17:56:32 +0000104cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000105 llvm::DylibsUsed("dylibs-used",
106 cl::desc("Print the shared libraries used for linked "
107 "Mach-O files (requires -macho)"));
108
109cl::opt<bool>
110 llvm::DylibId("dylib-id",
111 cl::desc("Print the shared library's id for the dylib Mach-O "
112 "file (requires -macho)"));
113
114cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000115 llvm::NonVerbose("non-verbose",
116 cl::desc("Print the info for Mach-O objects in "
117 "non-verbose or numeric form (requires -macho)"));
118
Kevin Enderby6a221752015-03-17 17:10:57 +0000119cl::opt<std::string> llvm::DisSymName(
120 "dis-symname",
121 cl::desc("disassemble just this symbol's instructions (requires -macho"));
122
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000123static cl::list<std::string>
124 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
125 cl::ZeroOrMore);
126bool ArchAll = false;
127
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000128static std::string ThumbTripleName;
129
130static const Target *GetTarget(const MachOObjectFile *MachOObj,
131 const char **McpuDefault,
132 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000133 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000134 if (TripleName.empty()) {
135 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000136 llvm::Triple ThumbTriple = Triple();
137 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000138 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000139 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000140 }
141
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000142 // Get the target specific parser.
143 std::string Error;
144 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000145 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000146 return TheTarget;
147
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000148 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
149 if (*ThumbTarget)
150 return TheTarget;
151
152 errs() << "llvm-objdump: error: unable to get target for '";
153 if (!TheTarget)
154 errs() << TripleName;
155 else
156 errs() << ThumbTripleName;
157 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000158 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000159}
160
Owen Andersond9243c42011-10-17 21:37:35 +0000161struct SymbolSorter {
162 bool operator()(const SymbolRef &A, const SymbolRef &B) {
163 SymbolRef::Type AType, BType;
164 A.getType(AType);
165 B.getType(BType);
166
167 uint64_t AAddr, BAddr;
168 if (AType != SymbolRef::ST_Function)
169 AAddr = 0;
170 else
171 A.getAddress(AAddr);
172 if (BType != SymbolRef::ST_Function)
173 BAddr = 0;
174 else
175 B.getAddress(BAddr);
176 return AAddr < BAddr;
177 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000178};
179
Kevin Enderby273ae012013-06-06 17:20:50 +0000180// Types for the storted data in code table that is built before disassembly
181// and the predicate function to sort them.
182typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
183typedef std::vector<DiceTableEntry> DiceTable;
184typedef DiceTable::iterator dice_table_iterator;
185
Kevin Enderby930fdc72014-11-06 19:00:13 +0000186// This is used to search for a data in code table entry for the PC being
187// disassembled. The j parameter has the PC in j.first. A single data in code
188// table entry can cover many bytes for each of its Kind's. So if the offset,
189// aka the i.first value, of the data in code table entry plus its Length
190// covers the PC being searched for this will return true. If not it will
191// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000192static bool compareDiceTableEntries(const DiceTableEntry &i,
193 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000194 uint16_t Length;
195 i.second.getLength(Length);
196
197 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000198}
199
Kevin Enderby930fdc72014-11-06 19:00:13 +0000200static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
201 unsigned short Kind) {
202 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000203
204 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000205 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000206 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000207 if (Length >= 4) {
208 if (!NoShowRawInsn)
209 DumpBytes(StringRef(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000210 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000211 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000212 Size = 4;
213 } else if (Length >= 2) {
214 if (!NoShowRawInsn)
215 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000216 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000217 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000218 Size = 2;
219 } else {
220 if (!NoShowRawInsn)
221 DumpBytes(StringRef(bytes, 2));
Kevin Enderby273ae012013-06-06 17:20:50 +0000222 Value = bytes[0];
223 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000224 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000225 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 if (Kind == MachO::DICE_KIND_DATA)
227 outs() << "\t@ KIND_DATA\n";
228 else
229 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000230 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000231 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000232 if (!NoShowRawInsn)
233 DumpBytes(StringRef(bytes, 1));
Kevin Enderby273ae012013-06-06 17:20:50 +0000234 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000235 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
236 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000237 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000238 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000239 if (!NoShowRawInsn)
240 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000241 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000242 outs() << "\t.short " << format("%5u", Value & 0xffff)
243 << "\t@ KIND_JUMP_TABLE16\n";
244 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000245 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000246 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000247 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
248 if (!NoShowRawInsn)
249 DumpBytes(StringRef(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000250 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000251 outs() << "\t.long " << Value;
252 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
253 outs() << "\t@ KIND_JUMP_TABLE32\n";
254 else
255 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
256 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000257 break;
258 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000259 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000260}
261
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000262static void getSectionsAndSymbols(const MachO::mach_header Header,
263 MachOObjectFile *MachOObj,
264 std::vector<SectionRef> &Sections,
265 std::vector<SymbolRef> &Symbols,
266 SmallVectorImpl<uint64_t> &FoundFns,
267 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000268 for (const SymbolRef &Symbol : MachOObj->symbols()) {
269 StringRef SymName;
270 Symbol.getName(SymName);
271 if (!SymName.startswith("ltmp"))
272 Symbols.push_back(Symbol);
273 }
Owen Andersond9243c42011-10-17 21:37:35 +0000274
Alexey Samsonov48803e52014-03-13 14:37:36 +0000275 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000276 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000277 Section.getName(SectName);
278 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000279 }
280
Rafael Espindola56f976f2013-04-18 18:08:55 +0000281 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000282 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000283 bool BaseSegmentAddressSet = false;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000284 for (unsigned i = 0;; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000285 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000286 // We found a function starts segment, parse the addresses for later
287 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000288 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000289 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000290
Charles Davis8bdfafd2013-09-01 04:28:48 +0000291 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000292 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
293 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000294 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000295 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000296 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000297 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000298 }
299 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000300
Charles Davis8bdfafd2013-09-01 04:28:48 +0000301 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000302 break;
303 else
304 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000305 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000306}
307
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000308static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
309 uint32_t n, uint32_t count,
310 uint32_t stride, uint64_t addr) {
311 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
312 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
313 if (n > nindirectsyms)
314 outs() << " (entries start past the end of the indirect symbol "
315 "table) (reserved1 field greater than the table size)";
316 else if (n + count > nindirectsyms)
317 outs() << " (entries extends past the end of the indirect symbol "
318 "table)";
319 outs() << "\n";
320 uint32_t cputype = O->getHeader().cputype;
321 if (cputype & MachO::CPU_ARCH_ABI64)
322 outs() << "address index";
323 else
324 outs() << "address index";
325 if (verbose)
326 outs() << " name\n";
327 else
328 outs() << "\n";
329 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
330 if (cputype & MachO::CPU_ARCH_ABI64)
331 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
332 else
333 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
334 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
335 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
336 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
337 outs() << "LOCAL\n";
338 continue;
339 }
340 if (indirect_symbol ==
341 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
342 outs() << "LOCAL ABSOLUTE\n";
343 continue;
344 }
345 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
346 outs() << "ABSOLUTE\n";
347 continue;
348 }
349 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000350 if (verbose) {
351 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
352 if (indirect_symbol < Symtab.nsyms) {
353 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
354 SymbolRef Symbol = *Sym;
355 StringRef SymName;
356 Symbol.getName(SymName);
357 outs() << SymName;
358 } else {
359 outs() << "?";
360 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000361 }
362 outs() << "\n";
363 }
364}
365
366static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
367 uint32_t LoadCommandCount = O->getHeader().ncmds;
368 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
369 for (unsigned I = 0;; ++I) {
370 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
371 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
372 for (unsigned J = 0; J < Seg.nsects; ++J) {
373 MachO::section_64 Sec = O->getSection64(Load, J);
374 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
375 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
376 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
377 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
378 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
379 section_type == MachO::S_SYMBOL_STUBS) {
380 uint32_t stride;
381 if (section_type == MachO::S_SYMBOL_STUBS)
382 stride = Sec.reserved2;
383 else
384 stride = 8;
385 if (stride == 0) {
386 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
387 << Sec.sectname << ") "
388 << "(size of stubs in reserved2 field is zero)\n";
389 continue;
390 }
391 uint32_t count = Sec.size / stride;
392 outs() << "Indirect symbols for (" << Sec.segname << ","
393 << Sec.sectname << ") " << count << " entries";
394 uint32_t n = Sec.reserved1;
395 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
396 }
397 }
398 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
399 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
400 for (unsigned J = 0; J < Seg.nsects; ++J) {
401 MachO::section Sec = O->getSection(Load, J);
402 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
403 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
404 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
405 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
406 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
407 section_type == MachO::S_SYMBOL_STUBS) {
408 uint32_t stride;
409 if (section_type == MachO::S_SYMBOL_STUBS)
410 stride = Sec.reserved2;
411 else
412 stride = 4;
413 if (stride == 0) {
414 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
415 << Sec.sectname << ") "
416 << "(size of stubs in reserved2 field is zero)\n";
417 continue;
418 }
419 uint32_t count = Sec.size / stride;
420 outs() << "Indirect symbols for (" << Sec.segname << ","
421 << Sec.sectname << ") " << count << " entries";
422 uint32_t n = Sec.reserved1;
423 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
424 }
425 }
426 }
427 if (I == LoadCommandCount - 1)
428 break;
429 else
430 Load = O->getNextLoadCommandInfo(Load);
431 }
432}
433
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000434static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
435 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
436 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
437 outs() << "Data in code table (" << nentries << " entries)\n";
438 outs() << "offset length kind\n";
439 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
440 ++DI) {
441 uint32_t Offset;
442 DI->getOffset(Offset);
443 outs() << format("0x%08" PRIx32, Offset) << " ";
444 uint16_t Length;
445 DI->getLength(Length);
446 outs() << format("%6u", Length) << " ";
447 uint16_t Kind;
448 DI->getKind(Kind);
449 if (verbose) {
450 switch (Kind) {
451 case MachO::DICE_KIND_DATA:
452 outs() << "DATA";
453 break;
454 case MachO::DICE_KIND_JUMP_TABLE8:
455 outs() << "JUMP_TABLE8";
456 break;
457 case MachO::DICE_KIND_JUMP_TABLE16:
458 outs() << "JUMP_TABLE16";
459 break;
460 case MachO::DICE_KIND_JUMP_TABLE32:
461 outs() << "JUMP_TABLE32";
462 break;
463 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
464 outs() << "ABS_JUMP_TABLE32";
465 break;
466 default:
467 outs() << format("0x%04" PRIx32, Kind);
468 break;
469 }
470 } else
471 outs() << format("0x%04" PRIx32, Kind);
472 outs() << "\n";
473 }
474}
475
Kevin Enderby9a509442015-01-27 21:28:24 +0000476static void PrintLinkOptHints(MachOObjectFile *O) {
477 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
478 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
479 uint32_t nloh = LohLC.datasize;
480 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
481 for (uint32_t i = 0; i < nloh;) {
482 unsigned n;
483 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
484 i += n;
485 outs() << " identifier " << identifier << " ";
486 if (i >= nloh)
487 return;
488 switch (identifier) {
489 case 1:
490 outs() << "AdrpAdrp\n";
491 break;
492 case 2:
493 outs() << "AdrpLdr\n";
494 break;
495 case 3:
496 outs() << "AdrpAddLdr\n";
497 break;
498 case 4:
499 outs() << "AdrpLdrGotLdr\n";
500 break;
501 case 5:
502 outs() << "AdrpAddStr\n";
503 break;
504 case 6:
505 outs() << "AdrpLdrGotStr\n";
506 break;
507 case 7:
508 outs() << "AdrpAdd\n";
509 break;
510 case 8:
511 outs() << "AdrpLdrGot\n";
512 break;
513 default:
514 outs() << "Unknown identifier value\n";
515 break;
516 }
517 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
518 i += n;
519 outs() << " narguments " << narguments << "\n";
520 if (i >= nloh)
521 return;
522
523 for (uint32_t j = 0; j < narguments; j++) {
524 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
525 i += n;
526 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
527 if (i >= nloh)
528 return;
529 }
530 }
531}
532
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000533static void PrintDylibs(MachOObjectFile *O, bool JustId) {
534 uint32_t LoadCommandCount = O->getHeader().ncmds;
535 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
536 for (unsigned I = 0;; ++I) {
537 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
538 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
539 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
540 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
541 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
542 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
543 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
544 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
545 if (dl.dylib.name < dl.cmdsize) {
546 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
547 if (JustId)
548 outs() << p << "\n";
549 else {
550 outs() << "\t" << p;
551 outs() << " (compatibility version "
552 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
553 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
554 << (dl.dylib.compatibility_version & 0xff) << ",";
555 outs() << " current version "
556 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
557 << ((dl.dylib.current_version >> 8) & 0xff) << "."
558 << (dl.dylib.current_version & 0xff) << ")\n";
559 }
560 } else {
561 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
562 if (Load.C.cmd == MachO::LC_ID_DYLIB)
563 outs() << "LC_ID_DYLIB ";
564 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
565 outs() << "LC_LOAD_DYLIB ";
566 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
567 outs() << "LC_LOAD_WEAK_DYLIB ";
568 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
569 outs() << "LC_LAZY_LOAD_DYLIB ";
570 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
571 outs() << "LC_REEXPORT_DYLIB ";
572 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
573 outs() << "LC_LOAD_UPWARD_DYLIB ";
574 else
575 outs() << "LC_??? ";
576 outs() << "command " << I << "\n";
577 }
578 }
579 if (I == LoadCommandCount - 1)
580 break;
581 else
582 Load = O->getNextLoadCommandInfo(Load);
583 }
584}
585
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000586typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
587
588static void CreateSymbolAddressMap(MachOObjectFile *O,
589 SymbolAddressMap *AddrMap) {
590 // Create a map of symbol addresses to symbol names.
591 for (const SymbolRef &Symbol : O->symbols()) {
592 SymbolRef::Type ST;
593 Symbol.getType(ST);
594 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
595 ST == SymbolRef::ST_Other) {
596 uint64_t Address;
597 Symbol.getAddress(Address);
598 StringRef SymName;
599 Symbol.getName(SymName);
600 (*AddrMap)[Address] = SymName;
601 }
602 }
603}
604
605// GuessSymbolName is passed the address of what might be a symbol and a
606// pointer to the SymbolAddressMap. It returns the name of a symbol
607// with that address or nullptr if no symbol is found with that address.
608static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
609 const char *SymbolName = nullptr;
610 // A DenseMap can't lookup up some values.
611 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
612 StringRef name = AddrMap->lookup(value);
613 if (!name.empty())
614 SymbolName = name.data();
615 }
616 return SymbolName;
617}
618
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000619static void DumpCstringChar(const char c) {
620 char p[2];
621 p[0] = c;
622 p[1] = '\0';
623 outs().write_escaped(p);
624}
625
Kevin Enderby10ba0412015-02-04 21:38:42 +0000626static void DumpCstringSection(MachOObjectFile *O, const char *sect,
627 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000628 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000629 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000630 if (print_addresses) {
631 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000632 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000633 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000634 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000635 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000636 for (; i < sect_size && sect[i] != '\0'; i++)
637 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000638 if (i < sect_size && sect[i] == '\0')
639 outs() << "\n";
640 }
641}
642
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000643static void DumpLiteral4(uint32_t l, float f) {
644 outs() << format("0x%08" PRIx32, l);
645 if ((l & 0x7f800000) != 0x7f800000)
646 outs() << format(" (%.16e)\n", f);
647 else {
648 if (l == 0x7f800000)
649 outs() << " (+Infinity)\n";
650 else if (l == 0xff800000)
651 outs() << " (-Infinity)\n";
652 else if ((l & 0x00400000) == 0x00400000)
653 outs() << " (non-signaling Not-a-Number)\n";
654 else
655 outs() << " (signaling Not-a-Number)\n";
656 }
657}
658
659static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
660 uint32_t sect_size, uint64_t sect_addr,
661 bool print_addresses) {
662 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
663 if (print_addresses) {
664 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000665 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000666 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000667 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000668 }
669 float f;
670 memcpy(&f, sect + i, sizeof(float));
671 if (O->isLittleEndian() != sys::IsLittleEndianHost)
672 sys::swapByteOrder(f);
673 uint32_t l;
674 memcpy(&l, sect + i, sizeof(uint32_t));
675 if (O->isLittleEndian() != sys::IsLittleEndianHost)
676 sys::swapByteOrder(l);
677 DumpLiteral4(l, f);
678 }
679}
680
681static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
682 double d) {
683 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
684 uint32_t Hi, Lo;
685 if (O->isLittleEndian()) {
686 Hi = l1;
687 Lo = l0;
688 } else {
689 Hi = l0;
690 Lo = l1;
691 }
692 // Hi is the high word, so this is equivalent to if(isfinite(d))
693 if ((Hi & 0x7ff00000) != 0x7ff00000)
694 outs() << format(" (%.16e)\n", d);
695 else {
696 if (Hi == 0x7ff00000 && Lo == 0)
697 outs() << " (+Infinity)\n";
698 else if (Hi == 0xfff00000 && Lo == 0)
699 outs() << " (-Infinity)\n";
700 else if ((Hi & 0x00080000) == 0x00080000)
701 outs() << " (non-signaling Not-a-Number)\n";
702 else
703 outs() << " (signaling Not-a-Number)\n";
704 }
705}
706
707static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
708 uint32_t sect_size, uint64_t sect_addr,
709 bool print_addresses) {
710 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
711 if (print_addresses) {
712 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000713 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000714 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000715 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000716 }
717 double d;
718 memcpy(&d, sect + i, sizeof(double));
719 if (O->isLittleEndian() != sys::IsLittleEndianHost)
720 sys::swapByteOrder(d);
721 uint32_t l0, l1;
722 memcpy(&l0, sect + i, sizeof(uint32_t));
723 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
724 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
725 sys::swapByteOrder(l0);
726 sys::swapByteOrder(l1);
727 }
728 DumpLiteral8(O, l0, l1, d);
729 }
730}
731
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000732static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
733 outs() << format("0x%08" PRIx32, l0) << " ";
734 outs() << format("0x%08" PRIx32, l1) << " ";
735 outs() << format("0x%08" PRIx32, l2) << " ";
736 outs() << format("0x%08" PRIx32, l3) << "\n";
737}
738
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000739static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
740 uint32_t sect_size, uint64_t sect_addr,
741 bool print_addresses) {
742 for (uint32_t i = 0; i < sect_size; i += 16) {
743 if (print_addresses) {
744 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000745 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000746 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000747 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000748 }
749 uint32_t l0, l1, l2, l3;
750 memcpy(&l0, sect + i, sizeof(uint32_t));
751 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
752 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
753 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
754 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
755 sys::swapByteOrder(l0);
756 sys::swapByteOrder(l1);
757 sys::swapByteOrder(l2);
758 sys::swapByteOrder(l3);
759 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000760 DumpLiteral16(l0, l1, l2, l3);
761 }
762}
763
764static void DumpLiteralPointerSection(MachOObjectFile *O,
765 const SectionRef &Section,
766 const char *sect, uint32_t sect_size,
767 uint64_t sect_addr,
768 bool print_addresses) {
769 // Collect the literal sections in this Mach-O file.
770 std::vector<SectionRef> LiteralSections;
771 for (const SectionRef &Section : O->sections()) {
772 DataRefImpl Ref = Section.getRawDataRefImpl();
773 uint32_t section_type;
774 if (O->is64Bit()) {
775 const MachO::section_64 Sec = O->getSection64(Ref);
776 section_type = Sec.flags & MachO::SECTION_TYPE;
777 } else {
778 const MachO::section Sec = O->getSection(Ref);
779 section_type = Sec.flags & MachO::SECTION_TYPE;
780 }
781 if (section_type == MachO::S_CSTRING_LITERALS ||
782 section_type == MachO::S_4BYTE_LITERALS ||
783 section_type == MachO::S_8BYTE_LITERALS ||
784 section_type == MachO::S_16BYTE_LITERALS)
785 LiteralSections.push_back(Section);
786 }
787
788 // Set the size of the literal pointer.
789 uint32_t lp_size = O->is64Bit() ? 8 : 4;
790
791 // Collect the external relocation symbols for the the literal pointers.
792 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
793 for (const RelocationRef &Reloc : Section.relocations()) {
794 DataRefImpl Rel;
795 MachO::any_relocation_info RE;
796 bool isExtern = false;
797 Rel = Reloc.getRawDataRefImpl();
798 RE = O->getRelocation(Rel);
799 isExtern = O->getPlainRelocationExternal(RE);
800 if (isExtern) {
801 uint64_t RelocOffset;
802 Reloc.getOffset(RelocOffset);
803 symbol_iterator RelocSym = Reloc.getSymbol();
804 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
805 }
806 }
807 array_pod_sort(Relocs.begin(), Relocs.end());
808
809 // Dump each literal pointer.
810 for (uint32_t i = 0; i < sect_size; i += lp_size) {
811 if (print_addresses) {
812 if (O->is64Bit())
813 outs() << format("%016" PRIx64, sect_addr + i) << " ";
814 else
815 outs() << format("%08" PRIx64, sect_addr + i) << " ";
816 }
817 uint64_t lp;
818 if (O->is64Bit()) {
819 memcpy(&lp, sect + i, sizeof(uint64_t));
820 if (O->isLittleEndian() != sys::IsLittleEndianHost)
821 sys::swapByteOrder(lp);
822 } else {
823 uint32_t li;
824 memcpy(&li, sect + i, sizeof(uint32_t));
825 if (O->isLittleEndian() != sys::IsLittleEndianHost)
826 sys::swapByteOrder(li);
827 lp = li;
828 }
829
830 // First look for an external relocation entry for this literal pointer.
831 bool reloc_found = false;
832 for (unsigned j = 0, e = Relocs.size(); j != e; ++j) {
833 if (Relocs[i].first == i) {
834 symbol_iterator RelocSym = Relocs[j].second;
835 StringRef SymName;
836 RelocSym->getName(SymName);
837 outs() << "external relocation entry for symbol:" << SymName << "\n";
838 reloc_found = true;
839 }
840 }
841 if (reloc_found == true)
842 continue;
843
844 // For local references see what the section the literal pointer points to.
845 bool found = false;
846 for (unsigned SectIdx = 0; SectIdx != LiteralSections.size(); SectIdx++) {
847 uint64_t SectAddress = LiteralSections[SectIdx].getAddress();
848 uint64_t SectSize = LiteralSections[SectIdx].getSize();
849 if (lp >= SectAddress && lp < SectAddress + SectSize) {
850 found = true;
851
852 StringRef SectName;
853 LiteralSections[SectIdx].getName(SectName);
854 DataRefImpl Ref = LiteralSections[SectIdx].getRawDataRefImpl();
855 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
856 outs() << SegmentName << ":" << SectName << ":";
857
858 uint32_t section_type;
859 if (O->is64Bit()) {
860 const MachO::section_64 Sec = O->getSection64(Ref);
861 section_type = Sec.flags & MachO::SECTION_TYPE;
862 } else {
863 const MachO::section Sec = O->getSection(Ref);
864 section_type = Sec.flags & MachO::SECTION_TYPE;
865 }
866
867 StringRef BytesStr;
868 LiteralSections[SectIdx].getContents(BytesStr);
869 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
870
871 switch (section_type) {
872 case MachO::S_CSTRING_LITERALS:
873 for (uint64_t i = lp - SectAddress;
874 i < SectSize && Contents[i] != '\0'; i++) {
875 DumpCstringChar(Contents[i]);
876 }
877 outs() << "\n";
878 break;
879 case MachO::S_4BYTE_LITERALS:
880 float f;
881 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
882 uint32_t l;
883 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
884 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
885 sys::swapByteOrder(f);
886 sys::swapByteOrder(l);
887 }
888 DumpLiteral4(l, f);
889 break;
890 case MachO::S_8BYTE_LITERALS: {
891 double d;
892 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
893 uint32_t l0, l1;
894 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
895 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
896 sizeof(uint32_t));
897 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
898 sys::swapByteOrder(f);
899 sys::swapByteOrder(l0);
900 sys::swapByteOrder(l1);
901 }
902 DumpLiteral8(O, l0, l1, d);
903 break;
904 }
905 case MachO::S_16BYTE_LITERALS: {
906 uint32_t l0, l1, l2, l3;
907 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
908 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
909 sizeof(uint32_t));
910 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
911 sizeof(uint32_t));
912 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
913 sizeof(uint32_t));
914 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
915 sys::swapByteOrder(l0);
916 sys::swapByteOrder(l1);
917 sys::swapByteOrder(l2);
918 sys::swapByteOrder(l3);
919 }
920 DumpLiteral16(l0, l1, l2, l3);
921 break;
922 }
923 }
924 }
925 }
926 if (found == false)
927 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000928 }
929}
930
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000931static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
932 uint32_t sect_size, uint64_t sect_addr,
933 SymbolAddressMap *AddrMap,
934 bool verbose) {
935 uint32_t stride;
936 if (O->is64Bit())
937 stride = sizeof(uint64_t);
938 else
939 stride = sizeof(uint32_t);
940 for (uint32_t i = 0; i < sect_size; i += stride) {
941 const char *SymbolName = nullptr;
942 if (O->is64Bit()) {
943 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
944 uint64_t pointer_value;
945 memcpy(&pointer_value, sect + i, stride);
946 if (O->isLittleEndian() != sys::IsLittleEndianHost)
947 sys::swapByteOrder(pointer_value);
948 outs() << format("0x%016" PRIx64, pointer_value);
949 if (verbose)
950 SymbolName = GuessSymbolName(pointer_value, AddrMap);
951 } else {
952 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
953 uint32_t pointer_value;
954 memcpy(&pointer_value, sect + i, stride);
955 if (O->isLittleEndian() != sys::IsLittleEndianHost)
956 sys::swapByteOrder(pointer_value);
957 outs() << format("0x%08" PRIx32, pointer_value);
958 if (verbose)
959 SymbolName = GuessSymbolName(pointer_value, AddrMap);
960 }
961 if (SymbolName)
962 outs() << " " << SymbolName;
963 outs() << "\n";
964 }
965}
966
967static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
968 uint32_t size, uint64_t addr) {
969 uint32_t cputype = O->getHeader().cputype;
970 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
971 uint32_t j;
972 for (uint32_t i = 0; i < size; i += j, addr += j) {
973 if (O->is64Bit())
974 outs() << format("%016" PRIx64, addr) << "\t";
975 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000976 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000977 for (j = 0; j < 16 && i + j < size; j++) {
978 uint8_t byte_word = *(sect + i + j);
979 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
980 }
981 outs() << "\n";
982 }
983 } else {
984 uint32_t j;
985 for (uint32_t i = 0; i < size; i += j, addr += j) {
986 if (O->is64Bit())
987 outs() << format("%016" PRIx64, addr) << "\t";
988 else
989 outs() << format("%08" PRIx64, sect) << "\t";
990 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
991 j += sizeof(int32_t)) {
992 if (i + j + sizeof(int32_t) < size) {
993 uint32_t long_word;
994 memcpy(&long_word, sect + i + j, sizeof(int32_t));
995 if (O->isLittleEndian() != sys::IsLittleEndianHost)
996 sys::swapByteOrder(long_word);
997 outs() << format("%08" PRIx32, long_word) << " ";
998 } else {
999 for (uint32_t k = 0; i + j + k < size; k++) {
1000 uint8_t byte_word = *(sect + i + j);
1001 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1002 }
1003 }
1004 }
1005 outs() << "\n";
1006 }
1007 }
1008}
1009
Kevin Enderby95df54c2015-02-04 01:01:38 +00001010static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1011 StringRef DisSegName, StringRef DisSectName);
1012
1013static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1014 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001015 SymbolAddressMap AddrMap;
1016 if (verbose)
1017 CreateSymbolAddressMap(O, &AddrMap);
1018
1019 for (unsigned i = 0; i < DumpSections.size(); ++i) {
1020 StringRef DumpSection = DumpSections[i];
1021 std::pair<StringRef, StringRef> DumpSegSectName;
1022 DumpSegSectName = DumpSection.split(',');
1023 StringRef DumpSegName, DumpSectName;
1024 if (DumpSegSectName.second.size()) {
1025 DumpSegName = DumpSegSectName.first;
1026 DumpSectName = DumpSegSectName.second;
1027 } else {
1028 DumpSegName = "";
1029 DumpSectName = DumpSegSectName.first;
1030 }
1031 for (const SectionRef &Section : O->sections()) {
1032 StringRef SectName;
1033 Section.getName(SectName);
1034 DataRefImpl Ref = Section.getRawDataRefImpl();
1035 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1036 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1037 (SectName == DumpSectName)) {
1038 outs() << "Contents of (" << SegName << "," << SectName
1039 << ") section\n";
Kevin Enderby95df54c2015-02-04 01:01:38 +00001040 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001041 if (O->is64Bit()) {
1042 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001043 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001044
1045 } else {
1046 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001047 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001048 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001049 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001050
1051 StringRef BytesStr;
1052 Section.getContents(BytesStr);
1053 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1054 uint32_t sect_size = BytesStr.size();
1055 uint64_t sect_addr = Section.getAddress();
1056
1057 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001058 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1059 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1060 DisassembleMachO(Filename, O, SegName, SectName);
1061 continue;
1062 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001063 if (SegName == "__TEXT" && SectName == "__info_plist") {
1064 outs() << sect;
1065 continue;
1066 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001067 switch (section_type) {
1068 case MachO::S_REGULAR:
1069 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1070 break;
1071 case MachO::S_ZEROFILL:
1072 outs() << "zerofill section and has no contents in the file\n";
1073 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001074 case MachO::S_CSTRING_LITERALS:
1075 DumpCstringSection(O, sect, sect_size, sect_addr, verbose);
1076 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001077 case MachO::S_4BYTE_LITERALS:
1078 DumpLiteral4Section(O, sect, sect_size, sect_addr, verbose);
1079 break;
1080 case MachO::S_8BYTE_LITERALS:
1081 DumpLiteral8Section(O, sect, sect_size, sect_addr, verbose);
1082 break;
1083 case MachO::S_16BYTE_LITERALS:
1084 DumpLiteral16Section(O, sect, sect_size, sect_addr, verbose);
1085 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001086 case MachO::S_LITERAL_POINTERS:
1087 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1088 verbose);
1089 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001090 case MachO::S_MOD_INIT_FUNC_POINTERS:
1091 case MachO::S_MOD_TERM_FUNC_POINTERS:
1092 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1093 verbose);
1094 break;
1095 default:
1096 outs() << "Unknown section type ("
1097 << format("0x%08" PRIx32, section_type) << ")\n";
1098 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1099 break;
1100 }
1101 } else {
1102 if (section_type == MachO::S_ZEROFILL)
1103 outs() << "zerofill section and has no contents in the file\n";
1104 else
1105 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1106 }
1107 }
1108 }
1109 }
1110}
1111
Kevin Enderbycd66be52015-03-11 22:06:32 +00001112static void DumpInfoPlistSectionContents(StringRef Filename,
1113 MachOObjectFile *O) {
1114 for (const SectionRef &Section : O->sections()) {
1115 StringRef SectName;
1116 Section.getName(SectName);
1117 DataRefImpl Ref = Section.getRawDataRefImpl();
1118 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1119 if (SegName == "__TEXT" && SectName == "__info_plist") {
1120 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1121 StringRef BytesStr;
1122 Section.getContents(BytesStr);
1123 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1124 outs() << sect;
1125 return;
1126 }
1127 }
1128}
1129
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001130// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1131// and if it is and there is a list of architecture flags is specified then
1132// check to make sure this Mach-O file is one of those architectures or all
1133// architectures were specified. If not then an error is generated and this
1134// routine returns false. Else it returns true.
1135static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1136 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1137 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1138 bool ArchFound = false;
1139 MachO::mach_header H;
1140 MachO::mach_header_64 H_64;
1141 Triple T;
1142 if (MachO->is64Bit()) {
1143 H_64 = MachO->MachOObjectFile::getHeader64();
1144 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1145 } else {
1146 H = MachO->MachOObjectFile::getHeader();
1147 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1148 }
1149 unsigned i;
1150 for (i = 0; i < ArchFlags.size(); ++i) {
1151 if (ArchFlags[i] == T.getArchName())
1152 ArchFound = true;
1153 break;
1154 }
1155 if (!ArchFound) {
1156 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1157 << "architecture: " + ArchFlags[i] + "\n";
1158 return false;
1159 }
1160 }
1161 return true;
1162}
1163
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001164// ProcessMachO() is passed a single opened Mach-O file, which may be an
1165// archive member and or in a slice of a universal file. It prints the
1166// the file name and header info and then processes it according to the
1167// command line options.
1168static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1169 StringRef ArchiveMemberName = StringRef(),
1170 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001171 // If we are doing some processing here on the Mach-O file print the header
1172 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001173 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001174 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001175 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001176 DylibsUsed || DylibId || DumpSections.size() != 0) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001177 outs() << Filename;
1178 if (!ArchiveMemberName.empty())
1179 outs() << '(' << ArchiveMemberName << ')';
1180 if (!ArchitectureName.empty())
1181 outs() << " (architecture " << ArchitectureName << ")";
1182 outs() << ":\n";
1183 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001184
1185 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001186 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001187 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001188 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001189 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001190 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001191 if (LinkOptHints)
1192 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001193 if (Relocations)
1194 PrintRelocations(MachOOF);
1195 if (SectionHeaders)
1196 PrintSectionHeaders(MachOOF);
1197 if (SectionContents)
1198 PrintSectionContents(MachOOF);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001199 if (DumpSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001200 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001201 if (InfoPlist)
1202 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001203 if (DylibsUsed)
1204 PrintDylibs(MachOOF, false);
1205 if (DylibId)
1206 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001207 if (SymbolTable)
1208 PrintSymbolTable(MachOOF);
1209 if (UnwindInfo)
1210 printMachOUnwindInfo(MachOOF);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001211 if (PrivateHeaders)
1212 printMachOFileHeader(MachOOF);
1213 if (ExportsTrie)
1214 printExportsTrie(MachOOF);
1215 if (Rebase)
1216 printRebaseTable(MachOOF);
1217 if (Bind)
1218 printBindTable(MachOOF);
1219 if (LazyBind)
1220 printLazyBindTable(MachOOF);
1221 if (WeakBind)
1222 printWeakBindTable(MachOOF);
1223}
1224
Kevin Enderby131d1772015-01-09 19:22:37 +00001225// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1226static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1227 outs() << " cputype (" << cputype << ")\n";
1228 outs() << " cpusubtype (" << cpusubtype << ")\n";
1229}
1230
1231// printCPUType() helps print_fat_headers by printing the cputype and
1232// pusubtype (symbolically for the one's it knows about).
1233static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1234 switch (cputype) {
1235 case MachO::CPU_TYPE_I386:
1236 switch (cpusubtype) {
1237 case MachO::CPU_SUBTYPE_I386_ALL:
1238 outs() << " cputype CPU_TYPE_I386\n";
1239 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1240 break;
1241 default:
1242 printUnknownCPUType(cputype, cpusubtype);
1243 break;
1244 }
1245 break;
1246 case MachO::CPU_TYPE_X86_64:
1247 switch (cpusubtype) {
1248 case MachO::CPU_SUBTYPE_X86_64_ALL:
1249 outs() << " cputype CPU_TYPE_X86_64\n";
1250 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1251 break;
1252 case MachO::CPU_SUBTYPE_X86_64_H:
1253 outs() << " cputype CPU_TYPE_X86_64\n";
1254 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1255 break;
1256 default:
1257 printUnknownCPUType(cputype, cpusubtype);
1258 break;
1259 }
1260 break;
1261 case MachO::CPU_TYPE_ARM:
1262 switch (cpusubtype) {
1263 case MachO::CPU_SUBTYPE_ARM_ALL:
1264 outs() << " cputype CPU_TYPE_ARM\n";
1265 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1266 break;
1267 case MachO::CPU_SUBTYPE_ARM_V4T:
1268 outs() << " cputype CPU_TYPE_ARM\n";
1269 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1270 break;
1271 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1272 outs() << " cputype CPU_TYPE_ARM\n";
1273 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1274 break;
1275 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1276 outs() << " cputype CPU_TYPE_ARM\n";
1277 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1278 break;
1279 case MachO::CPU_SUBTYPE_ARM_V6:
1280 outs() << " cputype CPU_TYPE_ARM\n";
1281 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1282 break;
1283 case MachO::CPU_SUBTYPE_ARM_V6M:
1284 outs() << " cputype CPU_TYPE_ARM\n";
1285 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1286 break;
1287 case MachO::CPU_SUBTYPE_ARM_V7:
1288 outs() << " cputype CPU_TYPE_ARM\n";
1289 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1290 break;
1291 case MachO::CPU_SUBTYPE_ARM_V7EM:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1294 break;
1295 case MachO::CPU_SUBTYPE_ARM_V7K:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1298 break;
1299 case MachO::CPU_SUBTYPE_ARM_V7M:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1302 break;
1303 case MachO::CPU_SUBTYPE_ARM_V7S:
1304 outs() << " cputype CPU_TYPE_ARM\n";
1305 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1306 break;
1307 default:
1308 printUnknownCPUType(cputype, cpusubtype);
1309 break;
1310 }
1311 break;
1312 case MachO::CPU_TYPE_ARM64:
1313 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1314 case MachO::CPU_SUBTYPE_ARM64_ALL:
1315 outs() << " cputype CPU_TYPE_ARM64\n";
1316 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1317 break;
1318 default:
1319 printUnknownCPUType(cputype, cpusubtype);
1320 break;
1321 }
1322 break;
1323 default:
1324 printUnknownCPUType(cputype, cpusubtype);
1325 break;
1326 }
1327}
1328
1329static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1330 bool verbose) {
1331 outs() << "Fat headers\n";
1332 if (verbose)
1333 outs() << "fat_magic FAT_MAGIC\n";
1334 else
1335 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1336
1337 uint32_t nfat_arch = UB->getNumberOfObjects();
1338 StringRef Buf = UB->getData();
1339 uint64_t size = Buf.size();
1340 uint64_t big_size = sizeof(struct MachO::fat_header) +
1341 nfat_arch * sizeof(struct MachO::fat_arch);
1342 outs() << "nfat_arch " << UB->getNumberOfObjects();
1343 if (nfat_arch == 0)
1344 outs() << " (malformed, contains zero architecture types)\n";
1345 else if (big_size > size)
1346 outs() << " (malformed, architectures past end of file)\n";
1347 else
1348 outs() << "\n";
1349
1350 for (uint32_t i = 0; i < nfat_arch; ++i) {
1351 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1352 uint32_t cputype = OFA.getCPUType();
1353 uint32_t cpusubtype = OFA.getCPUSubType();
1354 outs() << "architecture ";
1355 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1356 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1357 uint32_t other_cputype = other_OFA.getCPUType();
1358 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001359 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001360 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001361 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001362 outs() << "(illegal duplicate architecture) ";
1363 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001364 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001365 }
1366 if (verbose) {
1367 outs() << OFA.getArchTypeName() << "\n";
1368 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1369 } else {
1370 outs() << i << "\n";
1371 outs() << " cputype " << cputype << "\n";
1372 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1373 << "\n";
1374 }
1375 if (verbose &&
1376 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1377 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1378 else
1379 outs() << " capabilities "
1380 << format("0x%" PRIx32,
1381 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1382 outs() << " offset " << OFA.getOffset();
1383 if (OFA.getOffset() > size)
1384 outs() << " (past end of file)";
1385 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1386 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1387 outs() << "\n";
1388 outs() << " size " << OFA.getSize();
1389 big_size = OFA.getOffset() + OFA.getSize();
1390 if (big_size > size)
1391 outs() << " (past end of file)";
1392 outs() << "\n";
1393 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1394 << ")\n";
1395 }
1396}
1397
Kevin Enderby13023a12015-01-15 23:19:11 +00001398static void printArchiveChild(Archive::Child &C, bool verbose,
1399 bool print_offset) {
1400 if (print_offset)
1401 outs() << C.getChildOffset() << "\t";
1402 sys::fs::perms Mode = C.getAccessMode();
1403 if (verbose) {
1404 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1405 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1406 outs() << "-";
1407 if (Mode & sys::fs::owner_read)
1408 outs() << "r";
1409 else
1410 outs() << "-";
1411 if (Mode & sys::fs::owner_write)
1412 outs() << "w";
1413 else
1414 outs() << "-";
1415 if (Mode & sys::fs::owner_exe)
1416 outs() << "x";
1417 else
1418 outs() << "-";
1419 if (Mode & sys::fs::group_read)
1420 outs() << "r";
1421 else
1422 outs() << "-";
1423 if (Mode & sys::fs::group_write)
1424 outs() << "w";
1425 else
1426 outs() << "-";
1427 if (Mode & sys::fs::group_exe)
1428 outs() << "x";
1429 else
1430 outs() << "-";
1431 if (Mode & sys::fs::others_read)
1432 outs() << "r";
1433 else
1434 outs() << "-";
1435 if (Mode & sys::fs::others_write)
1436 outs() << "w";
1437 else
1438 outs() << "-";
1439 if (Mode & sys::fs::others_exe)
1440 outs() << "x";
1441 else
1442 outs() << "-";
1443 } else {
1444 outs() << format("0%o ", Mode);
1445 }
1446
1447 unsigned UID = C.getUID();
1448 outs() << format("%3d/", UID);
1449 unsigned GID = C.getGID();
1450 outs() << format("%-3d ", GID);
Kevin Enderbyc12718932015-01-16 22:10:36 +00001451 uint64_t Size = C.getRawSize();
Kevin Enderby479ee612015-01-23 21:02:44 +00001452 outs() << format("%5" PRId64, Size) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001453
1454 StringRef RawLastModified = C.getRawLastModified();
1455 if (verbose) {
1456 unsigned Seconds;
1457 if (RawLastModified.getAsInteger(10, Seconds))
1458 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1459 else {
1460 // Since cime(3) returns a 26 character string of the form:
1461 // "Sun Sep 16 01:03:52 1973\n\0"
1462 // just print 24 characters.
1463 time_t t = Seconds;
1464 outs() << format("%.24s ", ctime(&t));
1465 }
1466 } else {
1467 outs() << RawLastModified << " ";
1468 }
1469
1470 if (verbose) {
1471 ErrorOr<StringRef> NameOrErr = C.getName();
1472 if (NameOrErr.getError()) {
1473 StringRef RawName = C.getRawName();
1474 outs() << RawName << "\n";
1475 } else {
1476 StringRef Name = NameOrErr.get();
1477 outs() << Name << "\n";
1478 }
1479 } else {
1480 StringRef RawName = C.getRawName();
1481 outs() << RawName << "\n";
1482 }
1483}
1484
1485static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1486 if (A->hasSymbolTable()) {
1487 Archive::child_iterator S = A->getSymbolTableChild();
1488 Archive::Child C = *S;
1489 printArchiveChild(C, verbose, print_offset);
1490 }
1491 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1492 ++I) {
1493 Archive::Child C = *I;
1494 printArchiveChild(C, verbose, print_offset);
1495 }
1496}
1497
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001498// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1499// -arch flags selecting just those slices as specified by them and also parses
1500// archive files. Then for each individual Mach-O file ProcessMachO() is
1501// called to process the file based on the command line options.
1502void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001503 // Check for -arch all and verifiy the -arch flags are valid.
1504 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1505 if (ArchFlags[i] == "all") {
1506 ArchAll = true;
1507 } else {
1508 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1509 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1510 "'for the -arch option\n";
1511 return;
1512 }
1513 }
1514 }
1515
1516 // Attempt to open the binary.
1517 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1518 if (std::error_code EC = BinaryOrErr.getError()) {
1519 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +00001520 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001521 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001522 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001523
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001524 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1525 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001526 if (ArchiveHeaders)
1527 printArchiveHeaders(A, true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001528 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1529 I != E; ++I) {
1530 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1531 if (ChildOrErr.getError())
1532 continue;
1533 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1534 if (!checkMachOAndArchFlags(O, Filename))
1535 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001536 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001537 }
1538 }
1539 return;
1540 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001541 if (UniversalHeaders) {
1542 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001543 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001544 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001545 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1546 // If we have a list of architecture flags specified dump only those.
1547 if (!ArchAll && ArchFlags.size() != 0) {
1548 // Look for a slice in the universal binary that matches each ArchFlag.
1549 bool ArchFound;
1550 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1551 ArchFound = false;
1552 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1553 E = UB->end_objects();
1554 I != E; ++I) {
1555 if (ArchFlags[i] == I->getArchTypeName()) {
1556 ArchFound = true;
1557 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1558 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001559 std::string ArchitectureName = "";
1560 if (ArchFlags.size() > 1)
1561 ArchitectureName = I->getArchTypeName();
1562 if (ObjOrErr) {
1563 ObjectFile &O = *ObjOrErr.get();
1564 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001565 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001566 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1567 I->getAsArchive()) {
1568 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001569 outs() << "Archive : " << Filename;
1570 if (!ArchitectureName.empty())
1571 outs() << " (architecture " << ArchitectureName << ")";
1572 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001573 if (ArchiveHeaders)
1574 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001575 for (Archive::child_iterator AI = A->child_begin(),
1576 AE = A->child_end();
1577 AI != AE; ++AI) {
1578 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1579 if (ChildOrErr.getError())
1580 continue;
1581 if (MachOObjectFile *O =
1582 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001583 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001584 }
1585 }
1586 }
1587 }
1588 if (!ArchFound) {
1589 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1590 << "architecture: " + ArchFlags[i] + "\n";
1591 return;
1592 }
1593 }
1594 return;
1595 }
1596 // No architecture flags were specified so if this contains a slice that
1597 // matches the host architecture dump only that.
1598 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001599 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1600 E = UB->end_objects();
1601 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001602 if (MachOObjectFile::getHostArch().getArchName() ==
1603 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001604 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001605 std::string ArchiveName;
1606 ArchiveName.clear();
1607 if (ObjOrErr) {
1608 ObjectFile &O = *ObjOrErr.get();
1609 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001610 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001611 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1612 I->getAsArchive()) {
1613 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001614 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001615 if (ArchiveHeaders)
1616 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001617 for (Archive::child_iterator AI = A->child_begin(),
1618 AE = A->child_end();
1619 AI != AE; ++AI) {
1620 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1621 if (ChildOrErr.getError())
1622 continue;
1623 if (MachOObjectFile *O =
1624 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001625 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001626 }
1627 }
1628 return;
1629 }
1630 }
1631 }
1632 // Either all architectures have been specified or none have been specified
1633 // and this does not contain the host architecture so dump all the slices.
1634 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1635 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1636 E = UB->end_objects();
1637 I != E; ++I) {
1638 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001639 std::string ArchitectureName = "";
1640 if (moreThanOneArch)
1641 ArchitectureName = I->getArchTypeName();
1642 if (ObjOrErr) {
1643 ObjectFile &Obj = *ObjOrErr.get();
1644 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001645 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001646 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1647 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001648 outs() << "Archive : " << Filename;
1649 if (!ArchitectureName.empty())
1650 outs() << " (architecture " << ArchitectureName << ")";
1651 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001652 if (ArchiveHeaders)
1653 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001654 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1655 AI != AE; ++AI) {
1656 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1657 if (ChildOrErr.getError())
1658 continue;
1659 if (MachOObjectFile *O =
1660 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1661 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001662 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1663 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001664 }
1665 }
1666 }
1667 }
1668 return;
1669 }
1670 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1671 if (!checkMachOAndArchFlags(O, Filename))
1672 return;
1673 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001674 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001675 } else
1676 errs() << "llvm-objdump: '" << Filename << "': "
1677 << "Object is not a Mach-O file type.\n";
1678 } else
1679 errs() << "llvm-objdump: '" << Filename << "': "
1680 << "Unrecognized file type.\n";
Rafael Espindola9b709252013-04-13 01:45:40 +00001681}
1682
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001683typedef std::pair<uint64_t, const char *> BindInfoEntry;
1684typedef std::vector<BindInfoEntry> BindTable;
1685typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001686
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001687// The block of info used by the Symbolizer call backs.
1688struct DisassembleInfo {
1689 bool verbose;
1690 MachOObjectFile *O;
1691 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001692 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001693 std::vector<SectionRef> *Sections;
1694 const char *class_name;
1695 const char *selector_name;
1696 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001697 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001698 uint64_t adrp_addr;
1699 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001700 BindTable *bindtable;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001701};
1702
1703// SymbolizerGetOpInfo() is the operand information call back function.
1704// This is called to get the symbolic information for operand(s) of an
1705// instruction when it is being done. This routine does this from
1706// the relocation information, symbol table, etc. That block of information
1707// is a pointer to the struct DisassembleInfo that was passed when the
1708// disassembler context was created and passed to back to here when
1709// called back by the disassembler for instruction operands that could have
1710// relocation information. The address of the instruction containing operand is
1711// at the Pc parameter. The immediate value the operand has is passed in
1712// op_info->Value and is at Offset past the start of the instruction and has a
1713// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1714// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1715// names and addends of the symbolic expression to add for the operand. The
1716// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1717// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001718static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1719 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001720 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1721 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001722 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001723
1724 // Make sure all fields returned are zero if we don't set them.
1725 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1726 op_info->Value = value;
1727
1728 // If the TagType is not the value 1 which it code knows about or if no
1729 // verbose symbolic information is wanted then just return 0, indicating no
1730 // information is being returned.
1731 if (TagType != 1 || info->verbose == false)
1732 return 0;
1733
1734 unsigned int Arch = info->O->getArch();
1735 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001736 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1737 return 0;
1738 // First search the section's relocation entries (if any) for an entry
1739 // for this section offset.
1740 uint32_t sect_addr = info->S.getAddress();
1741 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1742 bool reloc_found = false;
1743 DataRefImpl Rel;
1744 MachO::any_relocation_info RE;
1745 bool isExtern = false;
1746 SymbolRef Symbol;
1747 bool r_scattered = false;
1748 uint32_t r_value, pair_r_value, r_type;
1749 for (const RelocationRef &Reloc : info->S.relocations()) {
1750 uint64_t RelocOffset;
1751 Reloc.getOffset(RelocOffset);
1752 if (RelocOffset == sect_offset) {
1753 Rel = Reloc.getRawDataRefImpl();
1754 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001755 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001756 r_scattered = info->O->isRelocationScattered(RE);
1757 if (r_scattered) {
1758 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001759 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1760 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1761 DataRefImpl RelNext = Rel;
1762 info->O->moveRelocationNext(RelNext);
1763 MachO::any_relocation_info RENext;
1764 RENext = info->O->getRelocation(RelNext);
1765 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001766 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001767 else
1768 return 0;
1769 }
1770 } else {
1771 isExtern = info->O->getPlainRelocationExternal(RE);
1772 if (isExtern) {
1773 symbol_iterator RelocSym = Reloc.getSymbol();
1774 Symbol = *RelocSym;
1775 }
1776 }
1777 reloc_found = true;
1778 break;
1779 }
1780 }
1781 if (reloc_found && isExtern) {
1782 StringRef SymName;
1783 Symbol.getName(SymName);
1784 const char *name = SymName.data();
1785 op_info->AddSymbol.Present = 1;
1786 op_info->AddSymbol.Name = name;
1787 // For i386 extern relocation entries the value in the instruction is
1788 // the offset from the symbol, and value is already set in op_info->Value.
1789 return 1;
1790 }
1791 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1792 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001793 const char *add = GuessSymbolName(r_value, info->AddrMap);
1794 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001795 uint32_t offset = value - (r_value - pair_r_value);
1796 op_info->AddSymbol.Present = 1;
1797 if (add != nullptr)
1798 op_info->AddSymbol.Name = add;
1799 else
1800 op_info->AddSymbol.Value = r_value;
1801 op_info->SubtractSymbol.Present = 1;
1802 if (sub != nullptr)
1803 op_info->SubtractSymbol.Name = sub;
1804 else
1805 op_info->SubtractSymbol.Value = pair_r_value;
1806 op_info->Value = offset;
1807 return 1;
1808 }
1809 // TODO:
1810 // Second search the external relocation entries of a fully linked image
1811 // (if any) for an entry that matches this segment offset.
1812 // uint32_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001813 return 0;
1814 } else if (Arch == Triple::x86_64) {
1815 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1816 return 0;
1817 // First search the section's relocation entries (if any) for an entry
1818 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001819 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001820 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1821 bool reloc_found = false;
1822 DataRefImpl Rel;
1823 MachO::any_relocation_info RE;
1824 bool isExtern = false;
1825 SymbolRef Symbol;
1826 for (const RelocationRef &Reloc : info->S.relocations()) {
1827 uint64_t RelocOffset;
1828 Reloc.getOffset(RelocOffset);
1829 if (RelocOffset == sect_offset) {
1830 Rel = Reloc.getRawDataRefImpl();
1831 RE = info->O->getRelocation(Rel);
1832 // NOTE: Scattered relocations don't exist on x86_64.
1833 isExtern = info->O->getPlainRelocationExternal(RE);
1834 if (isExtern) {
1835 symbol_iterator RelocSym = Reloc.getSymbol();
1836 Symbol = *RelocSym;
1837 }
1838 reloc_found = true;
1839 break;
1840 }
1841 }
1842 if (reloc_found && isExtern) {
1843 // The Value passed in will be adjusted by the Pc if the instruction
1844 // adds the Pc. But for x86_64 external relocation entries the Value
1845 // is the offset from the external symbol.
1846 if (info->O->getAnyRelocationPCRel(RE))
1847 op_info->Value -= Pc + Offset + Size;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001848 StringRef SymName;
1849 Symbol.getName(SymName);
1850 const char *name = SymName.data();
1851 unsigned Type = info->O->getAnyRelocationType(RE);
1852 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1853 DataRefImpl RelNext = Rel;
1854 info->O->moveRelocationNext(RelNext);
1855 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1856 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1857 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1858 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1859 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1860 op_info->SubtractSymbol.Present = 1;
1861 op_info->SubtractSymbol.Name = name;
1862 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1863 Symbol = *RelocSymNext;
1864 StringRef SymNameNext;
1865 Symbol.getName(SymNameNext);
1866 name = SymNameNext.data();
1867 }
1868 }
1869 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1870 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1871 op_info->AddSymbol.Present = 1;
1872 op_info->AddSymbol.Name = name;
1873 return 1;
1874 }
1875 // TODO:
1876 // Second search the external relocation entries of a fully linked image
1877 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001878 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001879 return 0;
1880 } else if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001881 if (Offset != 0 || (Size != 4 && Size != 2))
1882 return 0;
1883 // First search the section's relocation entries (if any) for an entry
1884 // for this section offset.
1885 uint32_t sect_addr = info->S.getAddress();
1886 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1887 bool reloc_found = false;
1888 DataRefImpl Rel;
1889 MachO::any_relocation_info RE;
1890 bool isExtern = false;
1891 SymbolRef Symbol;
1892 bool r_scattered = false;
1893 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1894 for (const RelocationRef &Reloc : info->S.relocations()) {
1895 uint64_t RelocOffset;
1896 Reloc.getOffset(RelocOffset);
1897 if (RelocOffset == sect_offset) {
1898 Rel = Reloc.getRawDataRefImpl();
1899 RE = info->O->getRelocation(Rel);
1900 r_length = info->O->getAnyRelocationLength(RE);
1901 r_scattered = info->O->isRelocationScattered(RE);
1902 if (r_scattered) {
1903 r_value = info->O->getScatteredRelocationValue(RE);
1904 r_type = info->O->getScatteredRelocationType(RE);
1905 } else {
1906 r_type = info->O->getAnyRelocationType(RE);
1907 isExtern = info->O->getPlainRelocationExternal(RE);
1908 if (isExtern) {
1909 symbol_iterator RelocSym = Reloc.getSymbol();
1910 Symbol = *RelocSym;
1911 }
1912 }
1913 if (r_type == MachO::ARM_RELOC_HALF ||
1914 r_type == MachO::ARM_RELOC_SECTDIFF ||
1915 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1916 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1917 DataRefImpl RelNext = Rel;
1918 info->O->moveRelocationNext(RelNext);
1919 MachO::any_relocation_info RENext;
1920 RENext = info->O->getRelocation(RelNext);
1921 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1922 if (info->O->isRelocationScattered(RENext))
1923 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1924 }
1925 reloc_found = true;
1926 break;
1927 }
1928 }
1929 if (reloc_found && isExtern) {
1930 StringRef SymName;
1931 Symbol.getName(SymName);
1932 const char *name = SymName.data();
1933 op_info->AddSymbol.Present = 1;
1934 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001935 switch (r_type) {
1936 case MachO::ARM_RELOC_HALF:
1937 if ((r_length & 0x1) == 1) {
1938 op_info->Value = value << 16 | other_half;
1939 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1940 } else {
1941 op_info->Value = other_half << 16 | value;
1942 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001943 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001944 break;
1945 default:
1946 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001947 }
1948 return 1;
1949 }
1950 // If we have a branch that is not an external relocation entry then
1951 // return 0 so the code in tryAddingSymbolicOperand() can use the
1952 // SymbolLookUp call back with the branch target address to look up the
1953 // symbol and possiblity add an annotation for a symbol stub.
1954 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1955 r_type == MachO::ARM_THUMB_RELOC_BR22))
1956 return 0;
1957
1958 uint32_t offset = 0;
1959 if (reloc_found) {
1960 if (r_type == MachO::ARM_RELOC_HALF ||
1961 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1962 if ((r_length & 0x1) == 1)
1963 value = value << 16 | other_half;
1964 else
1965 value = other_half << 16 | value;
1966 }
1967 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1968 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1969 offset = value - r_value;
1970 value = r_value;
1971 }
1972 }
1973
1974 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1975 if ((r_length & 0x1) == 1)
1976 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1977 else
1978 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001979 const char *add = GuessSymbolName(r_value, info->AddrMap);
1980 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001981 int32_t offset = value - (r_value - pair_r_value);
1982 op_info->AddSymbol.Present = 1;
1983 if (add != nullptr)
1984 op_info->AddSymbol.Name = add;
1985 else
1986 op_info->AddSymbol.Value = r_value;
1987 op_info->SubtractSymbol.Present = 1;
1988 if (sub != nullptr)
1989 op_info->SubtractSymbol.Name = sub;
1990 else
1991 op_info->SubtractSymbol.Value = pair_r_value;
1992 op_info->Value = offset;
1993 return 1;
1994 }
1995
1996 if (reloc_found == false)
1997 return 0;
1998
1999 op_info->AddSymbol.Present = 1;
2000 op_info->Value = offset;
2001 if (reloc_found) {
2002 if (r_type == MachO::ARM_RELOC_HALF) {
2003 if ((r_length & 0x1) == 1)
2004 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2005 else
2006 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2007 }
2008 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002009 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002010 if (add != nullptr) {
2011 op_info->AddSymbol.Name = add;
2012 return 1;
2013 }
2014 op_info->AddSymbol.Value = value;
2015 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002016 } else if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002017 if (Offset != 0 || Size != 4)
2018 return 0;
2019 // First search the section's relocation entries (if any) for an entry
2020 // for this section offset.
2021 uint64_t sect_addr = info->S.getAddress();
2022 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2023 bool reloc_found = false;
2024 DataRefImpl Rel;
2025 MachO::any_relocation_info RE;
2026 bool isExtern = false;
2027 SymbolRef Symbol;
2028 uint32_t r_type = 0;
2029 for (const RelocationRef &Reloc : info->S.relocations()) {
2030 uint64_t RelocOffset;
2031 Reloc.getOffset(RelocOffset);
2032 if (RelocOffset == sect_offset) {
2033 Rel = Reloc.getRawDataRefImpl();
2034 RE = info->O->getRelocation(Rel);
2035 r_type = info->O->getAnyRelocationType(RE);
2036 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2037 DataRefImpl RelNext = Rel;
2038 info->O->moveRelocationNext(RelNext);
2039 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2040 if (value == 0) {
2041 value = info->O->getPlainRelocationSymbolNum(RENext);
2042 op_info->Value = value;
2043 }
2044 }
2045 // NOTE: Scattered relocations don't exist on arm64.
2046 isExtern = info->O->getPlainRelocationExternal(RE);
2047 if (isExtern) {
2048 symbol_iterator RelocSym = Reloc.getSymbol();
2049 Symbol = *RelocSym;
2050 }
2051 reloc_found = true;
2052 break;
2053 }
2054 }
2055 if (reloc_found && isExtern) {
2056 StringRef SymName;
2057 Symbol.getName(SymName);
2058 const char *name = SymName.data();
2059 op_info->AddSymbol.Present = 1;
2060 op_info->AddSymbol.Name = name;
2061
2062 switch (r_type) {
2063 case MachO::ARM64_RELOC_PAGE21:
2064 /* @page */
2065 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2066 break;
2067 case MachO::ARM64_RELOC_PAGEOFF12:
2068 /* @pageoff */
2069 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2070 break;
2071 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2072 /* @gotpage */
2073 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2074 break;
2075 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2076 /* @gotpageoff */
2077 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2078 break;
2079 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2080 /* @tvlppage is not implemented in llvm-mc */
2081 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2082 break;
2083 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2084 /* @tvlppageoff is not implemented in llvm-mc */
2085 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2086 break;
2087 default:
2088 case MachO::ARM64_RELOC_BRANCH26:
2089 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2090 break;
2091 }
2092 return 1;
2093 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002094 return 0;
2095 } else {
2096 return 0;
2097 }
2098}
2099
Kevin Enderbybf246f52014-09-24 23:08:22 +00002100// GuessCstringPointer is passed the address of what might be a pointer to a
2101// literal string in a cstring section. If that address is in a cstring section
2102// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002103static const char *GuessCstringPointer(uint64_t ReferenceValue,
2104 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002105 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2106 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2107 for (unsigned I = 0;; ++I) {
2108 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2109 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2110 for (unsigned J = 0; J < Seg.nsects; ++J) {
2111 MachO::section_64 Sec = info->O->getSection64(Load, J);
2112 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2113 if (section_type == MachO::S_CSTRING_LITERALS &&
2114 ReferenceValue >= Sec.addr &&
2115 ReferenceValue < Sec.addr + Sec.size) {
2116 uint64_t sect_offset = ReferenceValue - Sec.addr;
2117 uint64_t object_offset = Sec.offset + sect_offset;
2118 StringRef MachOContents = info->O->getData();
2119 uint64_t object_size = MachOContents.size();
2120 const char *object_addr = (const char *)MachOContents.data();
2121 if (object_offset < object_size) {
2122 const char *name = object_addr + object_offset;
2123 return name;
2124 } else {
2125 return nullptr;
2126 }
2127 }
2128 }
2129 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2130 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2131 for (unsigned J = 0; J < Seg.nsects; ++J) {
2132 MachO::section Sec = info->O->getSection(Load, J);
2133 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2134 if (section_type == MachO::S_CSTRING_LITERALS &&
2135 ReferenceValue >= Sec.addr &&
2136 ReferenceValue < Sec.addr + Sec.size) {
2137 uint64_t sect_offset = ReferenceValue - Sec.addr;
2138 uint64_t object_offset = Sec.offset + sect_offset;
2139 StringRef MachOContents = info->O->getData();
2140 uint64_t object_size = MachOContents.size();
2141 const char *object_addr = (const char *)MachOContents.data();
2142 if (object_offset < object_size) {
2143 const char *name = object_addr + object_offset;
2144 return name;
2145 } else {
2146 return nullptr;
2147 }
2148 }
2149 }
2150 }
2151 if (I == LoadCommandCount - 1)
2152 break;
2153 else
2154 Load = info->O->getNextLoadCommandInfo(Load);
2155 }
2156 return nullptr;
2157}
2158
Kevin Enderby85974882014-09-26 22:20:44 +00002159// GuessIndirectSymbol returns the name of the indirect symbol for the
2160// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2161// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2162// symbol name being referenced by the stub or pointer.
2163static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2164 struct DisassembleInfo *info) {
2165 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2166 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2167 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2168 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2169 for (unsigned I = 0;; ++I) {
2170 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2171 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2172 for (unsigned J = 0; J < Seg.nsects; ++J) {
2173 MachO::section_64 Sec = info->O->getSection64(Load, J);
2174 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2175 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2176 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2177 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2178 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2179 section_type == MachO::S_SYMBOL_STUBS) &&
2180 ReferenceValue >= Sec.addr &&
2181 ReferenceValue < Sec.addr + Sec.size) {
2182 uint32_t stride;
2183 if (section_type == MachO::S_SYMBOL_STUBS)
2184 stride = Sec.reserved2;
2185 else
2186 stride = 8;
2187 if (stride == 0)
2188 return nullptr;
2189 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2190 if (index < Dysymtab.nindirectsyms) {
2191 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002192 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002193 if (indirect_symbol < Symtab.nsyms) {
2194 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2195 SymbolRef Symbol = *Sym;
2196 StringRef SymName;
2197 Symbol.getName(SymName);
2198 const char *name = SymName.data();
2199 return name;
2200 }
2201 }
2202 }
2203 }
2204 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2205 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2206 for (unsigned J = 0; J < Seg.nsects; ++J) {
2207 MachO::section Sec = info->O->getSection(Load, J);
2208 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2209 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2210 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2211 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2212 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2213 section_type == MachO::S_SYMBOL_STUBS) &&
2214 ReferenceValue >= Sec.addr &&
2215 ReferenceValue < Sec.addr + Sec.size) {
2216 uint32_t stride;
2217 if (section_type == MachO::S_SYMBOL_STUBS)
2218 stride = Sec.reserved2;
2219 else
2220 stride = 4;
2221 if (stride == 0)
2222 return nullptr;
2223 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2224 if (index < Dysymtab.nindirectsyms) {
2225 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002226 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002227 if (indirect_symbol < Symtab.nsyms) {
2228 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2229 SymbolRef Symbol = *Sym;
2230 StringRef SymName;
2231 Symbol.getName(SymName);
2232 const char *name = SymName.data();
2233 return name;
2234 }
2235 }
2236 }
2237 }
2238 }
2239 if (I == LoadCommandCount - 1)
2240 break;
2241 else
2242 Load = info->O->getNextLoadCommandInfo(Load);
2243 }
2244 return nullptr;
2245}
2246
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002247// method_reference() is called passing it the ReferenceName that might be
2248// a reference it to an Objective-C method call. If so then it allocates and
2249// assembles a method call string with the values last seen and saved in
2250// the DisassembleInfo's class_name and selector_name fields. This is saved
2251// into the method field of the info and any previous string is free'ed.
2252// Then the class_name field in the info is set to nullptr. The method call
2253// string is set into ReferenceName and ReferenceType is set to
2254// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2255// then both ReferenceType and ReferenceName are left unchanged.
2256static void method_reference(struct DisassembleInfo *info,
2257 uint64_t *ReferenceType,
2258 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002259 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002260 if (*ReferenceName != nullptr) {
2261 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002262 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002263 if (info->method != nullptr)
2264 free(info->method);
2265 if (info->class_name != nullptr) {
2266 info->method = (char *)malloc(5 + strlen(info->class_name) +
2267 strlen(info->selector_name));
2268 if (info->method != nullptr) {
2269 strcpy(info->method, "+[");
2270 strcat(info->method, info->class_name);
2271 strcat(info->method, " ");
2272 strcat(info->method, info->selector_name);
2273 strcat(info->method, "]");
2274 *ReferenceName = info->method;
2275 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2276 }
2277 } else {
2278 info->method = (char *)malloc(9 + strlen(info->selector_name));
2279 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002280 if (Arch == Triple::x86_64)
2281 strcpy(info->method, "-[%rdi ");
2282 else if (Arch == Triple::aarch64)
2283 strcpy(info->method, "-[x0 ");
2284 else
2285 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002286 strcat(info->method, info->selector_name);
2287 strcat(info->method, "]");
2288 *ReferenceName = info->method;
2289 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2290 }
2291 }
2292 info->class_name = nullptr;
2293 }
2294 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002295 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002296 if (info->method != nullptr)
2297 free(info->method);
2298 info->method = (char *)malloc(17 + strlen(info->selector_name));
2299 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002300 if (Arch == Triple::x86_64)
2301 strcpy(info->method, "-[[%rdi super] ");
2302 else if (Arch == Triple::aarch64)
2303 strcpy(info->method, "-[[x0 super] ");
2304 else
2305 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002306 strcat(info->method, info->selector_name);
2307 strcat(info->method, "]");
2308 *ReferenceName = info->method;
2309 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2310 }
2311 info->class_name = nullptr;
2312 }
2313 }
2314 }
2315}
2316
2317// GuessPointerPointer() is passed the address of what might be a pointer to
2318// a reference to an Objective-C class, selector, message ref or cfstring.
2319// If so the value of the pointer is returned and one of the booleans are set
2320// to true. If not zero is returned and all the booleans are set to false.
2321static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2322 struct DisassembleInfo *info,
2323 bool &classref, bool &selref, bool &msgref,
2324 bool &cfstring) {
2325 classref = false;
2326 selref = false;
2327 msgref = false;
2328 cfstring = false;
2329 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2330 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2331 for (unsigned I = 0;; ++I) {
2332 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2333 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2334 for (unsigned J = 0; J < Seg.nsects; ++J) {
2335 MachO::section_64 Sec = info->O->getSection64(Load, J);
2336 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2337 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2338 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2339 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2340 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2341 ReferenceValue >= Sec.addr &&
2342 ReferenceValue < Sec.addr + Sec.size) {
2343 uint64_t sect_offset = ReferenceValue - Sec.addr;
2344 uint64_t object_offset = Sec.offset + sect_offset;
2345 StringRef MachOContents = info->O->getData();
2346 uint64_t object_size = MachOContents.size();
2347 const char *object_addr = (const char *)MachOContents.data();
2348 if (object_offset < object_size) {
2349 uint64_t pointer_value;
2350 memcpy(&pointer_value, object_addr + object_offset,
2351 sizeof(uint64_t));
2352 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2353 sys::swapByteOrder(pointer_value);
2354 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2355 selref = true;
2356 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2357 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2358 classref = true;
2359 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2360 ReferenceValue + 8 < Sec.addr + Sec.size) {
2361 msgref = true;
2362 memcpy(&pointer_value, object_addr + object_offset + 8,
2363 sizeof(uint64_t));
2364 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2365 sys::swapByteOrder(pointer_value);
2366 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2367 cfstring = true;
2368 return pointer_value;
2369 } else {
2370 return 0;
2371 }
2372 }
2373 }
2374 }
2375 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2376 if (I == LoadCommandCount - 1)
2377 break;
2378 else
2379 Load = info->O->getNextLoadCommandInfo(Load);
2380 }
2381 return 0;
2382}
2383
2384// get_pointer_64 returns a pointer to the bytes in the object file at the
2385// Address from a section in the Mach-O file. And indirectly returns the
2386// offset into the section, number of bytes left in the section past the offset
2387// and which section is was being referenced. If the Address is not in a
2388// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002389static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2390 uint32_t &left, SectionRef &S,
2391 DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002392 offset = 0;
2393 left = 0;
2394 S = SectionRef();
2395 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2396 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2397 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2398 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2399 S = (*(info->Sections))[SectIdx];
2400 offset = Address - SectAddress;
2401 left = SectSize - offset;
2402 StringRef SectContents;
2403 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2404 return SectContents.data() + offset;
2405 }
2406 }
2407 return nullptr;
2408}
2409
2410// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2411// the symbol indirectly through n_value. Based on the relocation information
2412// for the specified section offset in the specified section reference.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002413static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2414 DisassembleInfo *info, uint64_t &n_value) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002415 n_value = 0;
2416 if (info->verbose == false)
2417 return nullptr;
2418
2419 // See if there is an external relocation entry at the sect_offset.
2420 bool reloc_found = false;
2421 DataRefImpl Rel;
2422 MachO::any_relocation_info RE;
2423 bool isExtern = false;
2424 SymbolRef Symbol;
2425 for (const RelocationRef &Reloc : S.relocations()) {
2426 uint64_t RelocOffset;
2427 Reloc.getOffset(RelocOffset);
2428 if (RelocOffset == sect_offset) {
2429 Rel = Reloc.getRawDataRefImpl();
2430 RE = info->O->getRelocation(Rel);
2431 if (info->O->isRelocationScattered(RE))
2432 continue;
2433 isExtern = info->O->getPlainRelocationExternal(RE);
2434 if (isExtern) {
2435 symbol_iterator RelocSym = Reloc.getSymbol();
2436 Symbol = *RelocSym;
2437 }
2438 reloc_found = true;
2439 break;
2440 }
2441 }
2442 // If there is an external relocation entry for a symbol in this section
2443 // at this section_offset then use that symbol's value for the n_value
2444 // and return its name.
2445 const char *SymbolName = nullptr;
2446 if (reloc_found && isExtern) {
2447 Symbol.getAddress(n_value);
2448 StringRef name;
2449 Symbol.getName(name);
2450 if (!name.empty()) {
2451 SymbolName = name.data();
2452 return SymbolName;
2453 }
2454 }
2455
2456 // TODO: For fully linked images, look through the external relocation
2457 // entries off the dynamic symtab command. For these the r_offset is from the
2458 // start of the first writeable segment in the Mach-O file. So the offset
2459 // to this section from that segment is passed to this routine by the caller,
2460 // as the database_offset. Which is the difference of the section's starting
2461 // address and the first writable segment.
2462 //
2463 // NOTE: need add passing the database_offset to this routine.
2464
2465 // TODO: We did not find an external relocation entry so look up the
2466 // ReferenceValue as an address of a symbol and if found return that symbol's
2467 // name.
2468 //
2469 // NOTE: need add passing the ReferenceValue to this routine. Then that code
2470 // would simply be this:
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002471 // SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002472
2473 return SymbolName;
2474}
2475
2476// These are structs in the Objective-C meta data and read to produce the
2477// comments for disassembly. While these are part of the ABI they are no
2478// public defintions. So the are here not in include/llvm/Support/MachO.h .
2479
2480// The cfstring object in a 64-bit Mach-O file.
2481struct cfstring64_t {
2482 uint64_t isa; // class64_t * (64-bit pointer)
2483 uint64_t flags; // flag bits
2484 uint64_t characters; // char * (64-bit pointer)
2485 uint64_t length; // number of non-NULL characters in above
2486};
2487
2488// The class object in a 64-bit Mach-O file.
2489struct class64_t {
2490 uint64_t isa; // class64_t * (64-bit pointer)
2491 uint64_t superclass; // class64_t * (64-bit pointer)
2492 uint64_t cache; // Cache (64-bit pointer)
2493 uint64_t vtable; // IMP * (64-bit pointer)
2494 uint64_t data; // class_ro64_t * (64-bit pointer)
2495};
2496
2497struct class_ro64_t {
2498 uint32_t flags;
2499 uint32_t instanceStart;
2500 uint32_t instanceSize;
2501 uint32_t reserved;
2502 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2503 uint64_t name; // const char * (64-bit pointer)
2504 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2505 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2506 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2507 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2508 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2509};
2510
2511inline void swapStruct(struct cfstring64_t &cfs) {
2512 sys::swapByteOrder(cfs.isa);
2513 sys::swapByteOrder(cfs.flags);
2514 sys::swapByteOrder(cfs.characters);
2515 sys::swapByteOrder(cfs.length);
2516}
2517
2518inline void swapStruct(struct class64_t &c) {
2519 sys::swapByteOrder(c.isa);
2520 sys::swapByteOrder(c.superclass);
2521 sys::swapByteOrder(c.cache);
2522 sys::swapByteOrder(c.vtable);
2523 sys::swapByteOrder(c.data);
2524}
2525
2526inline void swapStruct(struct class_ro64_t &cro) {
2527 sys::swapByteOrder(cro.flags);
2528 sys::swapByteOrder(cro.instanceStart);
2529 sys::swapByteOrder(cro.instanceSize);
2530 sys::swapByteOrder(cro.reserved);
2531 sys::swapByteOrder(cro.ivarLayout);
2532 sys::swapByteOrder(cro.name);
2533 sys::swapByteOrder(cro.baseMethods);
2534 sys::swapByteOrder(cro.baseProtocols);
2535 sys::swapByteOrder(cro.ivars);
2536 sys::swapByteOrder(cro.weakIvarLayout);
2537 sys::swapByteOrder(cro.baseProperties);
2538}
2539
2540static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2541 struct DisassembleInfo *info);
2542
2543// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2544// to an Objective-C class and returns the class name. It is also passed the
2545// address of the pointer, so when the pointer is zero as it can be in an .o
2546// file, that is used to look for an external relocation entry with a symbol
2547// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002548static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2549 uint64_t ReferenceValue,
2550 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002551 const char *r;
2552 uint32_t offset, left;
2553 SectionRef S;
2554
2555 // The pointer_value can be 0 in an object file and have a relocation
2556 // entry for the class symbol at the ReferenceValue (the address of the
2557 // pointer).
2558 if (pointer_value == 0) {
2559 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2560 if (r == nullptr || left < sizeof(uint64_t))
2561 return nullptr;
2562 uint64_t n_value;
2563 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2564 if (symbol_name == nullptr)
2565 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00002566 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002567 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2568 return class_name + 2;
2569 else
2570 return nullptr;
2571 }
2572
2573 // The case were the pointer_value is non-zero and points to a class defined
2574 // in this Mach-O file.
2575 r = get_pointer_64(pointer_value, offset, left, S, info);
2576 if (r == nullptr || left < sizeof(struct class64_t))
2577 return nullptr;
2578 struct class64_t c;
2579 memcpy(&c, r, sizeof(struct class64_t));
2580 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2581 swapStruct(c);
2582 if (c.data == 0)
2583 return nullptr;
2584 r = get_pointer_64(c.data, offset, left, S, info);
2585 if (r == nullptr || left < sizeof(struct class_ro64_t))
2586 return nullptr;
2587 struct class_ro64_t cro;
2588 memcpy(&cro, r, sizeof(struct class_ro64_t));
2589 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2590 swapStruct(cro);
2591 if (cro.name == 0)
2592 return nullptr;
2593 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2594 return name;
2595}
2596
2597// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2598// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002599static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2600 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002601 const char *r, *name;
2602 uint32_t offset, left;
2603 SectionRef S;
2604 struct cfstring64_t cfs;
2605 uint64_t cfs_characters;
2606
2607 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2608 if (r == nullptr || left < sizeof(struct cfstring64_t))
2609 return nullptr;
2610 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2611 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2612 swapStruct(cfs);
2613 if (cfs.characters == 0) {
2614 uint64_t n_value;
2615 const char *symbol_name = get_symbol_64(
2616 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2617 if (symbol_name == nullptr)
2618 return nullptr;
2619 cfs_characters = n_value;
2620 } else
2621 cfs_characters = cfs.characters;
2622 name = get_pointer_64(cfs_characters, offset, left, S, info);
2623
2624 return name;
2625}
2626
2627// get_objc2_64bit_selref() is used for disassembly and is passed a the address
2628// of a pointer to an Objective-C selector reference when the pointer value is
2629// zero as in a .o file and is likely to have a external relocation entry with
2630// who's symbol's n_value is the real pointer to the selector name. If that is
2631// the case the real pointer to the selector name is returned else 0 is
2632// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002633static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2634 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002635 uint32_t offset, left;
2636 SectionRef S;
2637
2638 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2639 if (r == nullptr || left < sizeof(uint64_t))
2640 return 0;
2641 uint64_t n_value;
2642 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2643 if (symbol_name == nullptr)
2644 return 0;
2645 return n_value;
2646}
2647
Kevin Enderbybf246f52014-09-24 23:08:22 +00002648// GuessLiteralPointer returns a string which for the item in the Mach-O file
2649// for the address passed in as ReferenceValue for printing as a comment with
2650// the instruction and also returns the corresponding type of that item
2651// indirectly through ReferenceType.
2652//
2653// If ReferenceValue is an address of literal cstring then a pointer to the
2654// cstring is returned and ReferenceType is set to
2655// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2656//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002657// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2658// Class ref that name is returned and the ReferenceType is set accordingly.
2659//
2660// Lastly, literals which are Symbol address in a literal pool are looked for
2661// and if found the symbol name is returned and ReferenceType is set to
2662// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2663//
2664// If there is no item in the Mach-O file for the address passed in as
2665// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002666static const char *GuessLiteralPointer(uint64_t ReferenceValue,
2667 uint64_t ReferencePC,
2668 uint64_t *ReferenceType,
2669 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002670 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00002671 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00002672 uint64_t sect_offset = ReferencePC - sect_addr;
2673 bool reloc_found = false;
2674 DataRefImpl Rel;
2675 MachO::any_relocation_info RE;
2676 bool isExtern = false;
2677 SymbolRef Symbol;
2678 for (const RelocationRef &Reloc : info->S.relocations()) {
2679 uint64_t RelocOffset;
2680 Reloc.getOffset(RelocOffset);
2681 if (RelocOffset == sect_offset) {
2682 Rel = Reloc.getRawDataRefImpl();
2683 RE = info->O->getRelocation(Rel);
2684 if (info->O->isRelocationScattered(RE))
2685 continue;
2686 isExtern = info->O->getPlainRelocationExternal(RE);
2687 if (isExtern) {
2688 symbol_iterator RelocSym = Reloc.getSymbol();
2689 Symbol = *RelocSym;
2690 }
2691 reloc_found = true;
2692 break;
2693 }
2694 }
2695 // If there is an external relocation entry for a symbol in a section
2696 // then used that symbol's value for the value of the reference.
2697 if (reloc_found && isExtern) {
2698 if (info->O->getAnyRelocationPCRel(RE)) {
2699 unsigned Type = info->O->getAnyRelocationType(RE);
2700 if (Type == MachO::X86_64_RELOC_SIGNED) {
2701 Symbol.getAddress(ReferenceValue);
2702 }
2703 }
2704 }
2705
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002706 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2707 // Message refs and Class refs.
2708 bool classref, selref, msgref, cfstring;
2709 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2710 selref, msgref, cfstring);
2711 if (classref == true && pointer_value == 0) {
2712 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2713 // And the pointer_value in that section is typically zero as it will be
2714 // set by dyld as part of the "bind information".
2715 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2716 if (name != nullptr) {
2717 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00002718 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002719 if (class_name != nullptr && class_name[1] == '_' &&
2720 class_name[2] != '\0') {
2721 info->class_name = class_name + 2;
2722 return name;
2723 }
2724 }
2725 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002726
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002727 if (classref == true) {
2728 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2729 const char *name =
2730 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2731 if (name != nullptr)
2732 info->class_name = name;
2733 else
2734 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00002735 return name;
2736 }
2737
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002738 if (cfstring == true) {
2739 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2740 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2741 return name;
2742 }
2743
2744 if (selref == true && pointer_value == 0)
2745 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2746
2747 if (pointer_value != 0)
2748 ReferenceValue = pointer_value;
2749
2750 const char *name = GuessCstringPointer(ReferenceValue, info);
2751 if (name) {
2752 if (pointer_value != 0 && selref == true) {
2753 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2754 info->selector_name = name;
2755 } else if (pointer_value != 0 && msgref == true) {
2756 info->class_name = nullptr;
2757 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2758 info->selector_name = name;
2759 } else
2760 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2761 return name;
2762 }
2763
2764 // Lastly look for an indirect symbol with this ReferenceValue which is in
2765 // a literal pool. If found return that symbol name.
2766 name = GuessIndirectSymbol(ReferenceValue, info);
2767 if (name) {
2768 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2769 return name;
2770 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002771
2772 return nullptr;
2773}
2774
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002775// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00002776// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002777// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2778// is created and returns the symbol name that matches the ReferenceValue or
2779// nullptr if none. The ReferenceType is passed in for the IN type of
2780// reference the instruction is making from the values in defined in the header
2781// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2782// Out type and the ReferenceName will also be set which is added as a comment
2783// to the disassembled instruction.
2784//
Kevin Enderby04bf6932014-10-28 23:39:46 +00002785#if HAVE_CXXABI_H
2786// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002787// returned through ReferenceName and ReferenceType is set to
2788// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00002789#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002790//
2791// When this is called to get a symbol name for a branch target then the
2792// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2793// SymbolValue will be looked for in the indirect symbol table to determine if
2794// it is an address for a symbol stub. If so then the symbol name for that
2795// stub is returned indirectly through ReferenceName and then ReferenceType is
2796// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2797//
Kevin Enderbybf246f52014-09-24 23:08:22 +00002798// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002799// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2800// SymbolValue is checked to be an address of literal pointer, symbol pointer,
2801// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002802// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002803static const char *SymbolizerSymbolLookUp(void *DisInfo,
2804 uint64_t ReferenceValue,
2805 uint64_t *ReferenceType,
2806 uint64_t ReferencePC,
2807 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002808 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002809 // If no verbose symbolic information is wanted then just return nullptr.
2810 if (info->verbose == false) {
2811 *ReferenceName = nullptr;
2812 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002813 return nullptr;
2814 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002815
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002816 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00002817
Kevin Enderby85974882014-09-26 22:20:44 +00002818 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2819 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002820 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002821 method_reference(info, ReferenceType, ReferenceName);
2822 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2823 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2824 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00002825#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002826 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00002827 if (info->demangled_name != nullptr)
2828 free(info->demangled_name);
2829 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002830 info->demangled_name =
2831 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002832 if (info->demangled_name != nullptr) {
2833 *ReferenceName = info->demangled_name;
2834 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2835 } else
2836 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2837 } else
2838#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002839 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2840 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2841 *ReferenceName =
2842 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00002843 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002844 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00002845 else
2846 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002847 // If this is arm64 and the reference is an adrp instruction save the
2848 // instruction, passed in ReferenceValue and the address of the instruction
2849 // for use later if we see and add immediate instruction.
2850 } else if (info->O->getArch() == Triple::aarch64 &&
2851 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2852 info->adrp_inst = ReferenceValue;
2853 info->adrp_addr = ReferencePC;
2854 SymbolName = nullptr;
2855 *ReferenceName = nullptr;
2856 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2857 // If this is arm64 and reference is an add immediate instruction and we
2858 // have
2859 // seen an adrp instruction just before it and the adrp's Xd register
2860 // matches
2861 // this add's Xn register reconstruct the value being referenced and look to
2862 // see if it is a literal pointer. Note the add immediate instruction is
2863 // passed in ReferenceValue.
2864 } else if (info->O->getArch() == Triple::aarch64 &&
2865 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2866 ReferencePC - 4 == info->adrp_addr &&
2867 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2868 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2869 uint32_t addxri_inst;
2870 uint64_t adrp_imm, addxri_imm;
2871
2872 adrp_imm =
2873 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2874 if (info->adrp_inst & 0x0200000)
2875 adrp_imm |= 0xfffffffffc000000LL;
2876
2877 addxri_inst = ReferenceValue;
2878 addxri_imm = (addxri_inst >> 10) & 0xfff;
2879 if (((addxri_inst >> 22) & 0x3) == 1)
2880 addxri_imm <<= 12;
2881
2882 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2883 (adrp_imm << 12) + addxri_imm;
2884
2885 *ReferenceName =
2886 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2887 if (*ReferenceName == nullptr)
2888 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2889 // If this is arm64 and the reference is a load register instruction and we
2890 // have seen an adrp instruction just before it and the adrp's Xd register
2891 // matches this add's Xn register reconstruct the value being referenced and
2892 // look to see if it is a literal pointer. Note the load register
2893 // instruction is passed in ReferenceValue.
2894 } else if (info->O->getArch() == Triple::aarch64 &&
2895 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2896 ReferencePC - 4 == info->adrp_addr &&
2897 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2898 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2899 uint32_t ldrxui_inst;
2900 uint64_t adrp_imm, ldrxui_imm;
2901
2902 adrp_imm =
2903 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2904 if (info->adrp_inst & 0x0200000)
2905 adrp_imm |= 0xfffffffffc000000LL;
2906
2907 ldrxui_inst = ReferenceValue;
2908 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2909
2910 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2911 (adrp_imm << 12) + (ldrxui_imm << 3);
2912
2913 *ReferenceName =
2914 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2915 if (*ReferenceName == nullptr)
2916 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2917 }
2918 // If this arm64 and is an load register (PC-relative) instruction the
2919 // ReferenceValue is the PC plus the immediate value.
2920 else if (info->O->getArch() == Triple::aarch64 &&
2921 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2922 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2923 *ReferenceName =
2924 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2925 if (*ReferenceName == nullptr)
2926 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00002927 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00002928#if HAVE_CXXABI_H
2929 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2930 if (info->demangled_name != nullptr)
2931 free(info->demangled_name);
2932 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002933 info->demangled_name =
2934 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002935 if (info->demangled_name != nullptr) {
2936 *ReferenceName = info->demangled_name;
2937 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2938 }
2939 }
2940#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002941 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002942 *ReferenceName = nullptr;
2943 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2944 }
2945
2946 return SymbolName;
2947}
2948
Kevin Enderbybf246f52014-09-24 23:08:22 +00002949/// \brief Emits the comments that are stored in the CommentStream.
2950/// Each comment in the CommentStream must end with a newline.
2951static void emitComments(raw_svector_ostream &CommentStream,
2952 SmallString<128> &CommentsToEmit,
2953 formatted_raw_ostream &FormattedOS,
2954 const MCAsmInfo &MAI) {
2955 // Flush the stream before taking its content.
2956 CommentStream.flush();
2957 StringRef Comments = CommentsToEmit.str();
2958 // Get the default information for printing a comment.
2959 const char *CommentBegin = MAI.getCommentString();
2960 unsigned CommentColumn = MAI.getCommentColumn();
2961 bool IsFirst = true;
2962 while (!Comments.empty()) {
2963 if (!IsFirst)
2964 FormattedOS << '\n';
2965 // Emit a line of comments.
2966 FormattedOS.PadToColumn(CommentColumn);
2967 size_t Position = Comments.find('\n');
2968 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2969 // Move after the newline character.
2970 Comments = Comments.substr(Position + 1);
2971 IsFirst = false;
2972 }
2973 FormattedOS.flush();
2974
2975 // Tell the comment stream that the vector changed underneath it.
2976 CommentsToEmit.clear();
2977 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002978}
2979
Kevin Enderby95df54c2015-02-04 01:01:38 +00002980static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
2981 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002982 const char *McpuDefault = nullptr;
2983 const Target *ThumbTarget = nullptr;
2984 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002985 if (!TheTarget) {
2986 // GetTarget prints out stuff.
2987 return;
2988 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002989 if (MCPU.empty() && McpuDefault)
2990 MCPU = McpuDefault;
2991
Ahmed Charles56440fd2014-03-06 05:51:42 +00002992 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002993 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002994 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002995 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002996
Kevin Enderbyc9595622014-08-06 23:24:41 +00002997 // Package up features to be passed to target/subtarget
2998 std::string FeaturesStr;
2999 if (MAttrs.size()) {
3000 SubtargetFeatures Features;
3001 for (unsigned i = 0; i != MAttrs.size(); ++i)
3002 Features.AddFeature(MAttrs[i]);
3003 FeaturesStr = Features.getString();
3004 }
3005
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003006 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00003007 std::unique_ptr<const MCRegisterInfo> MRI(
3008 TheTarget->createMCRegInfo(TripleName));
3009 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00003010 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00003011 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00003012 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00003013 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003014 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003015 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003016 std::unique_ptr<MCSymbolizer> Symbolizer;
3017 struct DisassembleInfo SymbolizerInfo;
3018 std::unique_ptr<MCRelocationInfo> RelInfo(
3019 TheTarget->createMCRelocationInfo(TripleName, Ctx));
3020 if (RelInfo) {
3021 Symbolizer.reset(TheTarget->createMCSymbolizer(
3022 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00003023 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003024 DisAsm->setSymbolizer(std::move(Symbolizer));
3025 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003026 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00003027 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
3028 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00003029 // Set the display preference for hex vs. decimal immediates.
3030 IP->setPrintImmHex(PrintImmHex);
3031 // Comment stream and backing vector.
3032 SmallString<128> CommentsToEmit;
3033 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00003034 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
3035 // if it is done then arm64 comments for string literals don't get printed
3036 // and some constant get printed instead and not setting it causes intel
3037 // (32-bit and 64-bit) comments printed with different spacing before the
3038 // comment causing different diffs with the 'C' disassembler library API.
3039 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003040
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003041 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00003042 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003043 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003044 return;
3045 }
3046
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003047 // Set up thumb disassembler.
3048 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
3049 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
3050 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00003051 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003052 std::unique_ptr<MCInstPrinter> ThumbIP;
3053 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00003054 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
3055 struct DisassembleInfo ThumbSymbolizerInfo;
3056 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003057 if (ThumbTarget) {
3058 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
3059 ThumbAsmInfo.reset(
3060 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
3061 ThumbSTI.reset(
3062 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
3063 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
3064 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00003065 MCContext *PtrThumbCtx = ThumbCtx.get();
3066 ThumbRelInfo.reset(
3067 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
3068 if (ThumbRelInfo) {
3069 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
3070 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00003071 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00003072 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
3073 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003074 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
3075 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
3076 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
3077 *ThumbSTI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00003078 // Set the display preference for hex vs. decimal immediates.
3079 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003080 }
3081
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003082 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003083 errs() << "error: couldn't initialize disassembler for target "
3084 << ThumbTripleName << '\n';
3085 return;
3086 }
3087
Charles Davis8bdfafd2013-09-01 04:28:48 +00003088 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003089
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003090 // FIXME: Using the -cfg command line option, this code used to be able to
3091 // annotate relocations with the referenced symbol's name, and if this was
3092 // inside a __[cf]string section, the data it points to. This is now replaced
3093 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00003094 std::vector<SectionRef> Sections;
3095 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003096 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00003097 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003098
Kevin Enderby273ae012013-06-06 17:20:50 +00003099 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
3100 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003101
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003102 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00003103 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003104
Kevin Enderby273ae012013-06-06 17:20:50 +00003105 // Build a data in code table that is sorted on by the address of each entry.
3106 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00003107 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00003108 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00003109 else
3110 BaseAddress = BaseSegmentAddress;
3111 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00003112 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00003113 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00003114 uint32_t Offset;
3115 DI->getOffset(Offset);
3116 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
3117 }
3118 array_pod_sort(Dices.begin(), Dices.end());
3119
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003120#ifndef NDEBUG
3121 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
3122#else
3123 raw_ostream &DebugOut = nulls();
3124#endif
3125
Ahmed Charles56440fd2014-03-06 05:51:42 +00003126 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00003127 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00003128 // Try to find debug info and set up the DIContext for it.
3129 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00003130 // A separate DSym file path was specified, parse it as a macho file,
3131 // get the sections and supply it to the section name parsing machinery.
3132 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00003133 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00003134 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00003135 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00003136 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00003137 return;
3138 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00003139 DbgObj =
3140 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
3141 .get()
3142 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00003143 }
3144
Eric Christopher7370b552012-11-12 21:40:38 +00003145 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00003146 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00003147 }
3148
Kevin Enderby95df54c2015-02-04 01:01:38 +00003149 if (DumpSections.size() == 0)
3150 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00003151
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003152 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00003153 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00003154 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
3155 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003156
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00003157 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003158
Rafael Espindolab0f76a42013-04-05 15:15:22 +00003159 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00003160 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00003161 continue;
3162
Rafael Espindola7fc5b872014-11-12 02:04:27 +00003163 StringRef BytesStr;
3164 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00003165 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
3166 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00003167 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00003168
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003169 bool symbolTableWorked = false;
3170
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003171 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00003172 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
3173 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00003174 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00003175 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00003176 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00003177 RelocOffset -= SectionAddress;
3178
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00003179 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00003180
Rafael Espindola806f0062013-06-05 01:33:53 +00003181 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003182 }
3183 array_pod_sort(Relocs.begin(), Relocs.end());
3184
Kevin Enderbybf246f52014-09-24 23:08:22 +00003185 // Create a map of symbol addresses to symbol names for use by
3186 // the SymbolizerSymbolLookUp() routine.
3187 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00003188 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00003189 for (const SymbolRef &Symbol : MachOOF->symbols()) {
3190 SymbolRef::Type ST;
3191 Symbol.getType(ST);
3192 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
3193 ST == SymbolRef::ST_Other) {
3194 uint64_t Address;
3195 Symbol.getAddress(Address);
3196 StringRef SymName;
3197 Symbol.getName(SymName);
3198 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00003199 if (!DisSymName.empty() && DisSymName == SymName)
3200 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00003201 }
3202 }
Kevin Enderby6a221752015-03-17 17:10:57 +00003203 if (!DisSymName.empty() && DisSymNameFound == false) {
3204 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
3205 return;
3206 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003207 // Set up the block of info used by the Symbolizer call backs.
3208 SymbolizerInfo.verbose = true;
3209 SymbolizerInfo.O = MachOOF;
3210 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00003211 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003212 SymbolizerInfo.Sections = &Sections;
3213 SymbolizerInfo.class_name = nullptr;
3214 SymbolizerInfo.selector_name = nullptr;
3215 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00003216 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00003217 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00003218 SymbolizerInfo.adrp_addr = 0;
3219 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00003220 // Same for the ThumbSymbolizer
3221 ThumbSymbolizerInfo.verbose = true;
3222 ThumbSymbolizerInfo.O = MachOOF;
3223 ThumbSymbolizerInfo.S = Sections[SectIdx];
3224 ThumbSymbolizerInfo.AddrMap = &AddrMap;
3225 ThumbSymbolizerInfo.Sections = &Sections;
3226 ThumbSymbolizerInfo.class_name = nullptr;
3227 ThumbSymbolizerInfo.selector_name = nullptr;
3228 ThumbSymbolizerInfo.method = nullptr;
3229 ThumbSymbolizerInfo.demangled_name = nullptr;
3230 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00003231 ThumbSymbolizerInfo.adrp_addr = 0;
3232 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00003233
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003234 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003235 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00003236 StringRef SymName;
3237 Symbols[SymIdx].getName(SymName);
3238
3239 SymbolRef::Type ST;
3240 Symbols[SymIdx].getType(ST);
3241 if (ST != SymbolRef::ST_Function)
3242 continue;
3243
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003244 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00003245 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00003246 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003247 continue;
3248
Kevin Enderby6a221752015-03-17 17:10:57 +00003249 // If we are only disassembling one symbol see if this is that symbol.
3250 if (!DisSymName.empty() && DisSymName != SymName)
3251 continue;
3252
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003253 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00003254 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00003255 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00003256 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00003257 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00003258
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00003259 // Stop disassembling either at the beginning of the next symbol or at
3260 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00003261 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00003262 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003263 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00003264 while (Symbols.size() > NextSymIdx) {
3265 SymbolRef::Type NextSymType;
3266 Symbols[NextSymIdx].getType(NextSymType);
3267 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00003268 containsNextSym =
3269 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00003270 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00003271 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00003272 break;
3273 }
3274 ++NextSymIdx;
3275 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003276
Rafael Espindola80291272014-10-08 15:28:58 +00003277 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003278 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00003279 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003280
3281 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00003282
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003283 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
3284 bool isThumb =
3285 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
3286
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003287 outs() << SymName << ":\n";
3288 DILineInfo lastLine;
3289 for (uint64_t Index = Start; Index < End; Index += Size) {
3290 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00003291
Kevin Enderbybf246f52014-09-24 23:08:22 +00003292 uint64_t PC = SectAddress + Index;
3293 if (FullLeadingAddr) {
3294 if (MachOOF->is64Bit())
3295 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003296 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00003297 outs() << format("%08" PRIx64, PC);
3298 } else {
3299 outs() << format("%8" PRIx64 ":", PC);
3300 }
3301 if (!NoShowRawInsn)
3302 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00003303
3304 // Check the data in code table here to see if this is data not an
3305 // instruction to be disassembled.
3306 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00003307 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003308 dice_table_iterator DTI =
3309 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
3310 compareDiceTableEntries);
3311 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00003312 uint16_t Length;
3313 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00003314 uint16_t Kind;
3315 DTI->second.getKind(Kind);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00003316 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
3317 Index,
3318 Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00003319 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3320 (PC == (DTI->first + Length - 1)) && (Length & 1))
3321 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00003322 continue;
3323 }
3324
Kevin Enderbybf246f52014-09-24 23:08:22 +00003325 SmallVector<char, 64> AnnotationsBytes;
3326 raw_svector_ostream Annotations(AnnotationsBytes);
3327
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003328 bool gotInst;
3329 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00003330 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003331 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003332 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00003333 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00003334 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003335 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00003336 if (!NoShowRawInsn) {
Aaron Ballman106fd7b2014-11-12 14:01:17 +00003337 DumpBytes(StringRef(
3338 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
Kevin Enderbybf246f52014-09-24 23:08:22 +00003339 }
3340 formatted_raw_ostream FormattedOS(outs());
3341 Annotations.flush();
3342 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003343 if (isThumb)
Kevin Enderbybf246f52014-09-24 23:08:22 +00003344 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00003345 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00003346 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
3347 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00003348
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003349 // Print debug info.
3350 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003351 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003352 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00003353 if (dli != lastLine && dli.Line != 0)
3354 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3355 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003356 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003357 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003358 outs() << "\n";
3359 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003360 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003361 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003362 outs() << format("\t.byte 0x%02x #bad opcode\n",
3363 *(Bytes.data() + Index) & 0xff);
3364 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003365 } else if (Arch == Triple::aarch64) {
3366 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3367 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3368 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3369 (*(Bytes.data() + Index + 3) & 0xff) << 24;
3370 outs() << format("\t.long\t0x%08x\n", opcode);
3371 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003372 } else {
3373 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3374 if (Size == 0)
3375 Size = 1; // skip illegible bytes
3376 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003377 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003378 }
3379 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00003380 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00003381 // Reading the symbol table didn't work, disassemble the whole section.
3382 uint64_t SectAddress = Sections[SectIdx].getAddress();
3383 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00003384 uint64_t InstSize;
3385 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00003386 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00003387
Kevin Enderbybf246f52014-09-24 23:08:22 +00003388 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00003389 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3390 DebugOut, nulls())) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00003391 if (FullLeadingAddr) {
3392 if (MachOOF->is64Bit())
3393 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003394 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00003395 outs() << format("%08" PRIx64, PC);
3396 } else {
3397 outs() << format("%8" PRIx64 ":", PC);
3398 }
3399 if (!NoShowRawInsn) {
3400 outs() << "\t";
Aaron Ballman106fd7b2014-11-12 14:01:17 +00003401 DumpBytes(
3402 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
3403 InstSize));
Kevin Enderbybf246f52014-09-24 23:08:22 +00003404 }
Bill Wendling4e68e062012-07-19 00:17:40 +00003405 IP->printInst(&Inst, outs(), "");
3406 outs() << "\n";
3407 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003408 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003409 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003410 outs() << format("\t.byte 0x%02x #bad opcode\n",
3411 *(Bytes.data() + Index) & 0xff);
3412 InstSize = 1; // skip exactly one illegible byte and move on.
3413 } else {
3414 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3415 if (InstSize == 0)
3416 InstSize = 1; // skip illegible bytes
3417 }
Bill Wendling4e68e062012-07-19 00:17:40 +00003418 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00003419 }
3420 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00003421 // The TripleName's need to be reset if we are called again for a different
3422 // archtecture.
3423 TripleName = "";
3424 ThumbTripleName = "";
3425
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003426 if (SymbolizerInfo.method != nullptr)
3427 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00003428 if (SymbolizerInfo.demangled_name != nullptr)
3429 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00003430 if (SymbolizerInfo.bindtable != nullptr)
3431 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00003432 if (ThumbSymbolizerInfo.method != nullptr)
3433 free(ThumbSymbolizerInfo.method);
3434 if (ThumbSymbolizerInfo.demangled_name != nullptr)
3435 free(ThumbSymbolizerInfo.demangled_name);
3436 if (ThumbSymbolizerInfo.bindtable != nullptr)
3437 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00003438 }
3439}
Tim Northover4bd286a2014-08-01 13:07:19 +00003440
Tim Northover39c70bb2014-08-12 11:52:59 +00003441//===----------------------------------------------------------------------===//
3442// __compact_unwind section dumping
3443//===----------------------------------------------------------------------===//
3444
Tim Northover4bd286a2014-08-01 13:07:19 +00003445namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00003446
3447template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003448 using llvm::support::little;
3449 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00003450
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003451 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3452 Buf += sizeof(T);
3453 return Val;
3454}
Tim Northover39c70bb2014-08-12 11:52:59 +00003455
Tim Northover4bd286a2014-08-01 13:07:19 +00003456struct CompactUnwindEntry {
3457 uint32_t OffsetInSection;
3458
3459 uint64_t FunctionAddr;
3460 uint32_t Length;
3461 uint32_t CompactEncoding;
3462 uint64_t PersonalityAddr;
3463 uint64_t LSDAAddr;
3464
3465 RelocationRef FunctionReloc;
3466 RelocationRef PersonalityReloc;
3467 RelocationRef LSDAReloc;
3468
3469 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003470 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00003471 if (Is64)
3472 read<uint64_t>(Contents.data() + Offset);
3473 else
3474 read<uint32_t>(Contents.data() + Offset);
3475 }
3476
3477private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003478 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00003479 FunctionAddr = readNext<UIntPtr>(Buf);
3480 Length = readNext<uint32_t>(Buf);
3481 CompactEncoding = readNext<uint32_t>(Buf);
3482 PersonalityAddr = readNext<UIntPtr>(Buf);
3483 LSDAAddr = readNext<UIntPtr>(Buf);
3484 }
3485};
3486}
3487
3488/// Given a relocation from __compact_unwind, consisting of the RelocationRef
3489/// and data being relocated, determine the best base Name and Addend to use for
3490/// display purposes.
3491///
3492/// 1. An Extern relocation will directly reference a symbol (and the data is
3493/// then already an addend), so use that.
3494/// 2. Otherwise the data is an offset in the object file's layout; try to find
3495// a symbol before it in the same section, and use the offset from there.
3496/// 3. Finally, if all that fails, fall back to an offset from the start of the
3497/// referenced section.
3498static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3499 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003500 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00003501 StringRef &Name, uint64_t &Addend) {
3502 if (Reloc.getSymbol() != Obj->symbol_end()) {
3503 Reloc.getSymbol()->getName(Name);
3504 Addend = Addr;
3505 return;
3506 }
3507
3508 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3509 SectionRef RelocSection = Obj->getRelocationSection(RE);
3510
Rafael Espindola80291272014-10-08 15:28:58 +00003511 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00003512
3513 auto Sym = Symbols.upper_bound(Addr);
3514 if (Sym == Symbols.begin()) {
3515 // The first symbol in the object is after this reference, the best we can
3516 // do is section-relative notation.
3517 RelocSection.getName(Name);
3518 Addend = Addr - SectionAddr;
3519 return;
3520 }
3521
3522 // Go back one so that SymbolAddress <= Addr.
3523 --Sym;
3524
3525 section_iterator SymSection = Obj->section_end();
3526 Sym->second.getSection(SymSection);
3527 if (RelocSection == *SymSection) {
3528 // There's a valid symbol in the same section before this reference.
3529 Sym->second.getName(Name);
3530 Addend = Addr - Sym->first;
3531 return;
3532 }
3533
3534 // There is a symbol before this reference, but it's in a different
3535 // section. Probably not helpful to mention it, so use the section name.
3536 RelocSection.getName(Name);
3537 Addend = Addr - SectionAddr;
3538}
3539
3540static void printUnwindRelocDest(const MachOObjectFile *Obj,
3541 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003542 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00003543 StringRef Name;
3544 uint64_t Addend;
3545
Tim Northover0b0add52014-09-09 10:45:06 +00003546 if (!Reloc.getObjectFile())
3547 return;
3548
Tim Northover4bd286a2014-08-01 13:07:19 +00003549 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3550
3551 outs() << Name;
3552 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00003553 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00003554}
3555
3556static void
3557printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3558 std::map<uint64_t, SymbolRef> &Symbols,
3559 const SectionRef &CompactUnwind) {
3560
3561 assert(Obj->isLittleEndian() &&
3562 "There should not be a big-endian .o with __compact_unwind");
3563
3564 bool Is64 = Obj->is64Bit();
3565 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3566 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3567
3568 StringRef Contents;
3569 CompactUnwind.getContents(Contents);
3570
3571 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3572
3573 // First populate the initial raw offsets, encodings and so on from the entry.
3574 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3575 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3576 CompactUnwinds.push_back(Entry);
3577 }
3578
3579 // Next we need to look at the relocations to find out what objects are
3580 // actually being referred to.
3581 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3582 uint64_t RelocAddress;
3583 Reloc.getOffset(RelocAddress);
3584
3585 uint32_t EntryIdx = RelocAddress / EntrySize;
3586 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3587 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3588
3589 if (OffsetInEntry == 0)
3590 Entry.FunctionReloc = Reloc;
3591 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3592 Entry.PersonalityReloc = Reloc;
3593 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3594 Entry.LSDAReloc = Reloc;
3595 else
3596 llvm_unreachable("Unexpected relocation in __compact_unwind section");
3597 }
3598
3599 // Finally, we're ready to print the data we've gathered.
3600 outs() << "Contents of __compact_unwind section:\n";
3601 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00003602 outs() << " Entry at offset "
3603 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00003604
3605 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003606 outs() << " start: " << format("0x%" PRIx64,
3607 Entry.FunctionAddr) << ' ';
3608 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00003609 outs() << '\n';
3610
3611 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003612 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3613 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00003614 // 3. The 32-bit compact encoding.
3615 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00003616 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00003617
3618 // 4. The personality function, if present.
3619 if (Entry.PersonalityReloc.getObjectFile()) {
3620 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00003621 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00003622 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3623 Entry.PersonalityAddr);
3624 outs() << '\n';
3625 }
3626
3627 // 5. This entry's language-specific data area.
3628 if (Entry.LSDAReloc.getObjectFile()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003629 outs() << " LSDA: " << format("0x%" PRIx64,
3630 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00003631 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3632 outs() << '\n';
3633 }
3634 }
3635}
3636
Tim Northover39c70bb2014-08-12 11:52:59 +00003637//===----------------------------------------------------------------------===//
3638// __unwind_info section dumping
3639//===----------------------------------------------------------------------===//
3640
3641static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3642 const char *Pos = PageStart;
3643 uint32_t Kind = readNext<uint32_t>(Pos);
3644 (void)Kind;
3645 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3646
3647 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3648 uint16_t NumEntries = readNext<uint16_t>(Pos);
3649
3650 Pos = PageStart + EntriesStart;
3651 for (unsigned i = 0; i < NumEntries; ++i) {
3652 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3653 uint32_t Encoding = readNext<uint32_t>(Pos);
3654
3655 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003656 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3657 << ", "
3658 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003659 }
3660}
3661
3662static void printCompressedSecondLevelUnwindPage(
3663 const char *PageStart, uint32_t FunctionBase,
3664 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3665 const char *Pos = PageStart;
3666 uint32_t Kind = readNext<uint32_t>(Pos);
3667 (void)Kind;
3668 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3669
3670 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3671 uint16_t NumEntries = readNext<uint16_t>(Pos);
3672
3673 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3674 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00003675 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3676 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00003677
3678 Pos = PageStart + EntriesStart;
3679 for (unsigned i = 0; i < NumEntries; ++i) {
3680 uint32_t Entry = readNext<uint32_t>(Pos);
3681 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3682 uint32_t EncodingIdx = Entry >> 24;
3683
3684 uint32_t Encoding;
3685 if (EncodingIdx < CommonEncodings.size())
3686 Encoding = CommonEncodings[EncodingIdx];
3687 else
3688 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3689
3690 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003691 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3692 << ", "
3693 << "encoding[" << EncodingIdx
3694 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003695 }
3696}
3697
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003698static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3699 std::map<uint64_t, SymbolRef> &Symbols,
3700 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00003701
3702 assert(Obj->isLittleEndian() &&
3703 "There should not be a big-endian .o with __unwind_info");
3704
3705 outs() << "Contents of __unwind_info section:\n";
3706
3707 StringRef Contents;
3708 UnwindInfo.getContents(Contents);
3709 const char *Pos = Contents.data();
3710
3711 //===----------------------------------
3712 // Section header
3713 //===----------------------------------
3714
3715 uint32_t Version = readNext<uint32_t>(Pos);
3716 outs() << " Version: "
3717 << format("0x%" PRIx32, Version) << '\n';
3718 assert(Version == 1 && "only understand version 1");
3719
3720 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3721 outs() << " Common encodings array section offset: "
3722 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3723 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3724 outs() << " Number of common encodings in array: "
3725 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3726
3727 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3728 outs() << " Personality function array section offset: "
3729 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3730 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3731 outs() << " Number of personality functions in array: "
3732 << format("0x%" PRIx32, NumPersonalities) << '\n';
3733
3734 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3735 outs() << " Index array section offset: "
3736 << format("0x%" PRIx32, IndicesStart) << '\n';
3737 uint32_t NumIndices = readNext<uint32_t>(Pos);
3738 outs() << " Number of indices in array: "
3739 << format("0x%" PRIx32, NumIndices) << '\n';
3740
3741 //===----------------------------------
3742 // A shared list of common encodings
3743 //===----------------------------------
3744
3745 // These occupy indices in the range [0, N] whenever an encoding is referenced
3746 // from a compressed 2nd level index table. In practice the linker only
3747 // creates ~128 of these, so that indices are available to embed encodings in
3748 // the 2nd level index.
3749
3750 SmallVector<uint32_t, 64> CommonEncodings;
3751 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3752 Pos = Contents.data() + CommonEncodingsStart;
3753 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3754 uint32_t Encoding = readNext<uint32_t>(Pos);
3755 CommonEncodings.push_back(Encoding);
3756
3757 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3758 << '\n';
3759 }
3760
Tim Northover39c70bb2014-08-12 11:52:59 +00003761 //===----------------------------------
3762 // Personality functions used in this executable
3763 //===----------------------------------
3764
3765 // There should be only a handful of these (one per source language,
3766 // roughly). Particularly since they only get 2 bits in the compact encoding.
3767
3768 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3769 Pos = Contents.data() + PersonalitiesStart;
3770 for (unsigned i = 0; i < NumPersonalities; ++i) {
3771 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3772 outs() << " personality[" << i + 1
3773 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3774 }
3775
3776 //===----------------------------------
3777 // The level 1 index entries
3778 //===----------------------------------
3779
3780 // These specify an approximate place to start searching for the more detailed
3781 // information, sorted by PC.
3782
3783 struct IndexEntry {
3784 uint32_t FunctionOffset;
3785 uint32_t SecondLevelPageStart;
3786 uint32_t LSDAStart;
3787 };
3788
3789 SmallVector<IndexEntry, 4> IndexEntries;
3790
3791 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3792 Pos = Contents.data() + IndicesStart;
3793 for (unsigned i = 0; i < NumIndices; ++i) {
3794 IndexEntry Entry;
3795
3796 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3797 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3798 Entry.LSDAStart = readNext<uint32_t>(Pos);
3799 IndexEntries.push_back(Entry);
3800
3801 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003802 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3803 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00003804 << "2nd level page offset="
3805 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003806 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003807 }
3808
Tim Northover39c70bb2014-08-12 11:52:59 +00003809 //===----------------------------------
3810 // Next come the LSDA tables
3811 //===----------------------------------
3812
3813 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3814 // the first top-level index's LSDAOffset to the last (sentinel).
3815
3816 outs() << " LSDA descriptors:\n";
3817 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3818 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3819 (2 * sizeof(uint32_t));
3820 for (int i = 0; i < NumLSDAs; ++i) {
3821 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3822 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3823 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003824 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3825 << ", "
3826 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003827 }
3828
3829 //===----------------------------------
3830 // Finally, the 2nd level indices
3831 //===----------------------------------
3832
3833 // Generally these are 4K in size, and have 2 possible forms:
3834 // + Regular stores up to 511 entries with disparate encodings
3835 // + Compressed stores up to 1021 entries if few enough compact encoding
3836 // values are used.
3837 outs() << " Second level indices:\n";
3838 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3839 // The final sentinel top-level index has no associated 2nd level page
3840 if (IndexEntries[i].SecondLevelPageStart == 0)
3841 break;
3842
3843 outs() << " Second level index[" << i << "]: "
3844 << "offset in section="
3845 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3846 << ", "
3847 << "base function offset="
3848 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3849
3850 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00003851 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00003852 if (Kind == 2)
3853 printRegularSecondLevelUnwindPage(Pos);
3854 else if (Kind == 3)
3855 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3856 CommonEncodings);
3857 else
3858 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00003859 }
3860}
3861
Tim Northover4bd286a2014-08-01 13:07:19 +00003862void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3863 std::map<uint64_t, SymbolRef> Symbols;
3864 for (const SymbolRef &SymRef : Obj->symbols()) {
3865 // Discard any undefined or absolute symbols. They're not going to take part
3866 // in the convenience lookup for unwind info and just take up resources.
3867 section_iterator Section = Obj->section_end();
3868 SymRef.getSection(Section);
3869 if (Section == Obj->section_end())
3870 continue;
3871
3872 uint64_t Addr;
3873 SymRef.getAddress(Addr);
3874 Symbols.insert(std::make_pair(Addr, SymRef));
3875 }
3876
3877 for (const SectionRef &Section : Obj->sections()) {
3878 StringRef SectName;
3879 Section.getName(SectName);
3880 if (SectName == "__compact_unwind")
3881 printMachOCompactUnwindSection(Obj, Symbols, Section);
3882 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00003883 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00003884 else if (SectName == "__eh_frame")
3885 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00003886 }
3887}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003888
3889static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3890 uint32_t cpusubtype, uint32_t filetype,
3891 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3892 bool verbose) {
3893 outs() << "Mach header\n";
3894 outs() << " magic cputype cpusubtype caps filetype ncmds "
3895 "sizeofcmds flags\n";
3896 if (verbose) {
3897 if (magic == MachO::MH_MAGIC)
3898 outs() << " MH_MAGIC";
3899 else if (magic == MachO::MH_MAGIC_64)
3900 outs() << "MH_MAGIC_64";
3901 else
3902 outs() << format(" 0x%08" PRIx32, magic);
3903 switch (cputype) {
3904 case MachO::CPU_TYPE_I386:
3905 outs() << " I386";
3906 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3907 case MachO::CPU_SUBTYPE_I386_ALL:
3908 outs() << " ALL";
3909 break;
3910 default:
3911 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3912 break;
3913 }
3914 break;
3915 case MachO::CPU_TYPE_X86_64:
3916 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00003917 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3918 case MachO::CPU_SUBTYPE_X86_64_ALL:
3919 outs() << " ALL";
3920 break;
3921 case MachO::CPU_SUBTYPE_X86_64_H:
3922 outs() << " Haswell";
3923 break;
3924 default:
3925 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3926 break;
3927 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003928 break;
3929 case MachO::CPU_TYPE_ARM:
3930 outs() << " ARM";
3931 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3932 case MachO::CPU_SUBTYPE_ARM_ALL:
3933 outs() << " ALL";
3934 break;
3935 case MachO::CPU_SUBTYPE_ARM_V4T:
3936 outs() << " V4T";
3937 break;
3938 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3939 outs() << " V5TEJ";
3940 break;
3941 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3942 outs() << " XSCALE";
3943 break;
3944 case MachO::CPU_SUBTYPE_ARM_V6:
3945 outs() << " V6";
3946 break;
3947 case MachO::CPU_SUBTYPE_ARM_V6M:
3948 outs() << " V6M";
3949 break;
3950 case MachO::CPU_SUBTYPE_ARM_V7:
3951 outs() << " V7";
3952 break;
3953 case MachO::CPU_SUBTYPE_ARM_V7EM:
3954 outs() << " V7EM";
3955 break;
3956 case MachO::CPU_SUBTYPE_ARM_V7K:
3957 outs() << " V7K";
3958 break;
3959 case MachO::CPU_SUBTYPE_ARM_V7M:
3960 outs() << " V7M";
3961 break;
3962 case MachO::CPU_SUBTYPE_ARM_V7S:
3963 outs() << " V7S";
3964 break;
3965 default:
3966 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3967 break;
3968 }
3969 break;
3970 case MachO::CPU_TYPE_ARM64:
3971 outs() << " ARM64";
3972 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3973 case MachO::CPU_SUBTYPE_ARM64_ALL:
3974 outs() << " ALL";
3975 break;
3976 default:
3977 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3978 break;
3979 }
3980 break;
3981 case MachO::CPU_TYPE_POWERPC:
3982 outs() << " PPC";
3983 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3984 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3985 outs() << " ALL";
3986 break;
3987 default:
3988 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3989 break;
3990 }
3991 break;
3992 case MachO::CPU_TYPE_POWERPC64:
3993 outs() << " PPC64";
3994 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3995 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3996 outs() << " ALL";
3997 break;
3998 default:
3999 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4000 break;
4001 }
4002 break;
4003 }
4004 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004005 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004006 } else {
4007 outs() << format(" 0x%02" PRIx32,
4008 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4009 }
4010 switch (filetype) {
4011 case MachO::MH_OBJECT:
4012 outs() << " OBJECT";
4013 break;
4014 case MachO::MH_EXECUTE:
4015 outs() << " EXECUTE";
4016 break;
4017 case MachO::MH_FVMLIB:
4018 outs() << " FVMLIB";
4019 break;
4020 case MachO::MH_CORE:
4021 outs() << " CORE";
4022 break;
4023 case MachO::MH_PRELOAD:
4024 outs() << " PRELOAD";
4025 break;
4026 case MachO::MH_DYLIB:
4027 outs() << " DYLIB";
4028 break;
4029 case MachO::MH_DYLIB_STUB:
4030 outs() << " DYLIB_STUB";
4031 break;
4032 case MachO::MH_DYLINKER:
4033 outs() << " DYLINKER";
4034 break;
4035 case MachO::MH_BUNDLE:
4036 outs() << " BUNDLE";
4037 break;
4038 case MachO::MH_DSYM:
4039 outs() << " DSYM";
4040 break;
4041 case MachO::MH_KEXT_BUNDLE:
4042 outs() << " KEXTBUNDLE";
4043 break;
4044 default:
4045 outs() << format(" %10u", filetype);
4046 break;
4047 }
4048 outs() << format(" %5u", ncmds);
4049 outs() << format(" %10u", sizeofcmds);
4050 uint32_t f = flags;
4051 if (f & MachO::MH_NOUNDEFS) {
4052 outs() << " NOUNDEFS";
4053 f &= ~MachO::MH_NOUNDEFS;
4054 }
4055 if (f & MachO::MH_INCRLINK) {
4056 outs() << " INCRLINK";
4057 f &= ~MachO::MH_INCRLINK;
4058 }
4059 if (f & MachO::MH_DYLDLINK) {
4060 outs() << " DYLDLINK";
4061 f &= ~MachO::MH_DYLDLINK;
4062 }
4063 if (f & MachO::MH_BINDATLOAD) {
4064 outs() << " BINDATLOAD";
4065 f &= ~MachO::MH_BINDATLOAD;
4066 }
4067 if (f & MachO::MH_PREBOUND) {
4068 outs() << " PREBOUND";
4069 f &= ~MachO::MH_PREBOUND;
4070 }
4071 if (f & MachO::MH_SPLIT_SEGS) {
4072 outs() << " SPLIT_SEGS";
4073 f &= ~MachO::MH_SPLIT_SEGS;
4074 }
4075 if (f & MachO::MH_LAZY_INIT) {
4076 outs() << " LAZY_INIT";
4077 f &= ~MachO::MH_LAZY_INIT;
4078 }
4079 if (f & MachO::MH_TWOLEVEL) {
4080 outs() << " TWOLEVEL";
4081 f &= ~MachO::MH_TWOLEVEL;
4082 }
4083 if (f & MachO::MH_FORCE_FLAT) {
4084 outs() << " FORCE_FLAT";
4085 f &= ~MachO::MH_FORCE_FLAT;
4086 }
4087 if (f & MachO::MH_NOMULTIDEFS) {
4088 outs() << " NOMULTIDEFS";
4089 f &= ~MachO::MH_NOMULTIDEFS;
4090 }
4091 if (f & MachO::MH_NOFIXPREBINDING) {
4092 outs() << " NOFIXPREBINDING";
4093 f &= ~MachO::MH_NOFIXPREBINDING;
4094 }
4095 if (f & MachO::MH_PREBINDABLE) {
4096 outs() << " PREBINDABLE";
4097 f &= ~MachO::MH_PREBINDABLE;
4098 }
4099 if (f & MachO::MH_ALLMODSBOUND) {
4100 outs() << " ALLMODSBOUND";
4101 f &= ~MachO::MH_ALLMODSBOUND;
4102 }
4103 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
4104 outs() << " SUBSECTIONS_VIA_SYMBOLS";
4105 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
4106 }
4107 if (f & MachO::MH_CANONICAL) {
4108 outs() << " CANONICAL";
4109 f &= ~MachO::MH_CANONICAL;
4110 }
4111 if (f & MachO::MH_WEAK_DEFINES) {
4112 outs() << " WEAK_DEFINES";
4113 f &= ~MachO::MH_WEAK_DEFINES;
4114 }
4115 if (f & MachO::MH_BINDS_TO_WEAK) {
4116 outs() << " BINDS_TO_WEAK";
4117 f &= ~MachO::MH_BINDS_TO_WEAK;
4118 }
4119 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
4120 outs() << " ALLOW_STACK_EXECUTION";
4121 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
4122 }
4123 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
4124 outs() << " DEAD_STRIPPABLE_DYLIB";
4125 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
4126 }
4127 if (f & MachO::MH_PIE) {
4128 outs() << " PIE";
4129 f &= ~MachO::MH_PIE;
4130 }
4131 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
4132 outs() << " NO_REEXPORTED_DYLIBS";
4133 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
4134 }
4135 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
4136 outs() << " MH_HAS_TLV_DESCRIPTORS";
4137 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
4138 }
4139 if (f & MachO::MH_NO_HEAP_EXECUTION) {
4140 outs() << " MH_NO_HEAP_EXECUTION";
4141 f &= ~MachO::MH_NO_HEAP_EXECUTION;
4142 }
4143 if (f & MachO::MH_APP_EXTENSION_SAFE) {
4144 outs() << " APP_EXTENSION_SAFE";
4145 f &= ~MachO::MH_APP_EXTENSION_SAFE;
4146 }
4147 if (f != 0 || flags == 0)
4148 outs() << format(" 0x%08" PRIx32, f);
4149 } else {
4150 outs() << format(" 0x%08" PRIx32, magic);
4151 outs() << format(" %7d", cputype);
4152 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4153 outs() << format(" 0x%02" PRIx32,
4154 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4155 outs() << format(" %10u", filetype);
4156 outs() << format(" %5u", ncmds);
4157 outs() << format(" %10u", sizeofcmds);
4158 outs() << format(" 0x%08" PRIx32, flags);
4159 }
4160 outs() << "\n";
4161}
4162
Kevin Enderby956366c2014-08-29 22:30:52 +00004163static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
4164 StringRef SegName, uint64_t vmaddr,
4165 uint64_t vmsize, uint64_t fileoff,
4166 uint64_t filesize, uint32_t maxprot,
4167 uint32_t initprot, uint32_t nsects,
4168 uint32_t flags, uint32_t object_size,
4169 bool verbose) {
4170 uint64_t expected_cmdsize;
4171 if (cmd == MachO::LC_SEGMENT) {
4172 outs() << " cmd LC_SEGMENT\n";
4173 expected_cmdsize = nsects;
4174 expected_cmdsize *= sizeof(struct MachO::section);
4175 expected_cmdsize += sizeof(struct MachO::segment_command);
4176 } else {
4177 outs() << " cmd LC_SEGMENT_64\n";
4178 expected_cmdsize = nsects;
4179 expected_cmdsize *= sizeof(struct MachO::section_64);
4180 expected_cmdsize += sizeof(struct MachO::segment_command_64);
4181 }
4182 outs() << " cmdsize " << cmdsize;
4183 if (cmdsize != expected_cmdsize)
4184 outs() << " Inconsistent size\n";
4185 else
4186 outs() << "\n";
4187 outs() << " segname " << SegName << "\n";
4188 if (cmd == MachO::LC_SEGMENT_64) {
4189 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
4190 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
4191 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00004192 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
4193 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00004194 }
4195 outs() << " fileoff " << fileoff;
4196 if (fileoff > object_size)
4197 outs() << " (past end of file)\n";
4198 else
4199 outs() << "\n";
4200 outs() << " filesize " << filesize;
4201 if (fileoff + filesize > object_size)
4202 outs() << " (past end of file)\n";
4203 else
4204 outs() << "\n";
4205 if (verbose) {
4206 if ((maxprot &
4207 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4208 MachO::VM_PROT_EXECUTE)) != 0)
4209 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
4210 else {
4211 if (maxprot & MachO::VM_PROT_READ)
4212 outs() << " maxprot r";
4213 else
4214 outs() << " maxprot -";
4215 if (maxprot & MachO::VM_PROT_WRITE)
4216 outs() << "w";
4217 else
4218 outs() << "-";
4219 if (maxprot & MachO::VM_PROT_EXECUTE)
4220 outs() << "x\n";
4221 else
4222 outs() << "-\n";
4223 }
4224 if ((initprot &
4225 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4226 MachO::VM_PROT_EXECUTE)) != 0)
4227 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
4228 else {
4229 if (initprot & MachO::VM_PROT_READ)
4230 outs() << " initprot r";
4231 else
4232 outs() << " initprot -";
4233 if (initprot & MachO::VM_PROT_WRITE)
4234 outs() << "w";
4235 else
4236 outs() << "-";
4237 if (initprot & MachO::VM_PROT_EXECUTE)
4238 outs() << "x\n";
4239 else
4240 outs() << "-\n";
4241 }
4242 } else {
4243 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
4244 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
4245 }
4246 outs() << " nsects " << nsects << "\n";
4247 if (verbose) {
4248 outs() << " flags";
4249 if (flags == 0)
4250 outs() << " (none)\n";
4251 else {
4252 if (flags & MachO::SG_HIGHVM) {
4253 outs() << " HIGHVM";
4254 flags &= ~MachO::SG_HIGHVM;
4255 }
4256 if (flags & MachO::SG_FVMLIB) {
4257 outs() << " FVMLIB";
4258 flags &= ~MachO::SG_FVMLIB;
4259 }
4260 if (flags & MachO::SG_NORELOC) {
4261 outs() << " NORELOC";
4262 flags &= ~MachO::SG_NORELOC;
4263 }
4264 if (flags & MachO::SG_PROTECTED_VERSION_1) {
4265 outs() << " PROTECTED_VERSION_1";
4266 flags &= ~MachO::SG_PROTECTED_VERSION_1;
4267 }
4268 if (flags)
4269 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
4270 else
4271 outs() << "\n";
4272 }
4273 } else {
4274 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
4275 }
4276}
4277
4278static void PrintSection(const char *sectname, const char *segname,
4279 uint64_t addr, uint64_t size, uint32_t offset,
4280 uint32_t align, uint32_t reloff, uint32_t nreloc,
4281 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
4282 uint32_t cmd, const char *sg_segname,
4283 uint32_t filetype, uint32_t object_size,
4284 bool verbose) {
4285 outs() << "Section\n";
4286 outs() << " sectname " << format("%.16s\n", sectname);
4287 outs() << " segname " << format("%.16s", segname);
4288 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
4289 outs() << " (does not match segment)\n";
4290 else
4291 outs() << "\n";
4292 if (cmd == MachO::LC_SEGMENT_64) {
4293 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
4294 outs() << " size " << format("0x%016" PRIx64, size);
4295 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00004296 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
4297 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00004298 }
4299 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4300 outs() << " (past end of file)\n";
4301 else
4302 outs() << "\n";
4303 outs() << " offset " << offset;
4304 if (offset > object_size)
4305 outs() << " (past end of file)\n";
4306 else
4307 outs() << "\n";
4308 uint32_t align_shifted = 1 << align;
4309 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
4310 outs() << " reloff " << reloff;
4311 if (reloff > object_size)
4312 outs() << " (past end of file)\n";
4313 else
4314 outs() << "\n";
4315 outs() << " nreloc " << nreloc;
4316 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4317 outs() << " (past end of file)\n";
4318 else
4319 outs() << "\n";
4320 uint32_t section_type = flags & MachO::SECTION_TYPE;
4321 if (verbose) {
4322 outs() << " type";
4323 if (section_type == MachO::S_REGULAR)
4324 outs() << " S_REGULAR\n";
4325 else if (section_type == MachO::S_ZEROFILL)
4326 outs() << " S_ZEROFILL\n";
4327 else if (section_type == MachO::S_CSTRING_LITERALS)
4328 outs() << " S_CSTRING_LITERALS\n";
4329 else if (section_type == MachO::S_4BYTE_LITERALS)
4330 outs() << " S_4BYTE_LITERALS\n";
4331 else if (section_type == MachO::S_8BYTE_LITERALS)
4332 outs() << " S_8BYTE_LITERALS\n";
4333 else if (section_type == MachO::S_16BYTE_LITERALS)
4334 outs() << " S_16BYTE_LITERALS\n";
4335 else if (section_type == MachO::S_LITERAL_POINTERS)
4336 outs() << " S_LITERAL_POINTERS\n";
4337 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4338 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4339 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4340 outs() << " S_LAZY_SYMBOL_POINTERS\n";
4341 else if (section_type == MachO::S_SYMBOL_STUBS)
4342 outs() << " S_SYMBOL_STUBS\n";
4343 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4344 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4345 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4346 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4347 else if (section_type == MachO::S_COALESCED)
4348 outs() << " S_COALESCED\n";
4349 else if (section_type == MachO::S_INTERPOSING)
4350 outs() << " S_INTERPOSING\n";
4351 else if (section_type == MachO::S_DTRACE_DOF)
4352 outs() << " S_DTRACE_DOF\n";
4353 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4354 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4355 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4356 outs() << " S_THREAD_LOCAL_REGULAR\n";
4357 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4358 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4359 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4360 outs() << " S_THREAD_LOCAL_VARIABLES\n";
4361 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4362 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4363 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4364 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4365 else
4366 outs() << format("0x%08" PRIx32, section_type) << "\n";
4367 outs() << "attributes";
4368 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4369 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4370 outs() << " PURE_INSTRUCTIONS";
4371 if (section_attributes & MachO::S_ATTR_NO_TOC)
4372 outs() << " NO_TOC";
4373 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4374 outs() << " STRIP_STATIC_SYMS";
4375 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4376 outs() << " NO_DEAD_STRIP";
4377 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4378 outs() << " LIVE_SUPPORT";
4379 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4380 outs() << " SELF_MODIFYING_CODE";
4381 if (section_attributes & MachO::S_ATTR_DEBUG)
4382 outs() << " DEBUG";
4383 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4384 outs() << " SOME_INSTRUCTIONS";
4385 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4386 outs() << " EXT_RELOC";
4387 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4388 outs() << " LOC_RELOC";
4389 if (section_attributes == 0)
4390 outs() << " (none)";
4391 outs() << "\n";
4392 } else
4393 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
4394 outs() << " reserved1 " << reserved1;
4395 if (section_type == MachO::S_SYMBOL_STUBS ||
4396 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4397 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4398 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4399 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4400 outs() << " (index into indirect symbol table)\n";
4401 else
4402 outs() << "\n";
4403 outs() << " reserved2 " << reserved2;
4404 if (section_type == MachO::S_SYMBOL_STUBS)
4405 outs() << " (size of stubs)\n";
4406 else
4407 outs() << "\n";
4408}
4409
David Majnemer73cc6ff2014-11-13 19:48:56 +00004410static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00004411 uint32_t object_size) {
4412 outs() << " cmd LC_SYMTAB\n";
4413 outs() << " cmdsize " << st.cmdsize;
4414 if (st.cmdsize != sizeof(struct MachO::symtab_command))
4415 outs() << " Incorrect size\n";
4416 else
4417 outs() << "\n";
4418 outs() << " symoff " << st.symoff;
4419 if (st.symoff > object_size)
4420 outs() << " (past end of file)\n";
4421 else
4422 outs() << "\n";
4423 outs() << " nsyms " << st.nsyms;
4424 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00004425 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00004426 big_size = st.nsyms;
4427 big_size *= sizeof(struct MachO::nlist_64);
4428 big_size += st.symoff;
4429 if (big_size > object_size)
4430 outs() << " (past end of file)\n";
4431 else
4432 outs() << "\n";
4433 } else {
4434 big_size = st.nsyms;
4435 big_size *= sizeof(struct MachO::nlist);
4436 big_size += st.symoff;
4437 if (big_size > object_size)
4438 outs() << " (past end of file)\n";
4439 else
4440 outs() << "\n";
4441 }
4442 outs() << " stroff " << st.stroff;
4443 if (st.stroff > object_size)
4444 outs() << " (past end of file)\n";
4445 else
4446 outs() << "\n";
4447 outs() << " strsize " << st.strsize;
4448 big_size = st.stroff;
4449 big_size += st.strsize;
4450 if (big_size > object_size)
4451 outs() << " (past end of file)\n";
4452 else
4453 outs() << "\n";
4454}
4455
4456static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4457 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00004458 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00004459 outs() << " cmd LC_DYSYMTAB\n";
4460 outs() << " cmdsize " << dyst.cmdsize;
4461 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4462 outs() << " Incorrect size\n";
4463 else
4464 outs() << "\n";
4465 outs() << " ilocalsym " << dyst.ilocalsym;
4466 if (dyst.ilocalsym > nsyms)
4467 outs() << " (greater than the number of symbols)\n";
4468 else
4469 outs() << "\n";
4470 outs() << " nlocalsym " << dyst.nlocalsym;
4471 uint64_t big_size;
4472 big_size = dyst.ilocalsym;
4473 big_size += dyst.nlocalsym;
4474 if (big_size > nsyms)
4475 outs() << " (past the end of the symbol table)\n";
4476 else
4477 outs() << "\n";
4478 outs() << " iextdefsym " << dyst.iextdefsym;
4479 if (dyst.iextdefsym > nsyms)
4480 outs() << " (greater than the number of symbols)\n";
4481 else
4482 outs() << "\n";
4483 outs() << " nextdefsym " << dyst.nextdefsym;
4484 big_size = dyst.iextdefsym;
4485 big_size += dyst.nextdefsym;
4486 if (big_size > nsyms)
4487 outs() << " (past the end of the symbol table)\n";
4488 else
4489 outs() << "\n";
4490 outs() << " iundefsym " << dyst.iundefsym;
4491 if (dyst.iundefsym > nsyms)
4492 outs() << " (greater than the number of symbols)\n";
4493 else
4494 outs() << "\n";
4495 outs() << " nundefsym " << dyst.nundefsym;
4496 big_size = dyst.iundefsym;
4497 big_size += dyst.nundefsym;
4498 if (big_size > nsyms)
4499 outs() << " (past the end of the symbol table)\n";
4500 else
4501 outs() << "\n";
4502 outs() << " tocoff " << dyst.tocoff;
4503 if (dyst.tocoff > object_size)
4504 outs() << " (past end of file)\n";
4505 else
4506 outs() << "\n";
4507 outs() << " ntoc " << dyst.ntoc;
4508 big_size = dyst.ntoc;
4509 big_size *= sizeof(struct MachO::dylib_table_of_contents);
4510 big_size += dyst.tocoff;
4511 if (big_size > object_size)
4512 outs() << " (past end of file)\n";
4513 else
4514 outs() << "\n";
4515 outs() << " modtaboff " << dyst.modtaboff;
4516 if (dyst.modtaboff > object_size)
4517 outs() << " (past end of file)\n";
4518 else
4519 outs() << "\n";
4520 outs() << " nmodtab " << dyst.nmodtab;
4521 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00004522 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00004523 modtabend = dyst.nmodtab;
4524 modtabend *= sizeof(struct MachO::dylib_module_64);
4525 modtabend += dyst.modtaboff;
4526 } else {
4527 modtabend = dyst.nmodtab;
4528 modtabend *= sizeof(struct MachO::dylib_module);
4529 modtabend += dyst.modtaboff;
4530 }
4531 if (modtabend > object_size)
4532 outs() << " (past end of file)\n";
4533 else
4534 outs() << "\n";
4535 outs() << " extrefsymoff " << dyst.extrefsymoff;
4536 if (dyst.extrefsymoff > object_size)
4537 outs() << " (past end of file)\n";
4538 else
4539 outs() << "\n";
4540 outs() << " nextrefsyms " << dyst.nextrefsyms;
4541 big_size = dyst.nextrefsyms;
4542 big_size *= sizeof(struct MachO::dylib_reference);
4543 big_size += dyst.extrefsymoff;
4544 if (big_size > object_size)
4545 outs() << " (past end of file)\n";
4546 else
4547 outs() << "\n";
4548 outs() << " indirectsymoff " << dyst.indirectsymoff;
4549 if (dyst.indirectsymoff > object_size)
4550 outs() << " (past end of file)\n";
4551 else
4552 outs() << "\n";
4553 outs() << " nindirectsyms " << dyst.nindirectsyms;
4554 big_size = dyst.nindirectsyms;
4555 big_size *= sizeof(uint32_t);
4556 big_size += dyst.indirectsymoff;
4557 if (big_size > object_size)
4558 outs() << " (past end of file)\n";
4559 else
4560 outs() << "\n";
4561 outs() << " extreloff " << dyst.extreloff;
4562 if (dyst.extreloff > object_size)
4563 outs() << " (past end of file)\n";
4564 else
4565 outs() << "\n";
4566 outs() << " nextrel " << dyst.nextrel;
4567 big_size = dyst.nextrel;
4568 big_size *= sizeof(struct MachO::relocation_info);
4569 big_size += dyst.extreloff;
4570 if (big_size > object_size)
4571 outs() << " (past end of file)\n";
4572 else
4573 outs() << "\n";
4574 outs() << " locreloff " << dyst.locreloff;
4575 if (dyst.locreloff > object_size)
4576 outs() << " (past end of file)\n";
4577 else
4578 outs() << "\n";
4579 outs() << " nlocrel " << dyst.nlocrel;
4580 big_size = dyst.nlocrel;
4581 big_size *= sizeof(struct MachO::relocation_info);
4582 big_size += dyst.locreloff;
4583 if (big_size > object_size)
4584 outs() << " (past end of file)\n";
4585 else
4586 outs() << "\n";
4587}
4588
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004589static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4590 uint32_t object_size) {
4591 if (dc.cmd == MachO::LC_DYLD_INFO)
4592 outs() << " cmd LC_DYLD_INFO\n";
4593 else
4594 outs() << " cmd LC_DYLD_INFO_ONLY\n";
4595 outs() << " cmdsize " << dc.cmdsize;
4596 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4597 outs() << " Incorrect size\n";
4598 else
4599 outs() << "\n";
4600 outs() << " rebase_off " << dc.rebase_off;
4601 if (dc.rebase_off > object_size)
4602 outs() << " (past end of file)\n";
4603 else
4604 outs() << "\n";
4605 outs() << " rebase_size " << dc.rebase_size;
4606 uint64_t big_size;
4607 big_size = dc.rebase_off;
4608 big_size += dc.rebase_size;
4609 if (big_size > object_size)
4610 outs() << " (past end of file)\n";
4611 else
4612 outs() << "\n";
4613 outs() << " bind_off " << dc.bind_off;
4614 if (dc.bind_off > object_size)
4615 outs() << " (past end of file)\n";
4616 else
4617 outs() << "\n";
4618 outs() << " bind_size " << dc.bind_size;
4619 big_size = dc.bind_off;
4620 big_size += dc.bind_size;
4621 if (big_size > object_size)
4622 outs() << " (past end of file)\n";
4623 else
4624 outs() << "\n";
4625 outs() << " weak_bind_off " << dc.weak_bind_off;
4626 if (dc.weak_bind_off > object_size)
4627 outs() << " (past end of file)\n";
4628 else
4629 outs() << "\n";
4630 outs() << " weak_bind_size " << dc.weak_bind_size;
4631 big_size = dc.weak_bind_off;
4632 big_size += dc.weak_bind_size;
4633 if (big_size > object_size)
4634 outs() << " (past end of file)\n";
4635 else
4636 outs() << "\n";
4637 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4638 if (dc.lazy_bind_off > object_size)
4639 outs() << " (past end of file)\n";
4640 else
4641 outs() << "\n";
4642 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4643 big_size = dc.lazy_bind_off;
4644 big_size += dc.lazy_bind_size;
4645 if (big_size > object_size)
4646 outs() << " (past end of file)\n";
4647 else
4648 outs() << "\n";
4649 outs() << " export_off " << dc.export_off;
4650 if (dc.export_off > object_size)
4651 outs() << " (past end of file)\n";
4652 else
4653 outs() << "\n";
4654 outs() << " export_size " << dc.export_size;
4655 big_size = dc.export_off;
4656 big_size += dc.export_size;
4657 if (big_size > object_size)
4658 outs() << " (past end of file)\n";
4659 else
4660 outs() << "\n";
4661}
4662
4663static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4664 const char *Ptr) {
4665 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4666 outs() << " cmd LC_ID_DYLINKER\n";
4667 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4668 outs() << " cmd LC_LOAD_DYLINKER\n";
4669 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4670 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4671 else
4672 outs() << " cmd ?(" << dyld.cmd << ")\n";
4673 outs() << " cmdsize " << dyld.cmdsize;
4674 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4675 outs() << " Incorrect size\n";
4676 else
4677 outs() << "\n";
4678 if (dyld.name >= dyld.cmdsize)
4679 outs() << " name ?(bad offset " << dyld.name << ")\n";
4680 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004681 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004682 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4683 }
4684}
4685
4686static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4687 outs() << " cmd LC_UUID\n";
4688 outs() << " cmdsize " << uuid.cmdsize;
4689 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4690 outs() << " Incorrect size\n";
4691 else
4692 outs() << "\n";
4693 outs() << " uuid ";
4694 outs() << format("%02" PRIX32, uuid.uuid[0]);
4695 outs() << format("%02" PRIX32, uuid.uuid[1]);
4696 outs() << format("%02" PRIX32, uuid.uuid[2]);
4697 outs() << format("%02" PRIX32, uuid.uuid[3]);
4698 outs() << "-";
4699 outs() << format("%02" PRIX32, uuid.uuid[4]);
4700 outs() << format("%02" PRIX32, uuid.uuid[5]);
4701 outs() << "-";
4702 outs() << format("%02" PRIX32, uuid.uuid[6]);
4703 outs() << format("%02" PRIX32, uuid.uuid[7]);
4704 outs() << "-";
4705 outs() << format("%02" PRIX32, uuid.uuid[8]);
4706 outs() << format("%02" PRIX32, uuid.uuid[9]);
4707 outs() << "-";
4708 outs() << format("%02" PRIX32, uuid.uuid[10]);
4709 outs() << format("%02" PRIX32, uuid.uuid[11]);
4710 outs() << format("%02" PRIX32, uuid.uuid[12]);
4711 outs() << format("%02" PRIX32, uuid.uuid[13]);
4712 outs() << format("%02" PRIX32, uuid.uuid[14]);
4713 outs() << format("%02" PRIX32, uuid.uuid[15]);
4714 outs() << "\n";
4715}
4716
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004717static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00004718 outs() << " cmd LC_RPATH\n";
4719 outs() << " cmdsize " << rpath.cmdsize;
4720 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4721 outs() << " Incorrect size\n";
4722 else
4723 outs() << "\n";
4724 if (rpath.path >= rpath.cmdsize)
4725 outs() << " path ?(bad offset " << rpath.path << ")\n";
4726 else {
4727 const char *P = (const char *)(Ptr) + rpath.path;
4728 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4729 }
4730}
4731
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004732static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4733 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4734 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4735 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4736 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4737 else
4738 outs() << " cmd " << vd.cmd << " (?)\n";
4739 outs() << " cmdsize " << vd.cmdsize;
4740 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4741 outs() << " Incorrect size\n";
4742 else
4743 outs() << "\n";
4744 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4745 << ((vd.version >> 8) & 0xff);
4746 if ((vd.version & 0xff) != 0)
4747 outs() << "." << (vd.version & 0xff);
4748 outs() << "\n";
4749 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00004750 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004751 else {
4752 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4753 << ((vd.sdk >> 8) & 0xff);
4754 }
4755 if ((vd.sdk & 0xff) != 0)
4756 outs() << "." << (vd.sdk & 0xff);
4757 outs() << "\n";
4758}
4759
4760static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4761 outs() << " cmd LC_SOURCE_VERSION\n";
4762 outs() << " cmdsize " << sd.cmdsize;
4763 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4764 outs() << " Incorrect size\n";
4765 else
4766 outs() << "\n";
4767 uint64_t a = (sd.version >> 40) & 0xffffff;
4768 uint64_t b = (sd.version >> 30) & 0x3ff;
4769 uint64_t c = (sd.version >> 20) & 0x3ff;
4770 uint64_t d = (sd.version >> 10) & 0x3ff;
4771 uint64_t e = sd.version & 0x3ff;
4772 outs() << " version " << a << "." << b;
4773 if (e != 0)
4774 outs() << "." << c << "." << d << "." << e;
4775 else if (d != 0)
4776 outs() << "." << c << "." << d;
4777 else if (c != 0)
4778 outs() << "." << c;
4779 outs() << "\n";
4780}
4781
4782static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4783 outs() << " cmd LC_MAIN\n";
4784 outs() << " cmdsize " << ep.cmdsize;
4785 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4786 outs() << " Incorrect size\n";
4787 else
4788 outs() << "\n";
4789 outs() << " entryoff " << ep.entryoff << "\n";
4790 outs() << " stacksize " << ep.stacksize << "\n";
4791}
4792
Kevin Enderby0804f4672014-12-16 23:25:52 +00004793static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4794 uint32_t object_size) {
4795 outs() << " cmd LC_ENCRYPTION_INFO\n";
4796 outs() << " cmdsize " << ec.cmdsize;
4797 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4798 outs() << " Incorrect size\n";
4799 else
4800 outs() << "\n";
4801 outs() << " cryptoff " << ec.cryptoff;
4802 if (ec.cryptoff > object_size)
4803 outs() << " (past end of file)\n";
4804 else
4805 outs() << "\n";
4806 outs() << " cryptsize " << ec.cryptsize;
4807 if (ec.cryptsize > object_size)
4808 outs() << " (past end of file)\n";
4809 else
4810 outs() << "\n";
4811 outs() << " cryptid " << ec.cryptid << "\n";
4812}
4813
Kevin Enderby57538292014-12-17 01:01:30 +00004814static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004815 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00004816 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4817 outs() << " cmdsize " << ec.cmdsize;
4818 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4819 outs() << " Incorrect size\n";
4820 else
4821 outs() << "\n";
4822 outs() << " cryptoff " << ec.cryptoff;
4823 if (ec.cryptoff > object_size)
4824 outs() << " (past end of file)\n";
4825 else
4826 outs() << "\n";
4827 outs() << " cryptsize " << ec.cryptsize;
4828 if (ec.cryptsize > object_size)
4829 outs() << " (past end of file)\n";
4830 else
4831 outs() << "\n";
4832 outs() << " cryptid " << ec.cryptid << "\n";
4833 outs() << " pad " << ec.pad << "\n";
4834}
4835
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004836static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4837 const char *Ptr) {
4838 outs() << " cmd LC_LINKER_OPTION\n";
4839 outs() << " cmdsize " << lo.cmdsize;
4840 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4841 outs() << " Incorrect size\n";
4842 else
4843 outs() << "\n";
4844 outs() << " count " << lo.count << "\n";
4845 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4846 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4847 uint32_t i = 0;
4848 while (left > 0) {
4849 while (*string == '\0' && left > 0) {
4850 string++;
4851 left--;
4852 }
4853 if (left > 0) {
4854 i++;
4855 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00004856 uint32_t NullPos = StringRef(string, left).find('\0');
4857 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004858 string += len;
4859 left -= len;
4860 }
4861 }
4862 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004863 outs() << " count " << lo.count << " does not match number of strings "
4864 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004865}
4866
Kevin Enderbyb4b79312014-12-18 19:24:35 +00004867static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4868 const char *Ptr) {
4869 outs() << " cmd LC_SUB_FRAMEWORK\n";
4870 outs() << " cmdsize " << sub.cmdsize;
4871 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4872 outs() << " Incorrect size\n";
4873 else
4874 outs() << "\n";
4875 if (sub.umbrella < sub.cmdsize) {
4876 const char *P = Ptr + sub.umbrella;
4877 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4878 } else {
4879 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4880 }
4881}
4882
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00004883static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4884 const char *Ptr) {
4885 outs() << " cmd LC_SUB_UMBRELLA\n";
4886 outs() << " cmdsize " << sub.cmdsize;
4887 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4888 outs() << " Incorrect size\n";
4889 else
4890 outs() << "\n";
4891 if (sub.sub_umbrella < sub.cmdsize) {
4892 const char *P = Ptr + sub.sub_umbrella;
4893 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4894 } else {
4895 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4896 }
4897}
4898
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004899static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004900 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004901 outs() << " cmd LC_SUB_LIBRARY\n";
4902 outs() << " cmdsize " << sub.cmdsize;
4903 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4904 outs() << " Incorrect size\n";
4905 else
4906 outs() << "\n";
4907 if (sub.sub_library < sub.cmdsize) {
4908 const char *P = Ptr + sub.sub_library;
4909 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4910 } else {
4911 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4912 }
4913}
4914
Kevin Enderby186eac32014-12-19 21:06:24 +00004915static void PrintSubClientCommand(MachO::sub_client_command sub,
4916 const char *Ptr) {
4917 outs() << " cmd LC_SUB_CLIENT\n";
4918 outs() << " cmdsize " << sub.cmdsize;
4919 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4920 outs() << " Incorrect size\n";
4921 else
4922 outs() << "\n";
4923 if (sub.client < sub.cmdsize) {
4924 const char *P = Ptr + sub.client;
4925 outs() << " client " << P << " (offset " << sub.client << ")\n";
4926 } else {
4927 outs() << " client ?(bad offset " << sub.client << ")\n";
4928 }
4929}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004930
Kevin Enderby52e4ce42014-12-19 22:25:22 +00004931static void PrintRoutinesCommand(MachO::routines_command r) {
4932 outs() << " cmd LC_ROUTINES\n";
4933 outs() << " cmdsize " << r.cmdsize;
4934 if (r.cmdsize != sizeof(struct MachO::routines_command))
4935 outs() << " Incorrect size\n";
4936 else
4937 outs() << "\n";
4938 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4939 outs() << " init_module " << r.init_module << "\n";
4940 outs() << " reserved1 " << r.reserved1 << "\n";
4941 outs() << " reserved2 " << r.reserved2 << "\n";
4942 outs() << " reserved3 " << r.reserved3 << "\n";
4943 outs() << " reserved4 " << r.reserved4 << "\n";
4944 outs() << " reserved5 " << r.reserved5 << "\n";
4945 outs() << " reserved6 " << r.reserved6 << "\n";
4946}
4947
4948static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4949 outs() << " cmd LC_ROUTINES_64\n";
4950 outs() << " cmdsize " << r.cmdsize;
4951 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4952 outs() << " Incorrect size\n";
4953 else
4954 outs() << "\n";
4955 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4956 outs() << " init_module " << r.init_module << "\n";
4957 outs() << " reserved1 " << r.reserved1 << "\n";
4958 outs() << " reserved2 " << r.reserved2 << "\n";
4959 outs() << " reserved3 " << r.reserved3 << "\n";
4960 outs() << " reserved4 " << r.reserved4 << "\n";
4961 outs() << " reserved5 " << r.reserved5 << "\n";
4962 outs() << " reserved6 " << r.reserved6 << "\n";
4963}
4964
Kevin Enderby48ef5342014-12-23 22:56:39 +00004965static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4966 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4967 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4968 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4969 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4970 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4971 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4972 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4973 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4974 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4975 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4976 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4977 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4978 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4979 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4980 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4981 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4982 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4983 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4984 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4985 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4986 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4987}
4988
Kevin Enderby227df342014-12-23 23:43:59 +00004989static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004990 uint32_t f;
4991 outs() << "\t mmst_reg ";
4992 for (f = 0; f < 10; f++)
4993 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4994 outs() << "\n";
4995 outs() << "\t mmst_rsrv ";
4996 for (f = 0; f < 6; f++)
4997 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4998 outs() << "\n";
4999}
5000
Kevin Enderbyaefb0032014-12-24 00:16:51 +00005001static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005002 uint32_t f;
5003 outs() << "\t xmm_reg ";
5004 for (f = 0; f < 16; f++)
5005 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
5006 outs() << "\n";
5007}
5008
5009static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
5010 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
5011 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
5012 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
5013 outs() << " denorm " << fpu.fpu_fcw.denorm;
5014 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
5015 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
5016 outs() << " undfl " << fpu.fpu_fcw.undfl;
5017 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
5018 outs() << "\t\t pc ";
5019 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
5020 outs() << "FP_PREC_24B ";
5021 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
5022 outs() << "FP_PREC_53B ";
5023 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
5024 outs() << "FP_PREC_64B ";
5025 else
5026 outs() << fpu.fpu_fcw.pc << " ";
5027 outs() << "rc ";
5028 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
5029 outs() << "FP_RND_NEAR ";
5030 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
5031 outs() << "FP_RND_DOWN ";
5032 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
5033 outs() << "FP_RND_UP ";
5034 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005035 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005036 outs() << "\n";
5037 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
5038 outs() << " denorm " << fpu.fpu_fsw.denorm;
5039 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
5040 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
5041 outs() << " undfl " << fpu.fpu_fsw.undfl;
5042 outs() << " precis " << fpu.fpu_fsw.precis;
5043 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
5044 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
5045 outs() << " c0 " << fpu.fpu_fsw.c0;
5046 outs() << " c1 " << fpu.fpu_fsw.c1;
5047 outs() << " c2 " << fpu.fpu_fsw.c2;
5048 outs() << " tos " << fpu.fpu_fsw.tos;
5049 outs() << " c3 " << fpu.fpu_fsw.c3;
5050 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
5051 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
5052 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
5053 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
5054 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
5055 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
5056 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
5057 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
5058 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
5059 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
5060 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
5061 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
5062 outs() << "\n";
5063 outs() << "\t fpu_stmm0:\n";
5064 Print_mmst_reg(fpu.fpu_stmm0);
5065 outs() << "\t fpu_stmm1:\n";
5066 Print_mmst_reg(fpu.fpu_stmm1);
5067 outs() << "\t fpu_stmm2:\n";
5068 Print_mmst_reg(fpu.fpu_stmm2);
5069 outs() << "\t fpu_stmm3:\n";
5070 Print_mmst_reg(fpu.fpu_stmm3);
5071 outs() << "\t fpu_stmm4:\n";
5072 Print_mmst_reg(fpu.fpu_stmm4);
5073 outs() << "\t fpu_stmm5:\n";
5074 Print_mmst_reg(fpu.fpu_stmm5);
5075 outs() << "\t fpu_stmm6:\n";
5076 Print_mmst_reg(fpu.fpu_stmm6);
5077 outs() << "\t fpu_stmm7:\n";
5078 Print_mmst_reg(fpu.fpu_stmm7);
5079 outs() << "\t fpu_xmm0:\n";
5080 Print_xmm_reg(fpu.fpu_xmm0);
5081 outs() << "\t fpu_xmm1:\n";
5082 Print_xmm_reg(fpu.fpu_xmm1);
5083 outs() << "\t fpu_xmm2:\n";
5084 Print_xmm_reg(fpu.fpu_xmm2);
5085 outs() << "\t fpu_xmm3:\n";
5086 Print_xmm_reg(fpu.fpu_xmm3);
5087 outs() << "\t fpu_xmm4:\n";
5088 Print_xmm_reg(fpu.fpu_xmm4);
5089 outs() << "\t fpu_xmm5:\n";
5090 Print_xmm_reg(fpu.fpu_xmm5);
5091 outs() << "\t fpu_xmm6:\n";
5092 Print_xmm_reg(fpu.fpu_xmm6);
5093 outs() << "\t fpu_xmm7:\n";
5094 Print_xmm_reg(fpu.fpu_xmm7);
5095 outs() << "\t fpu_xmm8:\n";
5096 Print_xmm_reg(fpu.fpu_xmm8);
5097 outs() << "\t fpu_xmm9:\n";
5098 Print_xmm_reg(fpu.fpu_xmm9);
5099 outs() << "\t fpu_xmm10:\n";
5100 Print_xmm_reg(fpu.fpu_xmm10);
5101 outs() << "\t fpu_xmm11:\n";
5102 Print_xmm_reg(fpu.fpu_xmm11);
5103 outs() << "\t fpu_xmm12:\n";
5104 Print_xmm_reg(fpu.fpu_xmm12);
5105 outs() << "\t fpu_xmm13:\n";
5106 Print_xmm_reg(fpu.fpu_xmm13);
5107 outs() << "\t fpu_xmm14:\n";
5108 Print_xmm_reg(fpu.fpu_xmm14);
5109 outs() << "\t fpu_xmm15:\n";
5110 Print_xmm_reg(fpu.fpu_xmm15);
5111 outs() << "\t fpu_rsrv4:\n";
5112 for (uint32_t f = 0; f < 6; f++) {
5113 outs() << "\t ";
5114 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005115 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005116 outs() << "\n";
5117 }
5118 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
5119 outs() << "\n";
5120}
5121
5122static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
5123 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
5124 outs() << " err " << format("0x%08" PRIx32, exc64.err);
5125 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
5126}
5127
5128static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
5129 bool isLittleEndian, uint32_t cputype) {
5130 if (t.cmd == MachO::LC_THREAD)
5131 outs() << " cmd LC_THREAD\n";
5132 else if (t.cmd == MachO::LC_UNIXTHREAD)
5133 outs() << " cmd LC_UNIXTHREAD\n";
5134 else
5135 outs() << " cmd " << t.cmd << " (unknown)\n";
5136 outs() << " cmdsize " << t.cmdsize;
5137 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
5138 outs() << " Incorrect size\n";
5139 else
5140 outs() << "\n";
5141
5142 const char *begin = Ptr + sizeof(struct MachO::thread_command);
5143 const char *end = Ptr + t.cmdsize;
5144 uint32_t flavor, count, left;
5145 if (cputype == MachO::CPU_TYPE_X86_64) {
5146 while (begin < end) {
5147 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5148 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5149 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005150 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005151 flavor = 0;
5152 begin = end;
5153 }
5154 if (isLittleEndian != sys::IsLittleEndianHost)
5155 sys::swapByteOrder(flavor);
5156 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5157 memcpy((char *)&count, begin, sizeof(uint32_t));
5158 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005159 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005160 count = 0;
5161 begin = end;
5162 }
5163 if (isLittleEndian != sys::IsLittleEndianHost)
5164 sys::swapByteOrder(count);
5165 if (flavor == MachO::x86_THREAD_STATE64) {
5166 outs() << " flavor x86_THREAD_STATE64\n";
5167 if (count == MachO::x86_THREAD_STATE64_COUNT)
5168 outs() << " count x86_THREAD_STATE64_COUNT\n";
5169 else
5170 outs() << " count " << count
5171 << " (not x86_THREAD_STATE64_COUNT)\n";
5172 MachO::x86_thread_state64_t cpu64;
5173 left = end - begin;
5174 if (left >= sizeof(MachO::x86_thread_state64_t)) {
5175 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
5176 begin += sizeof(MachO::x86_thread_state64_t);
5177 } else {
5178 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
5179 memcpy(&cpu64, begin, left);
5180 begin += left;
5181 }
5182 if (isLittleEndian != sys::IsLittleEndianHost)
5183 swapStruct(cpu64);
5184 Print_x86_thread_state64_t(cpu64);
5185 } else if (flavor == MachO::x86_THREAD_STATE) {
5186 outs() << " flavor x86_THREAD_STATE\n";
5187 if (count == MachO::x86_THREAD_STATE_COUNT)
5188 outs() << " count x86_THREAD_STATE_COUNT\n";
5189 else
5190 outs() << " count " << count
5191 << " (not x86_THREAD_STATE_COUNT)\n";
5192 struct MachO::x86_thread_state_t ts;
5193 left = end - begin;
5194 if (left >= sizeof(MachO::x86_thread_state_t)) {
5195 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
5196 begin += sizeof(MachO::x86_thread_state_t);
5197 } else {
5198 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
5199 memcpy(&ts, begin, left);
5200 begin += left;
5201 }
5202 if (isLittleEndian != sys::IsLittleEndianHost)
5203 swapStruct(ts);
5204 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
5205 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
5206 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
5207 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
5208 else
5209 outs() << "tsh.count " << ts.tsh.count
5210 << " (not x86_THREAD_STATE64_COUNT\n";
5211 Print_x86_thread_state64_t(ts.uts.ts64);
5212 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005213 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
5214 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005215 }
5216 } else if (flavor == MachO::x86_FLOAT_STATE) {
5217 outs() << " flavor x86_FLOAT_STATE\n";
5218 if (count == MachO::x86_FLOAT_STATE_COUNT)
5219 outs() << " count x86_FLOAT_STATE_COUNT\n";
5220 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005221 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005222 struct MachO::x86_float_state_t fs;
5223 left = end - begin;
5224 if (left >= sizeof(MachO::x86_float_state_t)) {
5225 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
5226 begin += sizeof(MachO::x86_float_state_t);
5227 } else {
5228 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
5229 memcpy(&fs, begin, left);
5230 begin += left;
5231 }
5232 if (isLittleEndian != sys::IsLittleEndianHost)
5233 swapStruct(fs);
5234 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
5235 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005236 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00005237 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
5238 else
5239 outs() << "fsh.count " << fs.fsh.count
5240 << " (not x86_FLOAT_STATE64_COUNT\n";
5241 Print_x86_float_state_t(fs.ufs.fs64);
5242 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005243 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
5244 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005245 }
5246 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
5247 outs() << " flavor x86_EXCEPTION_STATE\n";
5248 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
5249 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
5250 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005251 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00005252 << " (not x86_EXCEPTION_STATE_COUNT)\n";
5253 struct MachO::x86_exception_state_t es;
5254 left = end - begin;
5255 if (left >= sizeof(MachO::x86_exception_state_t)) {
5256 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
5257 begin += sizeof(MachO::x86_exception_state_t);
5258 } else {
5259 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
5260 memcpy(&es, begin, left);
5261 begin += left;
5262 }
5263 if (isLittleEndian != sys::IsLittleEndianHost)
5264 swapStruct(es);
5265 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
5266 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005267 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00005268 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
5269 else
5270 outs() << "\t esh.count " << es.esh.count
5271 << " (not x86_EXCEPTION_STATE64_COUNT\n";
5272 Print_x86_exception_state_t(es.ues.es64);
5273 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005274 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
5275 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00005276 }
5277 } else {
5278 outs() << " flavor " << flavor << " (unknown)\n";
5279 outs() << " count " << count << "\n";
5280 outs() << " state (unknown)\n";
5281 begin += count * sizeof(uint32_t);
5282 }
5283 }
5284 } else {
5285 while (begin < end) {
5286 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5287 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5288 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005289 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005290 flavor = 0;
5291 begin = end;
5292 }
5293 if (isLittleEndian != sys::IsLittleEndianHost)
5294 sys::swapByteOrder(flavor);
5295 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5296 memcpy((char *)&count, begin, sizeof(uint32_t));
5297 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005298 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00005299 count = 0;
5300 begin = end;
5301 }
5302 if (isLittleEndian != sys::IsLittleEndianHost)
5303 sys::swapByteOrder(count);
5304 outs() << " flavor " << flavor << "\n";
5305 outs() << " count " << count << "\n";
5306 outs() << " state (Unknown cputype/cpusubtype)\n";
5307 begin += count * sizeof(uint32_t);
5308 }
5309 }
5310}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005311
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005312static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5313 if (dl.cmd == MachO::LC_ID_DYLIB)
5314 outs() << " cmd LC_ID_DYLIB\n";
5315 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5316 outs() << " cmd LC_LOAD_DYLIB\n";
5317 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5318 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
5319 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5320 outs() << " cmd LC_REEXPORT_DYLIB\n";
5321 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5322 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
5323 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5324 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
5325 else
5326 outs() << " cmd " << dl.cmd << " (unknown)\n";
5327 outs() << " cmdsize " << dl.cmdsize;
5328 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5329 outs() << " Incorrect size\n";
5330 else
5331 outs() << "\n";
5332 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005333 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005334 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
5335 } else {
5336 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
5337 }
5338 outs() << " time stamp " << dl.dylib.timestamp << " ";
5339 time_t t = dl.dylib.timestamp;
5340 outs() << ctime(&t);
5341 outs() << " current version ";
5342 if (dl.dylib.current_version == 0xffffffff)
5343 outs() << "n/a\n";
5344 else
5345 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5346 << ((dl.dylib.current_version >> 8) & 0xff) << "."
5347 << (dl.dylib.current_version & 0xff) << "\n";
5348 outs() << "compatibility version ";
5349 if (dl.dylib.compatibility_version == 0xffffffff)
5350 outs() << "n/a\n";
5351 else
5352 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5353 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5354 << (dl.dylib.compatibility_version & 0xff) << "\n";
5355}
5356
5357static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5358 uint32_t object_size) {
5359 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5360 outs() << " cmd LC_FUNCTION_STARTS\n";
5361 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5362 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
5363 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5364 outs() << " cmd LC_FUNCTION_STARTS\n";
5365 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5366 outs() << " cmd LC_DATA_IN_CODE\n";
5367 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5368 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
5369 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5370 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
5371 else
5372 outs() << " cmd " << ld.cmd << " (?)\n";
5373 outs() << " cmdsize " << ld.cmdsize;
5374 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5375 outs() << " Incorrect size\n";
5376 else
5377 outs() << "\n";
5378 outs() << " dataoff " << ld.dataoff;
5379 if (ld.dataoff > object_size)
5380 outs() << " (past end of file)\n";
5381 else
5382 outs() << "\n";
5383 outs() << " datasize " << ld.datasize;
5384 uint64_t big_size = ld.dataoff;
5385 big_size += ld.datasize;
5386 if (big_size > object_size)
5387 outs() << " (past end of file)\n";
5388 else
5389 outs() << "\n";
5390}
5391
Kevin Enderby956366c2014-08-29 22:30:52 +00005392static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5393 uint32_t filetype, uint32_t cputype,
5394 bool verbose) {
Filipe Cabecinhase71bd0c2015-01-06 17:08:26 +00005395 if (ncmds == 0)
5396 return;
Kevin Enderby956366c2014-08-29 22:30:52 +00005397 StringRef Buf = Obj->getData();
5398 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5399 for (unsigned i = 0;; ++i) {
5400 outs() << "Load command " << i << "\n";
5401 if (Command.C.cmd == MachO::LC_SEGMENT) {
5402 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5403 const char *sg_segname = SLC.segname;
5404 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5405 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5406 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5407 verbose);
5408 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00005409 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00005410 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5411 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5412 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5413 }
5414 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5415 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5416 const char *sg_segname = SLC_64.segname;
5417 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5418 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5419 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5420 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5421 for (unsigned j = 0; j < SLC_64.nsects; j++) {
5422 MachO::section_64 S_64 = Obj->getSection64(Command, j);
5423 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5424 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5425 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5426 sg_segname, filetype, Buf.size(), verbose);
5427 }
5428 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5429 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00005430 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00005431 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5432 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5433 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00005434 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5435 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005436 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5437 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5438 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5439 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5440 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5441 Command.C.cmd == MachO::LC_ID_DYLINKER ||
5442 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5443 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5444 PrintDyldLoadCommand(Dyld, Command.Ptr);
5445 } else if (Command.C.cmd == MachO::LC_UUID) {
5446 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5447 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00005448 } else if (Command.C.cmd == MachO::LC_RPATH) {
5449 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5450 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00005451 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5452 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005453 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5454 PrintVersionMinLoadCommand(Vd);
5455 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5456 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5457 PrintSourceVersionCommand(Sd);
5458 } else if (Command.C.cmd == MachO::LC_MAIN) {
5459 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5460 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00005461 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005462 MachO::encryption_info_command Ei =
5463 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00005464 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00005465 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005466 MachO::encryption_info_command_64 Ei =
5467 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00005468 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00005469 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00005470 MachO::linker_option_command Lo =
5471 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00005472 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00005473 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5474 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5475 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00005476 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5477 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5478 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00005479 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5480 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5481 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00005482 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5483 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5484 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00005485 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5486 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5487 PrintRoutinesCommand(Rc);
5488 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5489 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5490 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00005491 } else if (Command.C.cmd == MachO::LC_THREAD ||
5492 Command.C.cmd == MachO::LC_UNIXTHREAD) {
5493 MachO::thread_command Tc = Obj->getThreadCommand(Command);
5494 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00005495 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5496 Command.C.cmd == MachO::LC_ID_DYLIB ||
5497 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5498 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5499 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5500 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00005501 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5502 PrintDylibCommand(Dl, Command.Ptr);
5503 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5504 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5505 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5506 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5507 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5508 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5509 MachO::linkedit_data_command Ld =
5510 Obj->getLinkeditDataLoadCommand(Command);
5511 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00005512 } else {
5513 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5514 << ")\n";
5515 outs() << " cmdsize " << Command.C.cmdsize << "\n";
5516 // TODO: get and print the raw bytes of the load command.
5517 }
5518 // TODO: print all the other kinds of load commands.
5519 if (i == ncmds - 1)
5520 break;
5521 else
5522 Command = Obj->getNextLoadCommandInfo(Command);
5523 }
5524}
5525
5526static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5527 uint32_t &filetype, uint32_t &cputype,
5528 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005529 if (Obj->is64Bit()) {
5530 MachO::mach_header_64 H_64;
5531 H_64 = Obj->getHeader64();
5532 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5533 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00005534 ncmds = H_64.ncmds;
5535 filetype = H_64.filetype;
5536 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005537 } else {
5538 MachO::mach_header H;
5539 H = Obj->getHeader();
5540 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5541 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00005542 ncmds = H.ncmds;
5543 filetype = H.filetype;
5544 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005545 }
5546}
5547
5548void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5549 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00005550 uint32_t ncmds = 0;
5551 uint32_t filetype = 0;
5552 uint32_t cputype = 0;
Kevin Enderbyf0640752015-03-13 17:56:32 +00005553 getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
5554 PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00005555}
Nick Kledzikd04bc352014-08-30 00:20:14 +00005556
5557//===----------------------------------------------------------------------===//
5558// export trie dumping
5559//===----------------------------------------------------------------------===//
5560
5561void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005562 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5563 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00005564 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5565 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5566 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5567 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5568 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5569 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5570 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5571 if (ReExport)
5572 outs() << "[re-export] ";
5573 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005574 outs() << format("0x%08llX ",
5575 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005576 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00005577 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005578 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00005579 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00005580 if (WeakDef) {
5581 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005582 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00005583 }
5584 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005585 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00005586 outs() << ", ";
5587 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005588 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00005589 }
5590 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005591 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00005592 outs() << ", ";
5593 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005594 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00005595 }
5596 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005597 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00005598 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005599 outs() << format("resolver=0x%08llX", Entry.other());
5600 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00005601 }
5602 outs() << "]";
5603 }
5604 if (ReExport) {
5605 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005606 int Ordinal = Entry.other() - 1;
5607 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5608 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00005609 outs() << " (from " << DylibName << ")";
5610 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00005611 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00005612 }
5613 outs() << "\n";
5614 }
5615}
Nick Kledzikac431442014-09-12 21:34:15 +00005616
Nick Kledzikac431442014-09-12 21:34:15 +00005617//===----------------------------------------------------------------------===//
5618// rebase table dumping
5619//===----------------------------------------------------------------------===//
5620
5621namespace {
5622class SegInfo {
5623public:
5624 SegInfo(const object::MachOObjectFile *Obj);
5625
5626 StringRef segmentName(uint32_t SegIndex);
5627 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5628 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5629
5630private:
5631 struct SectionInfo {
5632 uint64_t Address;
5633 uint64_t Size;
5634 StringRef SectionName;
5635 StringRef SegmentName;
5636 uint64_t OffsetInSegment;
5637 uint64_t SegmentStartAddress;
5638 uint32_t SegmentIndex;
5639 };
5640 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5641 SmallVector<SectionInfo, 32> Sections;
5642};
5643}
5644
5645SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5646 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00005647 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00005648 StringRef CurSegName;
5649 uint64_t CurSegAddress;
5650 for (const SectionRef &Section : Obj->sections()) {
5651 SectionInfo Info;
5652 if (error(Section.getName(Info.SectionName)))
5653 return;
Rafael Espindola80291272014-10-08 15:28:58 +00005654 Info.Address = Section.getAddress();
5655 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00005656 Info.SegmentName =
5657 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5658 if (!Info.SegmentName.equals(CurSegName)) {
5659 ++CurSegIndex;
5660 CurSegName = Info.SegmentName;
5661 CurSegAddress = Info.Address;
5662 }
5663 Info.SegmentIndex = CurSegIndex - 1;
5664 Info.OffsetInSegment = Info.Address - CurSegAddress;
5665 Info.SegmentStartAddress = CurSegAddress;
5666 Sections.push_back(Info);
5667 }
5668}
5669
5670StringRef SegInfo::segmentName(uint32_t SegIndex) {
5671 for (const SectionInfo &SI : Sections) {
5672 if (SI.SegmentIndex == SegIndex)
5673 return SI.SegmentName;
5674 }
5675 llvm_unreachable("invalid segIndex");
5676}
5677
5678const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5679 uint64_t OffsetInSeg) {
5680 for (const SectionInfo &SI : Sections) {
5681 if (SI.SegmentIndex != SegIndex)
5682 continue;
5683 if (SI.OffsetInSegment > OffsetInSeg)
5684 continue;
5685 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5686 continue;
5687 return SI;
5688 }
5689 llvm_unreachable("segIndex and offset not in any section");
5690}
5691
5692StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5693 return findSection(SegIndex, OffsetInSeg).SectionName;
5694}
5695
5696uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5697 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5698 return SI.SegmentStartAddress + OffsetInSeg;
5699}
5700
5701void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5702 // Build table of sections so names can used in final output.
5703 SegInfo sectionTable(Obj);
5704
5705 outs() << "segment section address type\n";
5706 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5707 uint32_t SegIndex = Entry.segmentIndex();
5708 uint64_t OffsetInSeg = Entry.segmentOffset();
5709 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5710 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5711 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5712
5713 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005714 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5715 SegmentName.str().c_str(), SectionName.str().c_str(),
5716 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00005717 }
5718}
Nick Kledzik56ebef42014-09-16 01:41:51 +00005719
5720static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5721 StringRef DylibName;
5722 switch (Ordinal) {
5723 case MachO::BIND_SPECIAL_DYLIB_SELF:
5724 return "this-image";
5725 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5726 return "main-executable";
5727 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5728 return "flat-namespace";
5729 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00005730 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005731 std::error_code EC =
5732 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00005733 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00005734 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00005735 return DylibName;
5736 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00005737 }
Nick Kledzikabd29872014-09-16 22:03:13 +00005738 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005739}
5740
5741//===----------------------------------------------------------------------===//
5742// bind table dumping
5743//===----------------------------------------------------------------------===//
5744
5745void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5746 // Build table of sections so names can used in final output.
5747 SegInfo sectionTable(Obj);
5748
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005749 outs() << "segment section address type "
5750 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005751 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5752 uint32_t SegIndex = Entry.segmentIndex();
5753 uint64_t OffsetInSeg = Entry.segmentOffset();
5754 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5755 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5756 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5757
5758 // Table lines look like:
5759 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005760 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00005761 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005762 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005763 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005764 << left_justify(SectionName, 18) << " "
5765 << format_hex(Address, 10, true) << " "
5766 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005767 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005768 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005769 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005770 }
5771}
5772
5773//===----------------------------------------------------------------------===//
5774// lazy bind table dumping
5775//===----------------------------------------------------------------------===//
5776
5777void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5778 // Build table of sections so names can used in final output.
5779 SegInfo sectionTable(Obj);
5780
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005781 outs() << "segment section address "
5782 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005783 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5784 uint32_t SegIndex = Entry.segmentIndex();
5785 uint64_t OffsetInSeg = Entry.segmentOffset();
5786 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5787 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5788 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5789
5790 // Table lines look like:
5791 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005792 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005793 << left_justify(SectionName, 18) << " "
5794 << format_hex(Address, 10, true) << " "
5795 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00005796 << Entry.symbolName() << "\n";
5797 }
5798}
5799
Nick Kledzik56ebef42014-09-16 01:41:51 +00005800//===----------------------------------------------------------------------===//
5801// weak bind table dumping
5802//===----------------------------------------------------------------------===//
5803
5804void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5805 // Build table of sections so names can used in final output.
5806 SegInfo sectionTable(Obj);
5807
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005808 outs() << "segment section address "
5809 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005810 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5811 // Strong symbols don't have a location to update.
5812 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005813 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00005814 << Entry.symbolName() << "\n";
5815 continue;
5816 }
5817 uint32_t SegIndex = Entry.segmentIndex();
5818 uint64_t OffsetInSeg = Entry.segmentOffset();
5819 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5820 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5821 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5822
5823 // Table lines look like:
5824 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005825 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005826 << left_justify(SectionName, 18) << " "
5827 << format_hex(Address, 10, true) << " "
5828 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005829 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5830 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005831 }
5832}
5833
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005834// get_dyld_bind_info_symbolname() is used for disassembly and passed an
5835// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5836// information for that address. If the address is found its binding symbol
5837// name is returned. If not nullptr is returned.
5838static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5839 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00005840 if (info->bindtable == nullptr) {
5841 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005842 SegInfo sectionTable(info->O);
5843 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5844 uint32_t SegIndex = Entry.segmentIndex();
5845 uint64_t OffsetInSeg = Entry.segmentOffset();
5846 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5847 const char *SymbolName = nullptr;
5848 StringRef name = Entry.symbolName();
5849 if (!name.empty())
5850 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00005851 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005852 }
5853 }
Kevin Enderby078be602014-10-23 19:53:12 +00005854 for (bind_table_iterator BI = info->bindtable->begin(),
5855 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005856 BI != BE; ++BI) {
5857 uint64_t Address = BI->first;
5858 if (ReferenceValue == Address) {
5859 const char *SymbolName = BI->second;
5860 return SymbolName;
5861 }
5862 }
5863 return nullptr;
5864}